Python Refresh

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Keys in ___ are unique and immutable.

Dictionary

___ items are presented in key:value pairs, and can be referred to by using the key name.

Dictionary

____ is a collection which is ordered*, changeable and do not allow duplicates.

Dictionary

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[:] Result: [0, 1, 2, 3, 4, 5] Explanation: Omitting both start and stop returns the entire list.

Entire List With Full Slice

price = 49 txt = "The price is {} dollars"print(txt.format(price))

Add a placeholder where you want to display the price

Slicing

Allows access to a portion of a sequence type (string, list, tuple).

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[1:4] Result: [1, 2, 3] Explanation: Slices from index 1 up to, but not including, index 4.

Basic Slicing

del p1

Delete objects

del p1.age

Delete properties on objects

Example: my_string = "Hello World" Slicing: my_string[6:11] Result: "World" Explanation: Works the same as list slicing, but with string characters.

Slicing Strings

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[-5:4] Result: [1, 2, 3] Explanation: Combining negative and positive indices in slicing.

Slicing With Negative Start and Positive Stop

Example: my_tuple = (0, 1, 2, 3, 4, 5) Slicing: my_tuple[2:5] Result: (2, 3, 4) Explanation: Tuples can be sliced like lists, but the result is also a tuple.

Slicing With Tuples

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[-4:-1] Result: [2, 3, 4] Explanation: Negative indices count from the end of the list.

Slicing: Negative Indices

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[::-1] Result: [5, 4, 3, 2, 1, 0] Explanation: A negative step reverses the list.

Slicing: Negative Step

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[:3] Result: [0, 1, 2] Explanation: Omitting the start begins the slice from index 0.

Slicing: Omitting Start and Stop

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[3:] Result: [3, 4, 5] Explanation: Omitting the stop extends the slice to the end of the list.

Slicing: Omitting Stop

Example: my_list = [0, 1, 2, 3, 4, 5] Slicing: my_list[1:5:2] Result: [1, 3] Explanation: The step parameter skips elements in the specified range.

Slicing: Step Parameter

continue

Stop the current iteration, and continue with the next

break

Stop the loop even if the while condition is true:

Create a object

p1 = MyClass() print(p1.x)

How to avoid error if class is empty?

pass

Python built-in none type?

NoneType

List Comprehensions

Provide a concise way to create lists

Which set considered 'True/False' and '1/0' respectively, as the same values?

Set

___ is a collection which is unordered, unchangeable*, and unindexed. * Note: ___ items are unchangeable, but you can remove items and add new items.

Set

Which collection data type does not allow duplicates?

Set, Dictionary

x = True

Setting the Data Type: Bool

x = b"Hello"

Setting the Data Type: Bytes

x = bytearray(5)

Setting the Data Type: Bytesarray

x = {"name" : "John", "age" : 36}

Setting the Data Type: Dict

x = ["apple", "banana", "cherry"]

Setting the Data Type: List

x = {"apple", "banana", "cherry"}

Setting the Data Type: Set

x = ("apple", "1", "3.14")

Setting the Data Type: Tuple

iterable[start:stop:step]

Slicing

___ items are ordered, unchangeable, and allow duplicate values.

Tuple

Use ___ for data that shouldn't change through the course of a program.

Tuples

Reverses the order of the list

list.reverse()

Sorts the list

list.sort(reverse=True|False, key=myFunc) * reverse option. True will sort the list descending. Default is reverse=False * key optional. A function to specify the sorting criteria(s)

for x in fruits

loop each elem in list

for x in "banana"

loop through the characters in string

All classes have a function called ____, which is always executed when the class is being initiated.

__init__() function

Use the_____ to assign values to object properties, or other operations that are necessary to do when the object is being created:

__init__() function

class Person: def _____(self, name, age): self.name = name self.age

__init__() function

If the ____ is not set, the string representation of the object is returned:

__str__() function

The _____ controls what should be returned when the class object is represented as a string.

__str__() function

class Person: def __init__(self, name, age): self.name = name self.age = age def _____(self): return f"{self.name}({self.age})"p1 = Person("John", 36)print(p1)

__str__() function

list.append(elmnt)

add an elem to the end of the list.

for x in cars:

'For in' loop to loop through all the elements of an array

What does find() return if value is not found?

-1

x = cars[0]

Get value of first elem in array

x = 5 print(type(x))

Getting the Data Type

Tuple

Immutable sequences, typically used to store collections of heterogeneous data.

"".join(iterable)

Joins the elements of an iterable to the end of the string

___ items are ordered, changeable, and allow duplicate values.

List

[x for x in iterable] or can include conditions: [x for x in iterable if condition]

List Comprehensions

___ are dynamic and can contain mixed data types.

Lists

p1.age = 40

Modify properties on objects

cars[0] = "Toyota"

Modify value of first elem in array

List

Mutable sequences, typically used to store collections of homogeneous items.

Python built-in binary type?

bytes, bytearray, memoryview

Add elem to an array

cars.append("Honda")

Remove elem in array and return it

cars.pop(1) # second elem position

Remove elem in array and do not return in

cars.remove("Volvo") Note: only removes the first occurrence of the specified value.

Create a class

class MyClass: x = 5

Python built-in mapping type?

dict

x = constructor(name = "John", age = 36, country = "Norway") print(x)

dict() constructor

f'Hello, {name}'

formating a string

What is the difference between find() and index()?

index() method raises an exception if the value is not found.

Python built-in numeric type?

int, float, complex

Python built-in sequence type?

list, tuple, range

Removes all the elements from the list

list.clear()

Returns a copy of the list

list.copy()

Returns the number of elements with the specified value

list.count(value)

Add the elements of a list (or any iterable), to the end of the current list

list.extend(iterable)

Returns the index of the first element with the specified value

list.index(elmnt)

Adds an element at the specified position

list.insert(pos, elmnt)

Returns a reversed iterator object.

reversed(sequence)

The ____ parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

self

Python built-in set type?

set, frozenset

Python built-in text type?

str

Method to return the number of times a defined value appears in the string:

string.count(value, start, end) ** value required

Returns true if the string ends with the specified value

string.endswith(value, start, end) * start optional * end optional

Method to find the first occurrence of the specified value.

string.find(value, start, end) ** value required

Converts a string into lower case

string.lower()

Returns a string where a specified value is replaced with a specified value

string.replace(oldvalue, newvalue, count) * old value required * new value required

Splits the string at the specified separator, and returns a list

string.split(separator, maxsplit) * separator optional * maxsplit optional

Splits the string at line breaks and returns a list

string.splitlines(keeplinebreaks) * keeplinebreaks option. default value is false

Returns true if the string starts with the specified value

string.startswith(value, start, end) * start optional * end optional

Returns a trimmed version of the string

string.strip(characters) * characters option

Converts a string into upper case

string.upper()

Dictionary

used to store key-value pairs and are optimized for retrieving data.

How do I create a tuple with one item?

x = ("apple",)


Kaugnay na mga set ng pag-aaral

Strategi - industri, branche og marked

View Set

BIBL 104 Quiz 3 Liberty University

View Set

Christ and the Everlasting Gospel Midterm 1

View Set