Cheatography

# Python Cheat Sheet by Pear Tan

### Symbol

 float() number with decimal point str() string int() integer len() the length of the word or string

### Multiply

 string * number Repeat those thing for the number of time string * string Crash! number * number Multiply like in math

### Exponents

 string ** number Crash! number ** number Exponent in Math number ** string Crash!

### Rule for naming the variable

 Rule for naming variab­les # letters # numbers # underscore (_) # can either start with letter or under­­scores ONLY # no space Exam­ple Hello_­­there me2 _mynumber Invalid names # 3my =cannot start with number # last name = no spaces allowed # last­-­­­name = dashes are not accepted

### Define Function

 ``````varl = 1 _varl = 3 _varl + 100 print(_varl) def bacon(): # defines a functio named bacon     print ("hello it's bacon")     print ("line2")     print ("line3")     print ("line4")     print ("line5")     print ("line6")     print ("line7")     return #exit the fuction bacon() bacon() bacon() def myprint (text):     print ("***"+ str(text) +"***")     return myprint(1) myprint("hello") myprint(2.5) def myprintnew (text, decoration):     print (decoration + str(text) + decoration)     return myprintnew (1,"+++") myprintnew ('hello','-=-=-=-=-=-=-=-=') myprintnew (1,"@@@@@@@") def doubleit(number):     return number * 2 print (doubleit(3)) print (doubleit(doubleit(4))) myvar = 12 myvar = doubleit(myvar) myvar = doubleit(myvar) print(myvar) Result 3 hello it's bacon line2 line3 line4 line5 line6 line7 hello it's bacon line2 line3 line4 line5 line6 line7 hello it's bacon line2 line3 line4 line5 line6 line7 1 hello 2.5 +++1+++ -=-=-=-=-=-=-=-=hello-=-=-=-=-=-=-=-= @@@@@@@1@@@@@@@ 6 16 48``````

### Example

 ``````firstname = input("What is your fisrt name?") lastname = input("What is your last name?") fullname = firstname + " " + lastname print(fullname) letternumber = input("What is the letter of number?") letternumber = int(letternumber) if letternumber>len(fullname):     print("Invalid letter number, try again") else:     print(fullname[letternumber])     times = input("How many times to print the letter?")     times = int(times)     if times>100:         print("Too many letters to print")     else:         print(fullname[letternumber]*times) Result What is your fisrt name? Pear What is your last name? Tan  Pear Tan What is the letter of number? 4 r How many times to print the letter? 12 rrrrrrrrrrrr``````

### Example

 ``````mystr = "hello123" numbers = [1,2,3,4,5,6] print (numbers) shoppinglist = ['shoes','bags','pants','shirts'] print (shoppinglist) mixed = [1, 'hello', 2.5, True, False] print (mixed) letter_num = 0 while letter_num < len(mystr):     print (mystr[letter_num])     letter_num = letter_num + 1 for myletterisawesome in mystr:     print(myletterisawesome) for tientien in shoppinglist:     print(tiemtiem) out = 0 for mrtim in shoppinglist:     out = out + 1 Result [1, 2, 3, 4, 5, 6] ['shoe', 'bags', 'pants', 'shirt'] [1, 'Hello', 2.5, True, False]``````

### word per line

 ``````mystr = input(" Please enter your word") letter_num = 0 while letter_num < len(mystr):     print (mystr[letter_num])     letter_num = letter_num + 1 Result Please enter your word1,2,3, 1 , 2 , 3 ,``````

### The area of circle

 ``````while True:     user_radius = input("Enter the radius of the circles")     radius = float(user_radius)     pi = 3.1415     #     answer = pi * (radius**2)     print("The area of the circle is",answer) Result Enter the radius of the circles3 The area of the circle is 28.273500000000002``````

### Palindrome

 ``````word = input("Please enter a string: ") letter_num = 0 reverse = "" while letter_num

### Group work

 ``````""" Group Members: Earn, Pop, Pear Class: 1005 """ import random # create a list mylist = ['earn', 'pear', 'pop', 'jaja', 'roong'] random_item = random.choice(mylist) #print print("mylist:",mylist) # ask the user to input the word chance = 5 score = 0 while chance!= 0:     user_guess = input("Guess a word: ")          if user_guess == random_item:         score = score + 100         print("That's correct!","Score",score)         random_item = random.choice(mylist)             else:         chance = chance - 1         print("Chances Remaining:",chance)                 #check if that word is in the list         if user_guess in mylist:              print ("Sorry, wrong choice")         else:              print("Sorry, that is not even in the list!") if chance == 0:     print(random_item)     print("Final score:",score) Result mylist: ['earn', 'pear', 'pop', 'jaja', 'roong'] Guess a word: pear Chances Remaining: 4 Sorry, wrong choice Guess a word: earn Chances Remaining: 3 Sorry, wrong choice Guess a word: pop Chances Remaining: 2 Sorry, wrong choice Guess a word: jaja Chances Remaining: 1 Sorry, wrong choice Guess a word: roong That's correct! Score 100 Guess a word: jaja Chances Remaining: 0 Sorry, wrong choice pear Final score: 100``````

### Function

 input() inform­ation that receive from user print() show inform­ation in the screen

 string + string combine those strings together string + number program will be crash number + number add together like doing math

### Symbol

 + plus or add - subtract * multiply ** exponent / divide and quotient (result) is float // divide and quotient (result) is integer % remainder (modulo) == equal to != not equal to <= less than or eqaul to < less than > more than >= more than or equal to # one line comment that will not included in the code "­"­" Multi-line comment True or anything Always true False and anything False

### The area of circle 2

 ``````def areaOfCircle (user_radius):     if user_radius<=0:         return "Error: invalid radius"          pi = 3.1415     area = pi*(user_radius**2)     return area user_radius = float(input("Enter the radius: ")) print('The area of the circle is', areaOfCircle(user_radius) Enter the radius: 3 The area of the circle is 28.273500000000002``````

### Meaning of the word

 ``````def printDefinition(word):     # write a definition in your own words for the folllowing words:     # use multi-line strings to print the definition     #variable     if word == "variable":         print("""         A variable is thing that can be changed         """)     elif word == "function":         #function         print ("""         A function is a thing that reuse block or quote.         """)     elif word == "parameter":         #parameter         print("""         A parameter is thing inside blacket of function         """)     elif word == "agument":         #argument         print("""         A argument is the same thing as parameter. It is thinfg inside blacket f function         """)     elif word == "function call":         #function call         print("""         Function is the thing make fuction run.         """)     elif word == "string":         #string         print("""         A string is a list of character         """)     else:         print("unknown word") while True:     word = input ("Enter the word")     printDefinition(word) Result Enter the wordvariable          A variable is thing that can be changed          Enter the wordfunction  A function is a thing that reuse block or quote.          Enter the wordagument  A argument is the same thing as parameter. It is thinfg inside blacket f function         Enter the wordfunction call Function is the thing make fuction run.          Enter the wordstring A string is a list of character         Enter the wordpear unknown word``````

### Count down

 ``````user_number = input("What is the number?" ) number = int(user_number) countdown_string ='' while number > 0:     countdown_string = countdown_string + str(number)     number = number-1 print(countdown_string) Result What is the number? 5 54321``````

### List

 ``````import random # Create a list of integers intlist = [1,2,3,4] random_int = random.choice(intlist) print(intlist,random_int)#print the entire list and the random item # Create a list of floating point numbers fplist=[1.1,2.2,3.3,4.4] random_fp = random.choice(fplist) print(fplist,random_fp) # Create a list of strings strlist=['phone','pencil','computer'] random_str = random.choice(strlist) print(strlist,random_str) mylist = [1,2,3,4,1.1,2.2,3.3,4.4,'phone','pencil','computer'] random_item = random.choice(mylist) print(mylist,random_item) #create a list of follwing veraibles myvar1 = 1 myvar2 = 2 myvar3 = 3 varlist = [myvar1,myvar2,myvar3] random_var = random.choice(varlist) print(varlist,random_var) Result [1, 2, 3, 4] 3 [1.1, 2.2, 3.3, 4.4] 3.3 ['phone', 'pencil', 'computer'] phone [1, 2, 3, 4, 1.1, 2.2, 3.3, 4.4, 'phone', 'pencil', 'computer'] pencil [1, 2, 3] 2``````

### Guess game with random

 ``````import random # create a list mylist = ['lion','cheetah','panther','cougar','leopard'] random_item = random.choice(mylist) print(random_item) #print print(mylist) # ask the user to input the word user_guess = input("Guess a word: ") if user_guess == random_item:     print("Correct") else:          #check if that word is in the list     if user_guess in mylist:         print("Yes, it is in the list")     else:         print("No, it is not in the list")``````

### List

 ``````myself= "hello123" numbers = [1,2,3,4,5,6] print(numbers) shoppinglist = ['shoe','bags','pants','shirt'] print(shoppinglist) mixed=[1,'Hello',2.5, True, False] print(mixed) letter_num = 0 while letter_num < len(mystr):     print (mystr[letter_num])     letter_num = letter_num + 1 for myletterisawesome in mystr:     print(myletterisawesome) for tientien in shoppinglist:     print(opal) shoppinglist. append('ties') print(shoppinglist) out = 0 for mrtim in shoppinglist:     out=out + 1     print(mrtim) print (out) largelist = range(100) for num in largelist:     print(num)``````

### Decision making

 ``````f 3 < 2: #if statement must compare two Booleans    print ('3 is less than2 ') elif 4 < 2: #can have 0 or more elif statements     print ('4 is less than 2') elif 5 < 2:     print ('5 is less than 2') else: #can have 0 or 1 else statement at the end     print ('none of the above are True')``````

### Function

 ``````def nameOfFunction():      print (‘This function has no parameters’)      print (‘This function has no return value’)      return # no value, just exits the function #function call nameOfFunction() #function with 1 parameter/argument def testFunction(param): print (‘This function has 1 parameter’) print (param) #function call testFunction (“this is the parameter value”) #function with 2 parameters and a return value def function3(param1, param2):       print(‘This function has 2 parameters’)       return param1 + param2 # return value #function call and store the result in a variable returnValue = function3(2, 3) print (returnValue)``````

### Determine zero positive and negative

 ``````num = int (input("Enter a number") if num>0:     print (num,"is positive") elif num<0:     print (num,"is negative") else:     print (num,"is zero")``````

### Divisible by 3

 ``````num = int(input(" Enter a word")) remainder = num%3 if remainder ==o:    print(num,"is divisible by 3") else:    print(num,"is not divisible by 3")``````

### Fibonacci fron o to 50

 ``````num1 = 0 num2 = 0 fibonacci = num1+num2 myoutput = "0,1" while fibonacci < 50:           myoutput = myouput + "," + str(fibonacci)           num1=num2           num2 = fibonacci           fibonacci = num1+ num2 print(my output) 0,1,1,2,3,5,8,13,...``````

### Sample

 ``````def test() :     while True:      user_input = input("Please enter a word: ")      if user_input == 'quit':          break     return test()  keep asking word till input quit``````

### Vocabulary

 variable A value or thing that can be changed string A list of character such as letter or symbol boolean True False modulo Find the remainder syntax There are error such as grammar or structure of language float A number with decimal point integer Rounded number which do not have decimal point

### Condition

 while... While this is true loop the command under the condit­­ional while True Forever loop for each item in name of list For every item in the list repeat the command under the loop that many times. (a string is a list too) If...: then... else If the statement in 'if ' is true, it will follow the statement in 'then'. If it is not, it will follow statement under 'else'.

### The largest value

 ``````#write a function that returns the largest of two values #name : max2 #agruments: num1, num2 # return: largest value # write a functrion that returns the largest of three values # name : max3 #agrument: num1, num2, num3 # return: largest value def max2(num1,num2):     if num1 >= num2:         max_value = (num1)     if num2 > num1:         max_value = (num2)     return max_value num1 = input('Enter the the first value') num2 = input('Enter the the second value') print (max2(num1,num2)) def max3(num1,num2,num3):     if num1 >= num2 and num1 >= num3:         max_value = (num1)     if num2 > num1 and num2 >= num3:         max_value = (num2)     if num3 >= num2 and num3 >= num1:         max_value = (num3)              return max_value num3 = input('Enter the the third value') print (max3(num1,num2,num3)) # write a function that returns the largest value # name: maxlist #argument : list #returns the largest value in the list def maxlist(list):     maxvalue = list(0)     for item in list:         if item > maxvalue:             value = item              return maxvalue mylist = [1,2,3,4,55,66,777,0,1] print (maxlist(list))``````

### Area of Triangle & Volume of prism

 ``````# write a function that computes the area of triangle # name : areaOfTriangle # parameters :b,h # return : area def areaOfTriangle(b,h):     if user_base<=0:         return "Error: invalid radius"     if user_height<=0:         return "Error: invalid radius"     area = 0.5 b h     return area user_base =float(input('Enter the base of the triangle:')) user_height = float(input('Enter the height of the triangle: ')) print ('The area of the triangle is',areaOfTriangle(user_base,user_height)) #write a function that computes the volume of a prism # name: volumeOfPrism # parameters :b,h,l # return : volume def volumeOfPrism(b,h,l):     volume = bhl     return volume user_length = float(input('Enter the length of the prism:')) print('The volume of the prism is', volumeOfPrism(user_base,user_height,user_length)) Result Enter the base of the triangle:12 Enter the height of the triangle: 6 The area of the triangle is 36.0 Enter the length of the prism:3 The volume of the prism is 216.0``````

### Useful Function for Name

 ``````mystr = "hello THERE" print (mystr.upper()) > HELLO THERE print (mystr.lower()) > hello there print (mystr.capitalize()) > Hello there print (mystr.title()) > Hello There``````

### How to convert to binary

 ``````user_number = input("Please enter a number") number = int(user_number) binary_string ='' while (number > 0):     remainder= number%2     binary_string = str(remainder) + binary_string     number= number//2      print("Binary string is", binary_string) Result Please enter a number 36 Binary string is 100100``````

### Guess a word

 ``````# create a list mylist = ['lion','cheetah','panther','cougar','leopard'] #print print(mylist) # ask the user to input the word user_guess = input("Guess a word: ") #check if that word is in the list if user_guess in mylist:     print("Yes, it is in the list") else:     print("No, it is not in the list")``````

### Boolean

 ``````print(True) print (2<3) print (2 != 2)``````

### Reverse

 ``````word = input("Please enter a word to reverse: ") letter_num = 0 reverse = "" while letter_num

### Range

 ``````#creates a list of numbers from 0 to the specified number numberlist = range(5) # is the same as creating the following list numberlist2 = [0, 1, 2, 3, 4] for num in range(100):      print (num) # prints all numbers from 0 – 99 for num in range(5, 50):       print(num) #prints all numbers from 5 - 49``````

### For loop with list

 ``````forlist = [3, 4, 5, 2, 1] for item in forlist:       print(item) print all items in the list``````

### While Loop with List:

 ``````thelist = [4, 3, 2, 1, 0] index = 0 # start at the first item while index < len(thelist):          print (thelist[index]) #prints each item          index = index + 1``````

### Lists

 ``````mylist = [2,3,4,5] # create a list #select an item from a list print (mylist) #selects first item and displays 2 # len() determines the length of the list print (len(mylist)) # displays 4 mylist.append(5) # adds an item to the end of the list``````

### Condition while loop

 ``````count = 0 # start at zero while count < 10: # loop while count is less than 10           print(count) #will print numbers 0 - 9           count = count + 1 # must increase count``````

### palindrome

 ``````def palindrome(word):     letter_num = 0     reverse = ""     for letter_num in word:          reverse = letter_num + reverse     if word == reverse:         return True     else:         return False while True:     user_word = input("Please enter a word: ")     if user_word != "quit":         print("This word has",len(user_word),"letters")     if user_word == "quit":          break     if palindrome(user_word) == True:         print(user_word,"is palindrome")     else:         print(user_word,"is not palindrome") Result Please enter a word: 321 This word has 3 letters 321 is not palindrome Please enter a word: 212 This word has 3 letters 212 is palindrome Please enter a word: quit``````

### while loop with counting number

 ``````num = -100 while num< -1:      print(num)      num = num + 2 num = 0 while num< 100:      num = num + 2      print(num)``````

### Example from sheet

 ``````mystring = " " count = 0 while count < 5:       mystring = mystring+ str(count)       print (mystring)       count = count + 1 mystring = " " for num in range(5):       mystring = mystring+ str(count)       print (mystring)g Result 0 01 012 0123 01234``````

### Positive integer count

 ``````evencount = 0 oddcount = 0 while True:          num = int (input("Enter a positive integer"))          if num < 0:                   print ("Even numbers:",evencount)                   print ("Odd numbers:",odd count)                   break          else:                   if (num%2) == 0:                       evencount = evencount + 1                   else:                         oddcount = oddcount + 1 program that repeatedly recieve positive integers from the user. When the user enters a negative integer, exit the loop and print how many of the numbers were odd and even``````