# Python Cheat Sheet by Zhiend

 string + string combine together number +number math - addition string + number crach

### Data Types

 String a list of characters e.g. "­abc­123­\$%^­", or empty string "­" Integer whole numbers, and negative numbers e.g. -5, 0, 2, 99 Floating Point decimal numbers e.g. 1.5, 2.0, -2.99 Boolean True or False

### True and False

 True or anything is always True False and anything is always False

### Math

 == equal to != no equal to < less than > v <= less than or equal to >= more than or equal to % Modulo, Find the remainder

### Multip­lic­ation and Exponent

 string * number Combine that string string* string crash number * number Multiply (Math) string ** string CRASH! number ** number Exponent (Math) string ** number crash

### Area of Circle

 "­­"­" Python Intro Assignment #2 name student number "­­"­" #Ask the user for a radius of a circle user_r­­adius = input(­­"What is a radius of a circle­­?") #Convert the given radius to a floating point radius = float(­­us­e­r­_r­­adius) #Make a variable called pi pi = float(­­3.1­415) #Calculate the area of the circle using exponents area = pi(ra­­diu­­s**2) #Display the area of the circle to the user print ("The area of the circle is", area)

### Condit­­ionals

 If..... :then..... else....... If the statement is true then do command under then else do command under else while...... While this is true loop the command under the condit­­ional While True loops forever 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)

### List

 ```#what do you think will be the output of the following code: mastr = "hello123" # string is just a list of characters number = [1,2,3,4,5,6] print (number) shoppinglist = ['shoes','bags','pants','shirts]) #how to add an item at the end of the list shopping. append('ties') print (shoppinglist) for martin in shoppinglist       print ('""' + martin + '""')```

 ```number1 = 1.0 number2 = 2.0 sum = str(number1) + str(number2) print(sum) Ans: 3.0```

### Define

 ```def bacon ():     print ("hello it's bacon")     return bacon() Ans : hello it's bacon def myprint(text):     print ("" + str(text) + "")     return myprint(1) Ans : 1 def myprintnew(text,decoration) :     print(decoration + str(text) + decoration)     return myprintnew(1, "+++") myprintnew(555, "+++") Ans : +++1+++ +++555+++ def doubleIt (number) :     return number * 2 print (doubleIt(5)) myvar = 12 myvar = doubleIt(myvar) print (myvar) Ans : 10, 24 def areaOfcircle(r):     if r <= 0:         return "error: invalid radius"     pi = 3.1415     area = pir*2     return area user_radius =input("Enter the radius: ") r = float(user_radius) print ('The area of the circle is', areaOfcircle(r))```

### mix the item

 ```my str = "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)```

### Volume of prism

 ```user_base = float(input("Enter the base of triangle: ")) user_height = float(input("Emter the hight of the triangle: ")) user_lenght = float(input("Enter the lenght of the triangle: ")) def volumeOfPrism (b,h,l):     volume = 1/2 b h * l     return volume print("The volume of the prism is",volumeOfPrism(user_base,user_height,user_lenght))```

### Function Largest Value

 ```def max2(num1,num2):     largestvalue = num1     if num1 > num2:         num1 = largestvalue     else:         largestvalue = num2     return largestvalue def max3 (num1,num2,num3):     if num1>num2 and num1>num3:         largestvalue = num1     elif num2>num3 and num2>num1:         largestvalue = num2     else:         largestvalue = num3     return largestvalue print (max3(9,100,25)) print (max3(69,85,1)) print (max3(75,9,33)) def maxlist (list):     largestvalue = list      for item in list:        if item > largestvalue:            largestvalue = item     return largestvalue mylist = [1,2,3,4,103,100,89,57] print (maxlist(mylist))```

### Vocabulary

 Variable hold a value and can be changed String a list of characters such as number, letter, symbol Integer Whole number / co­unting number Input Gain inform­ation Float number The number in decimal Syntax Gramma­­r/­S­t­ru­­cture of lauguage Modulo Find the remainder Boolean True/False Function define block of code that can reuse Parameter some thing you give to the function Argument some thing you give to the function function call Something that make the fuction work

### Function

 print() Show inform­­­ation that you want on the screen int() Change number to be number integer float() Change number to be decimal number input() Gain inform­­­ation from user str() A list of number, letter and symbols len() The length of the string # Comment, no effect

### Naming Convention

 Rule for giving name - letter - numbers - underscore _ Valid name - _myStr - my3 - Hello_­­there Invalid name - 3my=”hi” -- cannot start with number - first name=”hi” - first-name - first+name

### Sort word per line

 mystr = "­­He­l­l­o" letter_num = 0 while letter_num < len(my­­str): print (mystr­­[l­e­t­te­­r_num]) letter_num = letter_num + 1
H
e
l
l
o

### Number to Hex

 ```user_number = input("please enter a number: ") number = int(user_number) hex_string = ' ' while (number > 0):     remaider = number % 16     if remaider == 10:         remaider = 'A'     elif remaider == 11:             remaider = 'B'     elif remaider == 12:             remaider = 'C'     elif remaider == 13:             remaider = 'D'     elif remaider == 14:             remaider = 'E'     elif remaider == 15:             remaider = 'F'                                  hex_string = str(remaider) + str(hex_string)     number = number // 16 print ("Hexadecimal string is 0x", hex_string)```

### Random

 ```import random intlist = [1,2,3,4,5] random_int = random.choice(intlist) print (intlist,random_int) fplist = [1.69,2.69,3.69,4.69,5.69] random_fp = random.choice(fplist) print (fplist,random_fp) strlist = ['one','two','three','four','five'] random_str = random.choice(strlist) print (strlist,random_str) mylist = [1,1.69,'one'] random_item = random.choice(mylist) print (mylist,random_item) myvar1 = 1 myvar2 = 2 myvar3 = 3 varlist = [myvar1,myvar2,myvar3] random_var =random.choice(varlist) print (varlist,random_var)```

### Palindrome

 ```User_input = input("Type in an string: ") reverse = "" for letter in User_input:     reverse = letter + reverse print ("Reverse: ", reverse) palindrome = reverse if User_input == palindrome:     print ("you input is palindrome") else:     print ("you input is not palindrome")```

### Palindrome 2

 ```while True:     user_input = input("Enter the word: ")     if user_input == "quit" :        break     print (len(user_input))     reverse = ""     for letter in user_input:         reverse = letter + reverse     palindrome = reverse     if user_input == palindrome:         print (user_input," is palindrome")     else:         print (user_input," is not palindrome")```

### Palindrome 3

 ``` def isPalindrome(word) :     reverse = ""     for letter in user_input:         reverse = letter + reverse     palindrome = reverse     if palindrome:         return True     else:         return False                while True:     user_input = input("Enter the word: ")     if user_input == "quit" :        break     print (len(user_input))     ispal = isPalindrome(user_input)     if ispal == True:         print (user_input,"is a palindrome")     else:         print (user_input,"is not a palindrome")```

### Spelling a string out in reverse code

 ```word = input("Type in an word: ") reverse = "" for letter in word:     reverse = letter + reverse print ("Reverse: ", reverse)```

### Area of triangle

 ```user_base = float(input("Enter the base of triangle: ")) user_height = float(input("Emter the hight of the triangle: ")) def areaOfTriangle (b,h):     area = 1/2 b h     return area print ("The area of the triangle",areaOfTriangle(user_base,user_height))```

### Example

 ```Print (2) – integer Print (2.5) – floating point Print (“Hello”) – string Print (mystr) – variable Print (mystr­,”H­i”,­2,1.0) -- commas mystr = “Hi” mystr ← name “Hi” ← value can change print (int(1.5)) → 1 print (int(“2”)) → 2 print (float(1)) → 1.0 anything to a float Modulo­/Re­mainder % print (4%2) → 0 print (30%7) → 2```

### Print Name

 ```name = "tim GIRARD­" print (name.u­pp­er()) → TIM GIRARD print (name.l­ow­er()) → tim girard print (name.c­ap­ita­lize()) → Tim girard print (name.t­it­le()) → Tim Girard```

### Name strip

 ```firstname = input("what is your first name? ") lastname = input("what is your lastname? ") fullname = firstname + " " + lastname print("Your fullname is ") print (fullname) letternumber = input("what is letter number? ") mynumber = int(letternumber)-1 if (mynumber) > len(fullname):     print ("invalid letter number, try again") else:     print (fullname[mynumber])     repeat = input("how many times you want to print the letter? ")     myrepeat = int(repeat)     if (myrepeat) > 99:         print ("too many letter! ")     else:         print(fullname[mynumber]*(myrepeat))```

### Reverse Word

 ```while True:           word = input(­"­Please enter a word")           index = 0           reverse = ' '           while int(index) < len(word):                    reverse = word[i­ndex] + (reverse)                    index = int(index) + 1                    print ("Re­verse: ", reverse)```

### Countdown Code

 ```user_number = input("Please enter a number: ") number = int(user_number) countdown_string = "" while number > 0:     countdown_string = countdown_string + " " + str(number)     number = number-1 print (countdown_string)```

### This prints the true or false value using boolean

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

### Convert to binary

 ```user_n­umber = ' ' while user_n­umber != ' 0 ' :          user_n­umber = input ("Enter a number to convert to binary­")          number = int(us­er_­number)          binary­_string = ' '         while (number > 0):                  remainder = number%2                  binary­_string = str(re­mai­nder)+ binary­_string                  number = number//2 print ("Binary string is", binary­_st­ring)```

### Print definition

 ```def printdefinition(word) :     if word == "Variable" :         print ("""         A variable is something that has volume. Also it can change         """)     elif word == "Function" :         print ("""         A function is define block of code that can reuse         """)     elif word == "Paramiter" :         print ("""         A parameter and argument are some thing you give to the function         """)     elif word == "Function call" :         print ("""         A function call is something that make the fuction work         """)     elif word == "String" :         print ("""         A string is a lis of characters         """)     else:         print ("Unkonw word")                           return      user_input = input("Enter the word") printdefinition(user_input)```

### Guessing Game

 ```""" Group Members: Mind and Gam Class: 10-05 """ chance = 5 score = 0 mylist = ['coke','bacon', 'chicken', 'pocky', 'pepsi', 'pizza'] import random random_item = random.choice(mylist) while chance > 0:          print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")     print ("Guessing Game")     print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")          print ("Words:", mylist)          user_guese = input("Guese the word: ")     if user_guese == random_item:         score = score+100         print ("That's correct! Score:", score)         random_item = random.choice(mylist)     else:         chance = chance-1         if user_guese in mylist:             print ("Sorry, wrong choice!")             print ("Chances Remaining:", chance)         else:             print ("Sorry, that is not ever in the list")             print ("Chances Remaining:", chance) print ("Game Over! The word was", random_item) print ("Final Score:", score)```

### For‐Loop with List:

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

### 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``` 6 Pages
//media.cheatography.com/storage/thumb/zhiend_python.750.jpg

PDF (recommended)