Cheatography

Python cheat sheet - Cliff Cheat Sheet by Kawazoe

Function

 print() display given info. input() receives info from user int() converts a value to an integer float() converts a value to a floationg point str() converts a value to a string len() the length of the string == equal to <= less than or equal to >= more than or equal to % Modulo, Find the remainder # Comment, no effect on progra­mming whlie True continues for looping forever if...then "if true" will work, "if false" won't work loop stops // int outcome / float outcome

Multip­lic­ation and Exponent

 string * string Crash string­*number combines the string multiple times number­*number Math - Multiply string­**n­umber Crash number­**n­umber Math - Exponent string­**s­tring Crash

Palindrome

 ``````""" Cliff 1003 """ def isPalindrome (word):         index = 0  # word[0] len(word)-1 -0         numberOfLoops = 0         while index < 1/2*len(word):            numberOfLoops += 1            print('Comparing',word[index] ,word[len(word)-1-index])            if word[index] == word[len(word)-1-index]:                 index = index + 1            else:                 print ('loops:',numberOfLoops)                 return False                             print ('loops:',numberOfLoops)         return True while True:     user_input =input("what is your word? ")     if user_input == "quit":         break     print (len(user_input))     myword = isPalindrome(user_input)     if myword == True:         print ((user_input),"is a palindrome")     else:         print ((user_input),"isn't a palindrome")``````

Max Value in list / Max value

 ``````def max2(num1,num2):     maxvalue = num1     if num2 > maxvalue:         maxvalue = num2     return maxvalue print (max2 (4,3)) print (max2 (3,22)) answer = max2 (1,5) print (answer) def max3(num1,num2,num3):     maxvalue = num1     if num2 > maxvalue:         maxvalue = num2     if num3 > maxvalue:         maxvalue = num3     return maxvalue print (max3 (10,7,8)) print (max3 (7,10,8)) print (max3 (7,8,10)) def maxlist(list):     maxvalue = list[0]     for num in list:         if maxvalue < num:             maxvalue = num     return maxvalue print (maxlist(range(0,101))) mylist = 1,5,76,23,78,34,5678,2,5,8,675,2,6,86,54,23,6,8 print (maxlist(mylist))``````

Randomizer

 ``````import random intlist = [1,2,3,4,5] random_int = random.choice(intlist) print (intlist,random_int) fplist = [2.0,2.1,2.2,2.3,2.4,2.5] random_fp = random.choice(fplist) print (fplist,random_fp) strlist = ['a','b','c','d','e','f'] random_str = random.choice(strlist) print (strlist,random_str) mylist = [1,9.9,"hello"] random_mylist = random.choice(mylist) print (mylist,random_mylist) myvar1 = 1 myvar2 = 2 myvar3 = 3 varlist = [myvar1,myvar2,myvar3] random_var = random.choice(varlist) print (varlist,random_var)``````

commands

 import imports program random given written program random.ch­oice() random items in the list

Vocabulary

 Variable something that can change String a list of characters Print display given info. Syntax Gramma­r/S­tru­cture of language Modulo Find the remainder Boolean True/False

Reverse word

 ``````while True word = input("Please enter a word") index = 0 reverse = "" while int(index) < len(word)     reverse = word[index] + (reverse)     index = int(index) + 1 print ("Reverse: ", reverse)``````

Condit­ionals

 if else if the statement is true then do the command under. Else do command under else elif Similar to if else, but allows more condit­ions. (short abbrev­iation for if else for loop Will loop through every element of the set while loop A loop condition with conditions 1.initial value 2.ending condition 3.update while true While the statement is true keep looping Concat­enation Joins the strings by linking then end to end

Convert into binary

 ``````user_number = "" while user_number != ' 0 ':     user_number = input ("Enter a number to convert into binary")     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)``````

Finding the triangle (area,­volume)

 ``````def areaoftriangle(num1,num2):     area = 1/2num1num2     return area user_base = float(input('what is your base of the triangle; ')) user_height = float(input('what is your height of the triangle; ')) print ('The area of the triangle is: ',areaoftriangle(user_base,user_height)) def volofprism(base,height,prism_height):     volume = areaoftriangle(base,height) * prism_height     return volume user_prism = int(input('Enter the prism height; ')) print ("The volume of the prism is; ", volofprism(user_base,user_height,user_prism))``````

Guessing Game

 ``````import random score = 0 chances = 5 print ("Score:", score) print ("Chances:", chances) mylist = ['apple', 'banana', 'orange', 'mango', 'cherry'] print (mylist) random_item = random.choice(mylist) while chances > 0 :     user_guess = input("Guess a word:")     if user_guess == random_item:         print ("That's correct!")         score = score+100         print ("Score:", score)         print ("Chances:", chances)         random_item = random.choice(mylist)     else:         if user_guess in mylist:             print ("Sorry, wrong choice!")             chances = chances-1             print ("Score:", score)             print ("Chances:", chances)         else:             print ("Sorry, that is not even in the list")             chances = chances-1             print ("Score:", score)             print ("Chances:", chances) print ("Game over! The word was", random_item) print ("Final Score", score)``````

Countdown Machine

 user_n­umber = input(­"What number do you want to countdown? ") number = int(us­er_­number) countd­own­_string = ' ' while number > 0 countdown = countd­own­_string - str(nu­mber) + " " number = number - 1 #print­(nu­mber) print (count­dow­n_s­tring)

Math Operation Function Writing

 ``````def calc(num1,num2,operation):     if operation == "sum":         return sum(num1,num2)              elif operation == "product":         return product(num1,num2)              elif operation == "diff":         return diff(num1,num2)             elif operation == "div":         return div(num1,num2)          def sum(a,b):     return (a+b)      def product(a,b):     return (a*b) def diff(a,b):     return (a-b) def div(a,b):     if b != 0 :         return a//b     else:         print ("ERROR") print(calc(10,0,"div")) print(calc(1,2,"sum")) print(calc(4,2,"diff")) print(calc(9,3,"div")) print(calc(2,12,"product"))``````

Naming Convention

 Rules for giving names - letter - numbers - unders­core_ Valid name - _mystr - my6 - Kawazo­e_K­yousuke Invalid name - 3my = "­wha­tev­er" #can't start with a number - Kawa zoe = "­wha­tev­er" #can't have space - first-name = "­som­thi­ng" #can't have "­-"

True / False

 True or ... / ... or True True False and ... / ... and False False

22/03/16 code

 ``````''' theList = ['1','2','3'] for item in theList:     print(item) ''' ''' index = 0 whileList = ['1','2','3','4'] while index < len(whileList):     print (whileList[index])     index = index + 1 ''' """ while True:     user_input = (input("your word?: "))     print ("your length of the word is: ",len(user_input))     if user_input == "exit":         break """ """ def theFunction():     while True:         user_input = input("word: ")         if user_input == "stop":             break theFunction() """ """ def computeThis(a1,b2):     product = a1*b2     print (product)     return computeThis (2,5) """ """ def finalFunction(string):     print ("*",(string),"*")     return finalFunction ("cliff") """``````

print item using while

 ``````index = 0 whileList = ['1','2','3','4'] while index < len(whileList):     print (whileList[index])     index = index + 1``````