Show Menu
Cheatography

Python Cheat Sheet Chili by

my cheat sheet

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

Vocabulary

Variable
Hold a value and can be change
String
A list of character such as number, letter and symbols
Integer number
Whole number­/co­unting number
Float number
The number in decimal
Syntax
Gramma­r/S­tru­cture of language
Modulo
Find the remainder
Boolean
True/False

Example

Print (2) - integer
Print (2.5) - floating point
Print ("He­llo­") - string
Print (mystr) - variable
Print (mystr, "­Hi", 2, 1.0) -- commas

Reverse

#Finish this program so that it gets a word from the user and prints
#that word backwards

reverse = "­" #do not change
letter_num = 0 #do not change

word = input(­"­Please enter a word: "­)#get a word from the user
'''
while letter_num < len(wo­rd)­:#c­ompare the letter_num to the lenght of the word
reverse = word[l­ett­er_­num­]+r­eve­rse­#kepp adding the letter to the front of reverse
letter_num = letter­_nu­m+1#go to the next letter in the word
'''
for lette in word :
reverse = letter + revers

print ("Re­verse: "­,re­verse)


#creating list

mylist = [1,2,3­,4,5,6]

mylist2 = ['hi', 'hello­','­any­thing']


mylist3 = [1, 'hello', 2.5]

Area of the circle

_varl = 1
_varl = 3
_varl + 100
print(_varl)


def bacon():     #use the keyword def and end with a colon:
    print("hello it's bacon")
    return

bacon()
bacon()
bacon()
bacon()
bacon()


def bacon():
    print("hello it's bacon")
    print("line 2")
    print("line 3")
    print("line 4")
    print("line 5")
    print("line 6")
    print("line 7")
    print("line 8")
    return


bacon()
bacon()
bacon()


def myprint(text): #single parameter
    print ("" + str(text) + "")
    return

myprint(1)
myprint("hello")
myprint(1+2)


def myprint2(text, decoration):
    print(decoration + str(text) + decoration)
    return

myprint2(12312321312, "++++")
myprint2("hello", "<<>>")


def doubleIt(number):

    return number * 2

myvar = 2
myvarDouble = doubleIt(myvar)
print(doubleIt("hello"))

myvar = doubleIt(doubleIt(3)) #same as doubleIt(6)
print (myvar)


def sumIt(num1, num2):
    return num1 + num2

print(sumIt("a", "b"))
print(sumIt(2,3))


def areaOfCircle (radius):
    pi = 3.1415
    area = pi  radius*2 
    return area

user_radius = input('Enter the radius: ')
radius = float(user_radius)
print("The area of the circle is", areaOfCircle(radius))


def areaOfCircle(r):
    if r <= 0:
        return "Error: radius <= 0"

    pi = 3.1415
    area = pi  r * 2
    return area

user_radius = input("Enter the radius: ")
radius = float(user_radius)

print ("The area of the circle is", areaOfCircle(radius))
 

Math

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

Addition

string­­+s­tring
Combine together
string­­+s­tring
CRASH!
Number­­+n­umber
Additi­­on­(­Math)

Multip­lic­ation and Exponents

string­­*n­umber
Combine the string
string­­*s­tring
CRASH!
number­­*n­umber
Multip­­ly­(­math)
string­­**­s­tring
CRASH!
number­­**­n­umber
Expone­­nt­(­math)
string­­**­n­umber
CRASH!

Convert Hexade­­cimal

#write a program that convert a number to binary
while True:
#get a number from the user
user_n­umber = input(­"­please enter the number­")

#convert to integer
number = int(us­er_­number)

hex_string = ''
while (number > 0):#the number is greater than 0)
remainder = number % 16#user Modulo %
if remainder == 10:
remainder = 'A'
elif remainder == 11:
remainder = 'B'
elif remainder == 12:
remainder = 'C'
elif remainder == 13:
remainder = 'D'
elif remainder == 14:
remainder = 'E'
elif remainder == 15:
remainder = 'F'


hex_string = str(re­mai­nder) + hex_string #remainder + hexade­cimal string
number = number // 16#must use // when you divide

#after the loop print the Hexade­cimal string
print ("He­xad­ecimal string is 0x" + hex_st­ring)

#expected output - 5 = 101
#expected output - 3 = 11
#expected output - 2 = 10

Convert Binary

#write a program that convert a number to binary

while True:
#get a number from the user
user_n­umber = input(­"­please enter the number­")

#convert to integer
number = int(us­er_­number)

binary­_string = ''
while (number > 0):#the number is greater than 0)
remainder = number % 2#user Modulo %
binary­_string = str(re­mai­nder) + binary­_string #remainder + binary string
number = number // 2#must use // when you divide

#after the loop print the binary string
print ("Binary string is",­bin­ary­_st­ring)

#expected output - 5 = 101
#expected output - 3 = 11
#expected output - 2 = 10

Print defini­tions calc

 def calc(num1, num2, operation):
    # use if/elif/else to check what operation to do
    if operation == "sum":
        return sum(num1, num2)
    elif operation == "div":
        return div(num1, num2)
    elif operation == "product":
        return product(num1, num2)
    else:
        print ("unknown operation")

    # use the function below to compute the operation

    # return the answer


def sum(a, b):
    # calculate the sum of a and b
    return a + b 
    # return the answer


def product(a, b):
    # calculate the product of a and b
    return a * b
    # return the answer

def diff(a, b):
    # calculate the difference between a and b
    return a - b
    # return the answer


def div(a, b):
    # calculate the division of a and b
    return a / b
    # return the answer


print (calc (1, 2, "sum")) #output should be 3
print (calc (4, 2, "diff")) #output should be 2
print (calc (9, 3, "div")) #output should be 3
print (calc (2, 12, "product")) #output should be 24

Create­/Write a Function

# how to create a function

def nameOfFunction(myvar1, myvar2): #parameters or arguments
    print ("hello")  #must indent each line that is part of the function

    return myvar1 + myvar2

#function call

nameOfFunction('hi')


#write a function

#name : areaOfTriangle
#parameters : base height
#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', )
 

Countdown

# Create a program that receives a number from the user and counts down
# from that number on the same line

# receive the number from the user as a string
user_n­umber = input(­"­7")

#convert the user number to an integer
number = int(us­er_­number)

#setup the countdown string
countd­own­_string = '7 6 5 4 3 2 1 0'

while number > 0:
# add the number to the string
countd­owm­_string = something + str(so­met­hin­gelse)
# subtract 1 from the number
number = number - 1

print (count­dow­n_s­tring)

Radius of Circle

while True: 

#Ask the user for a radius of a circle
user_r­adius = input(­"­Please enter the radius of the circle­")

#Convert the given radiusto a floating point
radius = float(­use­r_r­adius)

#make a variable called pi
pi = 3.1415

#Calculate the area of the circle using exponents
area = pi radius *2

#display the area of the circle to the user
print(­"The area of the circle is", area)

Random

import random

# Create a list of integers
inlist = [1,2,4­,5,7,9]
random_int = random.ch­oic­e(i­ntlist)
print (inlist, random­_int) #print the entire list andthe random item

# Create a list of floating point numbers
fplist = [1.5,2.2,­1.0­,10­0.999]
random_fp = random.ch­oic­e(f­plist)
print (fplist, random_fp) #print the entire list and the random item

# Create a list of strings
strlist = ['dog', "­cat­", 'match', "it's me", '"hi­"']
random_str = random.ch­oic­e(s­trlist)
print (strlist, random­_str) #print the entire list and the random item

# Create a list of integers and floating point numbers and string
mylist = [1,2,2.2,3.2, 'string', "­hi"]
random­_item = random.ch­oic­e(m­ylist)
print (mylist, random­_item) #print the entire list and the random item

# create alist of following variable
myvar1 = 1
myvae2 = 2
myvar3 = 3
varlist = [myvar1, myvar2, myvar3]
random_var = random.ch­oic­e(v­arlist)
print (varlist, random­_var) #print the entire list and the random item

Print Defini­tions

# write definitions for the following words and print them using
# a multi-line string

def printDefinitions ():
    
    if word == "variable":
        #variable

        print ("""

        A variable is ....
    
        """)        

    elif word == "function":
        #function
        print ("""

        A function is something 
 
        """)

    elif word == "parameter":
        print ("""

        A parameter is ...
        
        """)

    elif word == "argument":
         print ("""

         A argument is

         """)

    elif word == "string":
        print ("""

        A string is ...
        
        """)

    elif word == "function call":
        print ("""

        A function call is ...
        
        """)

        
    else:
        return "unknown word"

#ask the user for the name of the word to define

user_input = input ("Enter the word to define: ")

printDefinitions(user_input )

Max value

# write a function that returns the largest of two values
# name: max2
# arguments: num1, num2
# return: the largest value


def max2 (num1, num2):
    maxvalue = num1
    
    if num2 > num1:
        maxvalue = num2

    return maxvalue

print(max2(10,9))
print(max2(1,9))


# write a function that returns the largest of three values
# name: max3
# arguments: num1, num2, num3
# return: the largest value


def max3 (num1, num2, num3):
    maxvalue = num1

    if num2 > maxvalue:
        maxvalue = num2
        
    if num3 > maxvalue:
        maxvalue = num3
        
    return maxvalue

print(max3(3,5,9))
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter