Show Menu
Cheatography

Vocabulary

String
A list of characters "­" , "­abc­"
Variable
Holds a value and can be changed
Syntax
Grammar / Structure of language
Parameter & Argument
something that you give to the function. Give function a value.

Addition, Multip­lic­ation, Exponents

String + String
Combine together
String + Number
CRASH!!!
Number +,*,/ Number
Math
String * Number
Combine that string
String * String
CRASH!!!
String ** Number
CRASH!!!
String ** String
CRASH!!!

Print Name

mystr = "­hello THERE"

print (mystr.ti­tle()) ⇨ Hello There
print (mystr.ca­pit­ali­ze()) ⇨ Hello there
print (mystr.lo­wer()) ⇨ hello there
print (mystr.up­per()) ⇨ HELLO THERE

List

mylist = [2,3,4,5] # create a list

print (mylist[0]) #first item of the list

print (len(mylist)) # displays 4

mylist.append(5) # adds an item to the end of the list

While/For 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

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

Function

def mui():
    print ("Hello!")
    return
mui()

Function Area of Circle

def areaofcircle (radius):
    if radius <=0:
        return "Error: invalis 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))

Function Argument

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,"000000")
***­1***
***­hel­lo­***
***­2.5­***
+++1+++
-=-=-=­-=-­=He­llo­-=-­=-=-=-=
000000­1000000

Return Function

def doubleIt(number):
    return number * 2
print (doubleIt(3))

myvar = 12
myvar = doubleIt(myvar)
myvar = doubleIt(myvar)
print (myvar)
6
48

Palindrome

user_input = input ("Enter a string:")

letter_num = 0
reverse = ""

for letter in user_input:
    reverse = letter + reverse
print ("reverse: ", reverse)

palindrome = reverse
if user_input == palindrome:
    print ("It's a palindrome.")
else:
    print ("It's not a palindrome.")

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 [0]
    for item in list:
       if item > largestvalue:
           largestvalue = item
    return largestvalue
mylist = [1,2,3,4,103,100,89,57]
print (maxlist(mylist))
100
85
75
103
 

Math Symbol

==
Equal to
!=
Not equal to
>=
More than OR Equal to
% (Modulo)
Find the remainder
/
Divide (Answer is a float)
//
Divide (Answer is an integer)
**
Exponent
True OR anything = True
False AND anything = False

Countdown Code

user_number = input("Enter the number:")
number = int(user_number)
countdown_string = ''
while number > 0:
    countdown_string = countdown_string + str (number)
    number = number - 1
print (countdown_string)
Enter the number:5
54321

Reverse Word

word = input ("Enter a word:")
letter_num = 0
reverse = ""

"""
while letter_num < len(word):
    reverse = word[letter_num] + reverse
    letter_num = letter_num + 1
"""

for letter in word:
    reverse = letter + reverse
print ("reverse: ", reverse)
Enter a word:mui
reverse: ium

Convert to Binary

user_number = input ("Enter an interger:")
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)
Enter an interg­er:18
Binary string is 10010

Find area of the circle

while True:
    userradius = input ("Enter the radius.")
    radius = float (userradius)
    pi = 3.1415
    answer = pi radius * 2
    print ("The area of the circle is " , answer)

Naming Conven­tions

Rules for naming variab­­les:
- Letters
- Numbers
- Unders­­cores (_)
- Can start with lett­ers or unde­r­sc­ores ONLY
- NO spaces
-Can start with capital letter

Valid names:
- _myname
- my9
-Hello­_­there

Guessing Game

import random
chance = 3
score = 0

mylist = ['Mind', 'Gam', 'Mui', 'Pim', 'Jui']
random_item = random.choice(mylist)

while chance > 0:
    print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
    print (" Guessing Game")
    print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")

    print(mylist)

    user_guess = input("Guess a word: ")
    if user_guess == random_item:
        score = score + 100
        print("Score:",score)
        print("That's Correct!")
        random_item = random.choice(mylist)
    else:
        if user_guess in mylist:
            chance = chance - 1
            print ("Chance remaining:",chance)
            print("Sorry, Wrong choice")
        else:
            chance = chance - 1
            print ("Chance remaining:",chance)
            print ("Sorry, that is not even in the list")

print("Gameover!!")
print("Word:",random_item)
print("Final Score",score)

Function Area of Triangle

def areaoftriangle(b,h):
    area = 1/2 * 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))

Palindrome Assignment

def ispalindrome(word):
    letter_num = 0
    reverse = ""

    for letter in useranswer:
        reverse = letter + reverse
    
    if reverse == word:
        return True
    else:
        return False

while True:
    useranswer = input("Enter a word:")
    if useranswer == "quit":
        break
    print (len(useranswer))
    
    ispal = ispalindrome(useranswer)
    if ispal == True:
        print (useranswer, "is a palindrome.")
    else:
        print (useranswer, "is not a palindrome.")
 

Functions

int()
Converts a value to an integers
str()
Converts a value to a string
float()
Converts a value to decimal value
len()
The length of the string
"­"­" / '''
Multi-line comment (Not effect code)

Examples

print ("He­llo­")
String
print (mystr)
Variable
print ("he­llo­", "­the­re") #displays hello there
print ("he­llo­" + "­the­re") #displays hellothere

Assignment 1

firstname = input("what is your first name?")
lastname = input("what is your lastname")
fullname = ((firstname) + " " + (lastname))
print (fullname)

letternum = int(input("what is the letter number? "))
if len(fullname) >= int(letternum):
   print (fullname[letternum])
else:
    print ("invalid lecter number, try again.")

letterprint = int(input("How many times to print the letter?"))
if int(letterprint) <= 100:
    print (fullname[letternum] * (letterprint))
else:
    print ("too many letter to print!")

Random LIst

import random

intlist = [1,2,3]
random_int = random.choice (intlist)
print(intlist, random_int)

fplist = [1.1,2.2,3.3]
random_fp = random.choice (fplist)
print (fplist,random_fp)

strlist = ['Lion','Tiger','Zebra']
random_str = random.choice (strlist)
print (strlist, random_str)

mylist = [1,1.5,'Hello']
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)
[1, 2, 3] 1
[1.1, 2.2, 3.3] 2.2
['Lion', 'Tiger', 'Zebra'] Lion
[1, 1.5, 'Hello'] Hello
[1, 2, 3] 3

Print definition of the word

def printdefinitions(word):
    if word == "Variable":
        print ("""
        A variable is something that can be changed.
        """)

    elif word == "Function":
        print ("""
        A function is block of code that can be re-use.
        """)

    elif word == "Parameter" or word == "Argument":
        print ("""
        A parameter and argument are the same. It is something that you give to the function. Give function a value.
        """)

    elif word == "Function call":
        print ("""
b A function call is when we call the function to run. It runs the code.
        """)

    elif word == "String":
        print ("""
        A string is a list of character such as number and symbol.
        """)

    else:
        print ("Unknown Word")
    return

while True:
    user_input = input ("Enter the word:")
    printdefinitions(user_input)

Function Area of Triangle and Prism

def areaoftriangle(b,h):
    area = 1/2 * 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))


def volumeofprism(b,h,l):
    volume = areaoftriangle(b,h) * l
    return volume

user_length = float(input("Enter the length of prism:"))
print ("The volume of the prism is", volumeofprism(user_base,user_height,user_length))

Range

numberlist = range(5)
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

Function with 2 arguments

#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)
 

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.