0% found this document useful (0 votes)
2 views

Cheat Sheet

Uploaded by

Larryis real
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Cheat Sheet

Uploaded by

Larryis real
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Function Definition Example

Introduction
print('hello world!')
print() prints a text hello world!
print('hello world!', end= ' ')
print('hello')
print(' ', end=' ') keeps the output of the next print on the same line hello world! hello
print('Name\nJohn')
Name
\n newline character John
print('Name\tJob')
\t insert a tab Name Job
SyntaxError invalid code print('Today is Monday")
IndentationError lines of the program are not properly indented. print("Friday, Friday")
ValueError invalid value is used int("Thursday")
NameError variable that does not exist. day_of_the_week = Friday
lyric = 99 +
TypeError uses incorrect types " bottles of pop on the wall"
adds data in memory location X to the number num,
Add X, #num, Y storing result in location Y add 97, #9, 98
subtracts num from data in location X, storing result
Sub X, #num, Y in location Y sub 97, #9, 98
multiplies data in location X by num, storing result in
Mul X, #num, Y location Y mul 97, #9, 98
divides data in location X by num, storing result in
Div X, #num, Y location Y div 97, #9, 98
Jmp Z next instruction to execute is in memory location Z jmp 97, #9, 98
Variables and
Expressions
type('ABC')
type() returns the type of an object <class'str'>
float(input())
float() decimal point 0.91
OverflowError value is too large to be stored 1.8*10^309
print(f'{math.pi:.4f}') prints only 4 numbers after the decimal point 3.1416
** exponent 2**2 = 4
used to round down the result of a floating-point 5 // 10 is 0
// division to the closest smaller whole number value. 5.0 // 2 is 2.0
% remainder of a division 9 % 5 is 4
exp(x) exponential function
pow(x, y) raise x to power y math.pow(2, 2) = 4
sqrt(x) square root math.sqrt(49) = 7
returns a random floating-point value each time in
random() the range of 0 to 1 ramdom.ramdom() = 0.5
print(random.randint(12, 20))
randint(min, max) returns a random integer between min and max 15
print(random.randrange(12, 20))
randrange(min, max) returns a random integer between min and max - 1 18
print('Name: John O\'Donald')
\' single quote (') Name: John O'Donald
print("He said, \"Hello friend!\"")
\" double quote (") He said, "Hello friend!"
print('\\home\\users\\')
\\ backslash (\) \home\users\
ord() returns an encoded integer value for a string ord('A') = 65
returns a string of one character for an encoded
chr() integer. chr('65') = 'A'
Types
input() user introduces the value input() = 65
x = 'Hello'
print(len(x))
len() find the length of a string 5
x = 'Hello'
print(x[2])
index[] find the position of a character in a sequence l
number = 36
print(f'{number} burritos')
f'{}' create a string with placeholder expressions 36 burritos
name = 'Aiden'
print(f'{name:s}')
print(f'{string:s}') string Aiden
number = 4
print(f'{number:d}')
print(f'{number:d}') number 4
number = 7600
print(f'{number:,d}')
print(f'{number:,d}') decimals with commas 7,600
number = 4
print(f'{number:03d}')
0[precision]d leading 0 notation 004
number = 4
print(f'{number:b}')
b Binary intregers 100
number = 31
print(f'{number:x}')
x, X Hexadecimal in lowercase (x) and uppercase (X) 1f
number = 44
print(f'{number:e}')
e Exponent notation 4.400000e+01
number = 4
print(f'{number:f}')
f Fixed-point notation (six places of precision) 4.000000
number = 4
print(f'{number:.2f}')
.[precision]f Fixed-point notation (programmer-defined precision) 4.00
number = 7600.1
print(f'{number:,.2f}')
,.[precision]f Fixed-point notation with commas 7,600.10
list.append(value) Adds value to the end of list my_list.append('abc')
list.pop(i) Removes the element at index i from list my_list.pop(1)
list.remove(v) Removes the first element whose value is v my_list.remove('abc')
white_house_coordinates =
tuple stores a collection of data, like a list, but is immutable (38.8977, 77.0366)
chevy_blazer = Car('Chevrolet',
'Blazer', 32000, 275, 8)
print(chevy_blazer)
Car(make='Chevrolet', model=
creates only the new simple data type and does not 'Blazer', price=32000,
namedtuple() create new data objects horsepower=275, seats=8)
nums1 = set([1, 2, 3])
print(nums1)
set() an unordered collection of unique elements {1, 2, 3}
players = {'Lionel Messi': 10,
'Cristiano Ronaldo': 7}
print(players)
Dictionaries are typically used in place of lists when {'Lionel Messi': 10,
dict{} an associative relationship exists. 'Cristiano Ronaldo': 7}
dict[k] = v Adds the new key-value pair k-v students['John'] = 'A+'
dict[k] = v Updates the existing entry dict[k] students['Jessica'] = 'A+'
del dict[k] Deletes the entry dict[k] del students['Rachel']
int() used for variable-width integers 1
Branching
if branch taken only if an expression is true If userAge is 20, True
if a user inputs an age less than
25, the statement insurePrice =
if an expression is true, else the other branch is 4800 executes. Else,
if-else executed insurePrice = 2200 executes.
"==" equality operator num_years == 50
!= a != b means a is not equal to b x != 4 is True
elif additional branches elif expression2:
< a < b means a is less than b x < 4 is True
> a > b means a is greater than b x > 2 is True
<= a <= b means a is less than or equal to b x <= 2 is False
>= a >= b means a is greater than or equal to b x >= 4 is False
a<b<c operator chaining 10 < 12 < 15
x is 7, y is 9
(x > 5) AND (y < 20)
a AND b True when both of its operands are True True
x is 7, y is 9
(x > 10) OR (y > 20)
a OR b True when at least one of its two operands are True True
x is 7, y is 9
NOT (x > 10)
NOT a True when its one operand is False, and vice versa False
abc' in '123abcd'
in / not in in x evaluates to True if there exists an index True
Loops
curr_power = 2
user_char = 'y'
while user_char == 'y':
print(curr_power)
curr_power = curr_power * 2
user_char = input()
print('Done')
2
4
8
while repeatedly executes an indented block of code Done
for name in ['Bill', 'Nicole', 'John']:
print(f'Hi {name}!')
Hi Bill!
Hi Nicole!
for loops over each element in a container one at a time Hi John!
sequence of integers between a starting integer and range(3)
range() an ending integer that is not included in the range 0, 1, 2
range(-7, -3)
range(X, Y) generates a sequence of all integers >= X and < Y -7, -6, -5, -4
Z is positive, generates a sequence of all integers range(0, 50, 10)
range(X, Y, Z) >= X and < Y, incrementing by Z 0, 10, 20, 30, 40
Z is negative, generates a sequence of all integers range(3, -1, -1)
range(X, Y, -Z) <= X and > Y, incrementing by Z 3, 2, 1, 0
if meal_cost == user_money:
break causes the loop to exit immediately break
if (num_tacos + num_empanadas)
causes an immediate jump to the while or for loop % num_diners != 0:
continue header statement continue
origins = [4, 8, 10]
for (index, value) in enumerate(origins):
print(f'Element {index}: {value}')
Element 0: 4
retrieves both the index and corresponding element Element 1: 8
enumerate() value at the same time Element 2: 10
Functions
def create new functions def calc_pizza_area():
return function may return one value return num_to_square * num_to_square
performs no operation except to act as a placeholder def steps_to_calories(num_steps):
pass for a required statement pass
def print_sandwich(bread, meat, *args):
*args arbitrary argument list print(f'{meat} on {bread}', end=' ')
def gen_command(application,
**kwargs):
**kwargs keyword arguments command = application
provides all the documentation associated with an
help() object. help(ticket_price)
Strings
Boggle'
creates a new string whose value contains the my_str[0:3]
my_str[start:end] characters of my_str from indices start to end -1 'Bog'
my_str[:5]
my_str[:end] yields the characters from indices 0 to end -1 0, 1, 2, 3, 4
my_str[5:]
my_str[start:] yields all characters at and after start 5, 6, 7, 8...
my_str = [0, 1, 2, 3, 4, 5]
my_str[:-1] returns all but the last character my_str[:-1] = 0, 1, 2, 3, 4
how much to increment the index after reading each
my_str[0:10:2] element my_str[0:10:2]
copy of the string with all occurrences of the phrase.replace('one', 'uno')
replace(old, new) substring old replaced by the string new uno
text = "apple banana apple cherry apple"
new_text = text.replace("apple",
"orange", 2)
Same as above, only replaces the first count print(new_text)
replace(old, new, count) occurrences of old. orange banana orange cherry apple
Boo Hoo!'
Returns the index of the first occurrence of item x in my_str.find('!')
find(x) the string 7
Boo Hoo!'
my_str.find('oo', 2)
find(x, start) begins the search at index start 5
Boo Hoo!'
my_str.find('oo', 2, 4)
find(x, start, end) stops the search at index end - 1 -1
text = "apple banana apple cherry apple"
last_index = text.rfind("apple")
print(last_index)
rfind(x) searches the string in reverse 22
Boo Hoo!'
my_str.count('oo')
count(x) Returns the number of times x occurs in the string 2
text = 'hello'
capitalized_text = text.capitalize()
string with the first character capitalized and the print(capitalized_text)
capitalize() rest lowercased Hello
text = 'HELLO'
capitalized_text = text.capitalize()
print(capitalized_text)
lower() all characters lowercased hello
text = 'hello'
capitalized_text = text.capitalize()
print(capitalized_text)
upper() all characters uppercased HELLO
text = " Hello, World! "
stripped_text = text.strip()
print(stripped_text)
strip() leading and trailing whitespace removed Hello, World!
text = "hello world"
titled_text = text.title()
Hello World
copy of the string as a title, with first letters of words
title() capitalized print(titled_text)
string = 'Music/artist/song.mp3'
my_tokens = string.split('/')
split() splits a string into a list of tokens 'Music/artist/song.mp3'
web_path = [ 'www.website.com',
'profile', 'settings' ]
separator = '/'
url = separator.join(web_path)
join() joins a list of strings together url = 'www.website.com/profile/settings'

You might also like