Python

=Working with variables=

Data Types
Variables can hold data, but not all data is the same. There are different data types explained below.

Check Data Type
There is a python function that returns the data type. Example: print(type("true")) This will print  meaning that the argument was a string.

String
Text Strings can store anything as text. You put the text between single or double quotes. When you want to start a new line you can use the \symbol You can also store long texts with multiple lines and quotes when using a triple quote around the text.

integer
Whole number It has no decimal point and contains all counting numbers (1, 2, 3, …) as well as their negative counterparts and the number 0. If you were counting the number of people in a room, the number of jellybeans in a jar, or the number of keys on a keyboard you would likely use an integer.

float
Decimal number It can be used to represent fractional quantities as well as precise measurements. If you were measuring the length of your bedroom wall or calculating the average test score.

Boolean
True of False The bool type can only have one of two values. True or False. Note that these two words are reserved python words. You can also store boolean values in a variable. You can simply assign True or False, but you can also assign boolean expressions. Example: bool_one = 5 != 7 So now the bool value of True is stored in the bool_one variable.

lists
A list is an ordered set of objects in Python.

create a list
In python a list is defined with the square brackets. Example: myList = [1,2,3] the komma's seperate the different list items. A list doesn't necessarily need to have any items. You can make an empty list like this: my_empty_list = []

create a range
A range is a list of consecutive numbers. Example: list1 = range(9) print (list(list1)) Note that the argument specified in the range function is the last number of the range -1. To print the contents of the l range object you need to convert it to a list first. range(a,b,c) Example: list1 = range(5, 15, 3) print(list(list1))
 * 1) This will print: [0, 1, 2, 3, 4, 5, 6, 7, 8]
 * When using multiple range arguments:
 * a = the starting number of the range
 * b = the end number of the range +1
 * c = the step size of the range
 * 1) This prints: [5, 8, 11, 14]

Lists of Lists
Lists can also contain other lists which are also defined with square brackets. Example: heights = 'Jenny', 61], ['Alexus', 70], ['Sam', 67], ['Grace', 64

Zip
This python command can combine lists and pair the items. Example: names = ['Jenny', 'Alexus', 'Sam', 'Grace'] dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph'] names_and_dogs_names = zip(names,dogs_names) list_of_names_and_dogs_names = list(names_and_dogs_names) print (list_of_names_and_dogs_names) You need to convert the zip back to a list as shown above if you want to see the contents instead of the location in memory.
 * 1) This prints: [('Jenny', 'Elphonse'), ('Alexus', 'Dr. Doggy DDS'), ('Sam', 'Carter'), ('Grace', 'Ralph')]

Growing a List (+)
You can add things to the end of a list using the + symbol. Example: orders = ['daisy', 'buttercup', 'snapdragon', 'gardenia', 'lily'] new_orders = orders + ['lilac', 'iris'] print (new_orders) You can only concatenate lists with other lists so you need to use the square brackets even when you're just adding one item. Example: broken_prices = [5, 3, 4, 5, 4] + [4]
 * 1) This will print: ['daisy', 'buttercup', 'snapdragon', 'gardenia', 'lily', 'lilac', 'iris']

append to a list
You can add items to a list using the append function. Example: myList.append('red') This will add red to the end of the list.

insert in a list
Syntax: list.insert(index position, element) The first argument the index position has to be an integer of the desired list position. In python list positions start at 0! If you want to insert at an index starting at the end you can use negative integers as your index. For example -1 will put the element in the second to last position in the list and -2 will put the element in the third to last position in the list.

remove list element
Syntax: myList.remove('red') this will remove the first instance of 'red' from the list if it is in there.

call a list item
myList = ["red","green","blue"] print myList[1] This will print green. You can also work backwards: myList = ["red","green","blue"] print myList[-1] This will print blue.
 * call one item

slicing
list[first position of the selection (included) : first position out the selection (NOT included)] or list[from this one : to the one before this one] The second index should be the first item that is not in your selection! Example: myList = ["red","green","blue","cyan","magenta","yellow"] print myList[3:5] You can also work backwards: myList = ["red","green","blue","cyan","magenta","yellow"] print myList[-3:-1] You can also use variables and mix negative and positive integers when defining your selection: myList = ["red","green","blue","cyan","magenta","yellow"] myYellow = myList.index("yellow")+1 print myList[-3:myYellow]
 * 1) Result: ['cyan', 'magenta']
 * 1) Result: ['cyan', 'magenta']
 * 1) Result: ['cyan', 'magenta', 'yellow']

call and remove a list item
You can use the pop function to return a list item and remove it from the list. Example: myList.pop(1) This will return and remove the item at index 1

call an index of a list item
Example: print myList.index('blue') This will print the index of where 'blue' is located in the list.

call lenght of the list
Example: print len(myList) This will print the number of items in the list.

Integer to Number
Any number can be converted to an integer number using a python method. Example: print int(4.9) This will print 4 since this method will convert the value the the smallest integer. With this function decimal values will be converted upwards. To use this function you need to import the math module. Example: import math print math.ceil(4.1) This will print 5.0 so still a float value. To round floats up and convert them to integers you need to combine this function with the int(x) function! This function works the same as ceil but converts values downwards.
 * int(x)
 * math.ceil(x)
 * math.floor(x)

Integer to Float
This python function will convert an integer to a float. Example: print float(1) This will print 1.0
 * float(x)

convert to string

 * str(x)

string to number
Strings can be converted to numbers with the int(x) and float(x) note that this will only work if the string only contains numbers. The int(x) in this case can't convert strings holding decimal values.

Create a new variable
To create a variable in python you just type the name of the new variable and assign a value with the =sign. Example: my_name = "Joey Kakbek" print("Hello and welcome " + my_name + "!")

Naming a variable
Variables can't have spaces or symbols in the name. It can't start with a number either, but it can have numbers anywhere else in the name.

Changing a variable
To change a variable you do the same as what you do when making a variable, but using the same name. Example: my_name = "Joey Kakbek" my_name = "Jimmy Raggelklont" Here the same variable is changed to a different string.

=Control Flow= This is the when code is executed based on conditions. With control flow tools the program can flow in a certain direction based on boolean statements.

if
An if statement is a control check that gives a boolean answer to a question. Based on that it will or will not execute specified lines of code. Syntax: if x comparison operator y : operation to perform in case the statement is True Notice the few spaces before the operation to perform. This is called the indentation this is Pythons way of nesting lines of code in a operation.

else
An else statement can execute alternative lines of code when the answer to the if statement is not true. Example: if 3<2: print "yes, it is" else: print "no, it is not"
 * 1) Result: no, it is not

elif
Operation to perform in case the if statement is False and this elif statement is True. When using one or more elif statements note that all statements are checked sequentially when one of the conditions is met none of the following code will be executed! Example: if 3<2: print "yes, it is" elif 3 == 3: print "yes, it is equals to 3" else: print "no, it is not"
 * 1) Result: yes, it is equals to 3

While Loop
Syntax: while x comparison operator y : (indented) operation to perform if the while statement is True, after executing evaluate the 'while' statement again and repeat this process until it is False Example: myVar = 1 while myVar<=5: print myVar myVar +=1 2 3 4 5
 * 1) Result: 1

for ... in Loop
This operation is useful when you want to do an operation on each element of a list. Syntax: for element in list: (indented) the operation that is going to perform for each element in the list, where element is the current item in the list Example: myList = ["red","green","blue"] print myList for i in myList: print i red green blue
 * 1) Result: ['red', 'green', 'blue']

Logical Operators
With these logical operations (also known as boolean operators) you can check multiple statements within one if operation to build larger boolean expressions.

and
Will return true if all statements are true. Example: if 1<2 and 3==3: print "yes, they are both true"
 * 1) Result: yes, they are both true

or
Will return true if one of the statements is true. Example: if 1<2 or 3==4: print "yes, one of them is true"
 * 1) Result: yes, one of them is true

not
This will simply change the result of the expression to the opposite. not True == False not False == True You use this word in the beginning to change the result. >>> not 1 + 1 == 2 False >>> not 7 < 0 True

try/except
Syntax: try: (indented) the operation that is going to try to perform if no error is returned. except ErrorName: (indented) the operation that is going to perform when an error is returned by the try statement. With these two operators you can try to execute code and if it gives an error execute something else. They can't be used singular. The ErrorName can be a keyword to represent a specific error. Keyword examples: Example: myList = ["red","green","blue",1,2.4] for i in myList: try: print i+1 except: print i green blue 2 3.4 So here it will add one and print when it doesn't give a concaternation error (because you can't add a number to a string) and will just print the list item when the try gives an error. When you don't want anything to be executed when the try results in an error you can use the pass keyword (indented). Syntax: except: pass try: code a   except: try: code b       except: pass This assumes that you want to run code b only if code a failed. try: code a except: pass
 * NameError
 * ValueError
 * ZeroDivisionError
 * 1) Result: red
 * pass
 * multiple tries:

try: code b except: pass You need to put it like this if you want to try code b run regardless of code a failing or not.

The in & not in Membership Operators
When working with lists and if statements you can check if something is in a list or not. Example: myList = ["red","green","blue"] if "red" in myList: print "yes, it is in my list" If you want to check if something is not in the list you can use the not in keyword instead of in.
 * 1) Result: yes, it is in my list

Python Comparison Operators
Checks if the value of two operands are equal or not, if yes then condition becomes true. ''('a'=='b') is false Checks if the value of two operands are equal or not, if no then condition becomes true. ''('a'=!'b') is true Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. ''('a'>'b') is false
 * == or the is keyword
 * != or <> or the is not keyword

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. ''('a'<'b') is true Checks if the value of left operand is greater than or equal the value of right operand, if yes then condition becomes true. Note that the =-symbol always has to be at the end! ''('a'>='b') is false Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. ''('a'<='b') is true

Comparing Strings
When comparing strings the is and is not will check if the strings are the same (case sensitive). When looking at larger or smaller then it will look at the first character of the string whether it has a larger of smaller alphabetical index. If those are the same it will look at the second character etc. If all the alphabetical indexes are the same is will look at the string length. Uppercase is always larger then lowercase despite the alphabetical index. Different data types are never equal to each other, when using larger than or smaller than a number is always smaller than a string.

=User Input=

input command
Example: likes_snakes = input("Do you like snakes? ") The following will happen: Example: res = input('What size drink can I get for you? \n[a] Small \n[b] Medium \n[c] Large \n> ') This will store the result in the variable res and look like this: What size drink can I get for you? [a] Small [b] Medium [c] Large >
 * 1) The program would print Do you like snakes? for the user.
 * 2) The user would enter an answer.
 * 3) The answer will be stored in the likes_snakes variable.

=Functions= A function is a collection of several lines of code. By calling a function, we can call all of these lines of code at once, without having to repeat ourselves.

Create a Function
Example: def sing_song: print("You may say I'm a dreamer") print("But I'm not the only one") print("I hope some day you'll join us") print("And the world will be as one")

Call a Function
You can call a functions just by typing it's name with the brackets. It can take attributes between the brackets if needed. Example: sing_song Syntax: functionName
 * Calling a function

moduleName.functionName
 * Calling a function inside a module

Parameters
Parameters created in a function are not accessible outside of the function. The scope of the parameter is the body of the function. Variables declared outside the body of the function can be used within the function. because the scope of that variable is the whole file!

create a parameter
To add a parameter to the function type it within the brackets when defining and then the variable can be called later in the function. An argument is what you put within the brackets when you call a function. The argument will then assigned to the parameter as if the following line would be in the beginning of the function: parameter = argument Syntax for creating a parameter: def mult_two_add_three(number): print(number*2 + 3)

create multiple parameters
You can use multiple parameters in a function when you divide the parameters and the corresponding arguments by komma's. def greet_customer(grocery_store, special_item): print("Welcome to "+ grocery_store + ".") print("Our special is " + special_item + ".") print("Have fun shopping!") greet_customer("Stu's Staples", "papayas")
 * Example creation of a function:
 * Example calling a multi-argument function:

Keyword Arguments
When calling a function you can use positional arguments (so just putting the arguments in divided by komma's and assigned in the same order as the parameters) or keyword arguments. Keyword arguments refer to a specific parameter and not to a position. Example: def greet_customer(grocery_store, special_item): print("Welcome to "+ grocery_store + ".") print("Our special is " + special_item + ".") print("Have fun shopping!") greet_customer(special_item="chips and salsa", grocery_store="Stu's Staples")

Default Arguments
You can also define default values for your parameter this means that it will take that argument when no argument is provided for that parameter. When defining you can't create a parameter with a default value and then one without it has to be the other way around. Example: def greet_customer(special_item="bananas", grocery_store): # this is not valid ...

def greet_customer(special_item, grocery_store="Engrossing Grocers"): # this is valid ...

Return
When there is a result from a function that can be stored in a variable, it is called a returned function value. We use the keyword return to do this. Example using the return keyword: def divide_by_four(input_number): return input_number/4 result = divide_by_four(16) print("16 divided by 4 is " + str(result) + "!") result2 = divide_by_four(result) print(str(result) + " divided by 4 is " + str(result2) + "!") This will print: 16 divided by 4 is 4! 4 divided by 4 is 1! This was returning a number; Example of returning a string: def create_special_string(special_item): return "Our special is " + special_item + "."

special_string = create_special_string("banana yogurt")

print(special_string) This will print: Our special is banana yogurt. Example: def square_point(x_value, y_value): x_2 = x_value * x_value y_2 = y_value * y_value return x_2, y_2 x_squared, y_squared = square_point(1, 3) print(x_squared) print(y_squared) This will print: 1 9
 * Return multiple values

Recursion
Recursion is when a function is called within it's own body. Example: def get_size: res = input('What size drink can I get for you? \n[a] Small \n[b] Medium \n[c] Large \n> ') if res == 'a': return 'small' elif res == 'b': return 'medium' elif res == 'c': return 'large' else: return get_size This will keep asking for an input when an invalid input is given. A data structure typically abstracted away from us that stores function calls in programs. contains the variables within each recursive function call. A line of code where there is no function call It recursively calls the function with an argument which will reach the base case. If a base case is never reached you'll run into a stack overflow
 * call stack:
 * recursive step:
 * execution context:
 * base case:
 * recursive step:

=Python functions=

calculations
Mathematical operations in Python follow the standard mathematical order of operations. Notice that when we perform division, the result has a decimal place. This is because Python converts all ints to floats before performing division. In older versions of Python (2.7 and earlier) this conversion did not happen, and integer division would always round down to the nearest integer.

addition
add values together with the +symbol

subtraction
subtracts values with the -symbol

multiplication
multiplies values with the *symbol

division
divides values with the /symbol

modulo
finds the remainder after division of one number by another with the %symbol

exponents
calculates the first number to the power of the second with the **symbol

print
This command will print something to the console. Example: my_name = "Joey Kakbek" print("Hello and welcome " + my_name + "!")

str
This command can turn data types other than a String into a string. This is helpful when you want to concatenate and integer with a string to print them out in some sort of message for example.

=Debugging= The process of updating the program so that it no longer produces unexpected errors. In python the error will point at the occasion it occurred with a ^symbol.

SyntaxError
This is like a grammar error in the programming language. Generally spelling or a misplaced character.

NameError
occurs when the Python interpreter sees a word it does not recognize. For example, code that contains something that looks like a variable but was never defined will throw a NameError

ZeroDivisionError
Can only happen when using the division operator. This error is raised when the program attempts to divide by 0.

TypeError
This will occur when using the wrong type of data. For example a function that is looking for a string but is given an integer as an argument. Doing data type conversions to make sure everything is getting what it is expecting can be the solution.

OSError
This error is related to OS impossibilities like creating a folder that already exists with the os module.

=Working with Python Modules= Modules are packages with functions that can be imported to python.

Import python module
You can import modules by starting the code with: import module Where module is the name of the module you want to import. import module1, module2, module3 or import module1 import module2 import module3
 * Importing multiple modules:

math
adds:
 * ceil
 * floor

=Notes= a = 1 b = 2 c = 3 d = 4
 * Chaining expression with a transitive relation:

(a < b) and (b < c) and (c < d) # True
 * 1) Original expression

a < b < c < d # True This method can sometimes shorten you code.
 * 1) Using chaining, we can shorten this.
 * 2) This will evaluate to the same result as above

Another example:  elif 5 < rating < 9: This way you can specify a range a variable needs to be in with just one expression.