Python

Ace your homework & exams now with Quizwiz!

Operator: += or *=

+= means add the variable to the new definition e.g. name = "Tuan" name = name + "Tiet" name += "Tiet"

Rules and Conventions for Variable naming

1. Must start with a letter or underscore - cannot start with numbers 2. Variables are CASE SENSITIVE 3. Use lowercase and underscores to separate words 4. CamelCase refers to a class 5. Double underscore (e.g. _do_not_touch_) = dunder

Comparisons

== Example: if name == "Jon Snow":

What is the difference between == and is

== checks if the values are the same "is" checks if the values or items are stored in the same place in memory

while loops

A loop that repeats continuously while a condition is truthy

How to print out or output a range?

A range needs to be assigned to a variable, and the variable must be passed to the function list()

What does indexing a string mean?

A string is a line of character texts: e.g., LOL, nice, gg "indexing" refers to allocating EACH character with a number slot. So, an index of "LOL" would allocate L to slot 0, O to slot 1, and L to slot 2 Note: indexing ALWAYS starts at the 0 slot

How to use a while loop to reiterate over a list

By basing the "while" loop based on the number of index in the lists, where index = the number of value slots recall that len() will return the total number of indices in a list e.g. [1,2,3] has 3 indices Example: list = [1,2,3] i = 0 while i < len(list): print(list[i]) i += 1 EXAMPLE 2: while i < len(list): print(f"{i}: {list[i]}") ## basically, you can use f string with lists

Command line: cd

Cd stands for "change director" used for navigating directories. Usage example: cd C:\Users\me Note 1: Use tab to autocomplete a present directory name e.g. Doc [tab] -> Document Note 2: use .. to go back one level in the directory e.g. cd .. will change the directory up one level Note 3: use ~ to move back to home/default directory from any location

Formatting strings or "f strings" whereby it converts any given input into a string

Changing any input into a string is called interpolating: f"text here {int_variable} end" the output will be one whole string Formatting strings = a way to break out of the strings note: old f string method is .format e.g. fruit = "banana" ripeness = "unripe" print("The {} is {}".format(fruit, ripeness)) print("{} left".format(bakery_stock[food]))

How to access a specific slot in an index?

Command: "string_here"[index_number_here] example: "LOL"[0] means return the character at the index slot 0, which will return "L" A common use for accessing specific character is when you want to get first letters of people's name for initials, etc

List Comprehension with conditions

Conditionals can be passed into a list argument example: if, else, for, while, and, or

dictionary methods: .fromkeys

Creates key-value pairs from comma separated values. In other words, this method creates a dictionary NOTE: .fromkeys(a,b) can only contain two variables i.e. pair, where the first variable corresponds to the "key" in the new dictionary. Passed through variables may be a LIST ## useful to set a bunch of keys to a default value, e.g. a syntax: {}.fromkeys('a', 'b') ## the empty {} is now filled to {'a':'b'}

How to check if a list exists

Example 1: if list_var: Example 2: if not list_var: ## where a list is empty

Command line: pwd

Identify the present directory

person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]

If you have a list of pairs, you can very easily turn it into a dictionary using dict() answer = dict(person) another good solution: answer = {k:v for k,v in person} ## So this means that a dictionary comprehension function automatically and by default takes any PAIR data and creates a Key:Value pairing

Index vs indices

Index is a singular term to refer to a specific index or list of a string; indices are plural

Data type: int

Integers = numbers

string_variable_here[-1] returns what value

It will return the LAST character in the string, wherever that last value is example: name = "Tuan" name[-1] returns "n" Note: [-2] will proceed from the 2nd to last

Dictionary

KEY-VALUE pair where a "key" describes the data and the "value" represents the actual data Syntax: {key:value, key2:value2, key3:value3} ## keys are almost always numbers or strings, but values can be anything, including another variable

Command line: ls

Lists the content of the current directory

Strings and double quote vs. single quote

No difference, depends on user's preference, just stay consistent

Difference between list and arrays?

None - they are the same

"None"

None is like True and False, and it means... null. It is used as a "container" for when it is given a value later on, e.g. from a user's input Note: lowercase none will give an error

What is printed out after the following code? nums = range(1,5) print(nums)

Output: range(1,5) This is because printing a range does not print out all the numbers in the range. To print out each numbers, the program must iterate over the range via a loop or a list() to print the numbers

List Comprehension

Python rules for creating lists intelligently. For example, you can create a list by specifying an equation or function that generates your desired list of items/variables s = [x for x in range(1:51) if x%2 == 0] ##the stuff inside the bracket generates a list of even numbers between 0-51 [2, 4, 6, 8, 10, 12, 14, 16, etc] syntax mnemonic: __for___in___

Accessing individual values

Recall that a dictionary consists of a key-value pairing. So to gain access to a value, the corresponding key must be used. Syntax: full_name = {'First':'Tuan', 'Last':'Tiet'} full_name['First'] ## returns the corresponding value 'Tuan'

remove()

Remove the FIRST item from the list whose value is x i.e. this function will search for x, and remove it if found

How to add data to a list: extend()

Same function as append() EXCEPT it can take multiple arguments, and add them to an existing list example: list.extend([5,6,7]) ## will result in list = [1,2,3,4,5,6,7] where [5,6,7] becomes items in list

What is slicing

Slicing is a method to copy a portion of a list syntax: list_name[start_index:end_index:step] ## where step is the interval, can be odd/even/etc ## not all arguments are required ## the start_index is INCLUSIVE ## colon is always needed, at least 1 ## this method only COPIES, it does not remove like pop Slice: end ## end is EXCLUSIVE ## [ :2] means ends at the index of 2, copies all until the index of 2, excluding the item at index 2 Example: full_list = [1,2,3] full_list[1:] ## starts at index 1, returns 2,3 because goes to the end ## if no colon, then only returns the item at the specified start index

Data type: str

Str = strings = a sequence of Unicode characters, e.g. Tuan

What is the data type for input()

String, even if the input is a number This means that the user's input will ALWAYS be a string.

for loops

Syntax: for [variable] in range(x,y) [can be list, or some other iterable object] note: the "variable" now refers to the FIRST item in the iterable object or collection of items i.e. value = 1 in the range 1,8 example: for number in range(1,8): print(number) where number = variable, and the iterable object = range

Dynamic typing

The ability of Python to allow a variable to change its type e.g. from a Bool > string > float etc.

naturally or inherently "falsy" statements

There are 3: - empty strings i.e. when there is no user's input to an input question - 0 - empty objects - None (capital N) Note: all else are inherently "truthy"

How to test for a key or value in a dict

They "key" is to use the in command (pun intended) syntax: key_here in dict_name ## returns false or true to test for a value: value_here in dict_name.values()

join()

This is actually a string method, not a list method, to add a string and join them to items in a list NOTE: this method returns an output that will need to be assigned syntax: add a string, identify the list words = ['coding', 'is', 'fun'] ' '.join(words) # coding is fun ## where the spaces were added between the "items" in the word list

dictionary methods: get **most useful***

This method acts as a search for a key in a dictionary, and returns the corresponding value if present. This method differs from using "in" to search because .get() returns None if nothing is found rather than getting an error

Dictionary methods: .pop() and .popitem()

This method: - receives a key - removes the key and corresponding value from the dictionary - returns the value corresponding to the key .popitem() functions as .pop() but removes an item randomly

Dictionary methods: .update()

This method: - receives a variable (single variable, list, dict, etc) - appends/adds the variable to a 2nd variable - when updating a dict with another dict, .update() may be used to update the values of a similar key Syntax: 1st_dict = {1,2,3,4) 2nd_dict = {5,6,7} 2nd_dict.update(1st_dict) ## 2nd_dict returns {5,6,7,1,2,3,4}

Dictionary comprehension

This syntax performs the same thing as list comp but for automating dicts that will: - iterates over keys by default - to iterate over keys AND values, use .items() ## recall that .items() will convert a dict into a nested list, where each key-value pairing becomes a list, hence iterable Syntax: {__:___for___in___} Example: numbers = dict(first = 1, second = 2) squared = { key: value ** 2 for key,value in numbers.items()}

Data type: Bool

True or False values Note: MUST have the capital T or F to indicate a Bool

Accessing all keys or values in a dictionary

Two syntaxs: .values() and .keys() dict_name.values() ## where you pass on on the the dict_name to .values() ## returns all values in the dict as a LIST syntax: for val in full_name.values(): print(val)

How to test for equality?

Two ways: 1. == 2. is

Command line: mkdir

Use to make a Folder in the present directory Example: mkdir Ramen

iterable object

a collection of data - you need a set of data so that operations can be done multiple times. I

Data type: dict

a collection of key: values {"first_name": "Colt", "last_name": "Steele"}

swapping values

a method to move values within a list to different indices, or swapping with another value within the list Syntax: list[index1], list[index2] = list[index2], list[index1]

Data type: list

an ordered sequence of values of other data types example: [1,2,3] or ["a", "b", "c"] tasks = ["breakfast", "drop off Celine", "gas"] note: CAN PASS VARIABLES INTO LISTS!!! e.g. var1 = 1 var2 = 2 var3 = 3 var_list = [var1, var2, var3] returns a list 1,2,3

Logical operators

and, or, not where not returns True when the opposite of a value is given example: if a and b age = 2 if age > 2 and age < 8 this will return "true" Can make this into a conditional staement

Escape characters

backslashes e.g. \n, and many others \n = newline e.g. new_line = "hi\nthere" note: use \\ to print just \ in a string

dictionary methods: .clear()

clears all keys and values

Command line: echo

full command line to create a file is: echo $null >> name_of_file.py Alternative way to make a file: New-Item - ItemType file dog.txt

What does this return or check: if int ##

if int means if the int variable is TRUTHY, then do this etc it is the same as saying if not int ## if int is falsy, then do this, etc

Conditional Statements

if some condition is True: do something elif some other condition is True: do something else: do this when no conditions are met under if and elif Note: colons are required?

How to get user's input

input() example: name = input("Enter your name here: ") example 2: print("how many km did you walk?") kms = float(input())

How to add data to a list: insert()

insert() an item at a given position syntax: insert(index_here, value_insert_here) example: first_list = [1,2,3,4] first_list.insert(2, "hi'!") ## first_list [1,2,"hi!", 3, 4], where "hi" is at the 3rd spot because list spot starts at 0

modifying portions of lists

list[:::] = [a,b,c]

how to print out nested lists

nested_lists = [[1,2],[3,4],[5,6]] for 1 in nested_lists: for val in 1: print(val) ## 2 for loops required to iterate the outer list and the nested list

Converting data types formula

new_data_type = new_data_type_FUNCTION(Old_data_type_variable) You use a function to convert the old type to the new type, then assigns that new type to a new variable example: decimal = 1.234 integer = int(decimal) # this int() function will convert decimal into an integer, then assigns that integer to the new variable "integer" NOTE: int() DOES NOT ROUND, only chops off the decimal!! NOTE2: when converting ints to strings, the numbers will be placed in quotes ""

dictionary methods: .copy()

new_variable = dict_here.copy() ## new_variable and dict_here have identical keys and values BUT they are distinct objects existing at different memory slots

list comprehension with nested lists

recall that list comprehension syntax: ___for___in___ nested list comprehension [list comprehension for the nested list] for ___ in *_____ ## *______ refers to the outer list

index()

returns the index of the specified item in the list i.e. instead of returning an item in a list, this function returns the index (i.e. the memory location slot of that item) example: first_list = [1,2,3] first_list.index(1) ## returns 0 where 0 is the index that contains the item "1" syntax 2: search, start index index(item_to_be_searched, starting index_here) Example: first_list.index(3,1) # will search for 3 AFTER index 1 ## this is useful if you want to SKIP indices so that the search excludes those indices syntax 3: search, start, end indices index(x, #, #)

count()

returns the number of times x appears in a list

reverse()

reverse the elements of the list (in-place) first_list = [1,2,3] first_list.reverse() ## [3,2,1]

round()

round a float: round(variable, # of decimal places to round)

sort()

sort the items of the list #by default, sorts by ascending order example: first_list = [3,2,1] first_list.sort() ## [1,2,3]

String Concatenation

strings can be added Note: NO space will be automatically added NOTE: cannot add different variable types

How to check if a Value is in a List

syntax: "value" in list_var e.g. 1 in tasks returns True or False

How to add data to a list: append()

syntax: list_here.append(item_to_be_added) ## the item will be added to the end of the list example: list = [1,2,3] list.append(4) print(list) ## (1,2,3,4) Note: append() can only pass a SINGLE VALUE, ie it can only take "one argument", even if that value is another list, such that a list can be nested in another list example: list.append([4,5,6]) ## will result in list = [1,2,3,[4,5,6]]

list1 = ["CA", "NJ", "RI"] list2 = ["California", "New Jersey", "Rhode Island"] output: {'CA': 'California', 'NJ': 'New Jersey', 'RI': 'Rhode Island'}

syntax: output = {list1[i] : list2[i] for i in range(0,len(list1))}

How to get data out of a list

syntax: list_variable[# of the mem slot to retrieve the data] e.g. tasks = [1,2,3] tasks[0] returns 1 at the 0 slot

Controlled Exit

the command is "break" This command is set within a condition that, once met, will trigger the break command to break out of a loop, such as a while loop

pop()

this function does two things: remove an item at a specified index, and return that item. The return item will need to be assigned to a variable (?) example: fst_list = [1,2,3] fst_list.pop(1) ## will return 2 ## if no index is specified, pop() will remove and return the LAST item in the list

len()

this function: - tells how many items are in a list or a string or iterable items - returns the length of the string or list - super useful as a function to set the run time condition or parameter of a loop so that the function only loops over the length of the item (string, list, etc) list = [1,2] len(list) returns 2 for 2 items in the list list

list()

this is a function to CONVERT a variable into a list e.g. converts a range(5) into a list [0,1,2,3,4] etc tasks = list(range(1,4)) returns 1,2,3

dict()

this is a shortcut way to create a Dictionary's key-value pairing where: Syntax: fullname = dict(first_name = 'Tuan', last_name='Tiet')

IMPORTANT: .items()

this method returns a dictionary as nested lists WHICH IS IMPORTANT because you MUST convert dict to a list to enable iterations via for, if, while loops full_name = {key:value, key2:value2, key3:value3} full_name.items() ## [[key, value], [key2,value2]....] the conditional for loop using items require defining two variables for the key and value respectively for key_var,val_var in full_name.items(): print(key_var, val_var) Example 2: for k, v in full_name.items(): print(f'{k} is {v}')

clear()

this syntax will delete ALL items in a list

nested lists

to access indices of nested lists: nested_lists = [[1,2],[3,4],[5,6]] nested_lists[1][0] ## returns the 2nd list [3,4] and specifically 3 which is in the 0 index slot

Logical operators: not

truthy if the opposite of a is true Example: if not is_weekend Example2: age = 10 not age < 4 returns true Example 3: commonly used when you want "not" to be the condition that triggers something so if not_less than 10 and/or not_greater than 21 (equiv of saying you are between 10-21 since NOT less than 10 and NOT greater than 21) >> then print that you are a teenager

ranges

two syntax: range(x) will start from 0 to x, EXCLUDING X: so if x is 5, then range(5) will give you 0,1,2,3,4 range(1,5) will give the range 1,2,3,4 so inclusive of 1 but still exclusive of y range(1,10,2) where the 3rd number tells how to count, i.e. 1,10,2 = 1,3,5,7,9 Note: always excludes the last number


Related study sets