Python Notes Updated
Python Notes Updated
Basic commands
List directory - dir
Go back – cd ..
Clear screen – cls
Save as python file - .py
Change directory – cd + (name of directory) ex. (cd Desktop)
Computing Numbers
Integer – whole numbers
Floating points – can contain decimals and digits past the decimal points. ex (100.5,
100.0, 3.9 etc.)
Add/ subtract - +,-
Multiply/divide - *,/
To the power of - **
Modulo or “Mod” - % (To know if number is even or odd or divisible by another number)
example: 10%2= 0, 10%3=1 (aka, 1 left over)
Data Types
Variables
Variable Names - cannot start with numbers. Cannot use spaces in the name, use _
instead, names should be lowercase, avoid using words that have special meanings in
python.
Dynamic Typing (Used in Python)- reassigning variables to different data types
Strings
Strings are sequences of characters
Strings are ordered sequences – ‘hello’ , “Hello” , “I don’t do that”
Indexing
Indexing is used to grab a single character from a string, uses [], indexing starts at 0 in
Python. Every character has an index position assigned to it
Characters: Hello
Index : 01234
Reverse indexing: 0 -4 -3 -2 -1
Slicing
Used to grab sub-sections of multiple characters of a string
[start:stop:step]
Start is a numerical index for the slice start
Stop is the index you will go up to (but NOT include)
Step is the size of the “jump” you take
To grab ‘ink’ from ‘tinker’, you would use ‘tinker’[1:4] = ‘ink’
Stepping: in string ‘abcdefghijk’, if you want to grab every other character(acegik), you
would do ‘abcdefghijk’ [0:12:2] 0= start, 12=end of string, 2=every 2 nd character
To reverse any string, use (string name)[::-1]
String formatting
String interpolation – injecting a variable into a string. ex. my_name=”Jose”
Print(“Hello”+my_name)
Lists
Ordered sequences that can hold a variety of objects.
They use [] brackets and commas to separate objects in the list [1,2,3,4,5]
Lists support indexing and slicing as well.
Lists are used to retrieve objects by location.
Ex. my_list = ['one', 'two','three']
Another_list = ['four','five']
New_list = my_list+another_list
New_list = 'one', 'two', 'three', 'four', 'five'
.append() is used for adding objects into the end of a list
new_list.append('six')
'one', 'two', 'three', 'four', 'five', ‘six’
.pop() is used to delete objects from end of a list
new_list.pop()
‘six’
new_list = 'one', 'two', 'three', 'four', 'five'
Using .sort() will arrange a list alphabetically or numerically
ex.
input: new_list = ['a', 'e', 'x', 'b', 'c']
input: new_list.sort()
input: new_list
output: ['a', 'b', 'c', 'e', 'x']
Using .reverse() will reverse your list
Dictionaries
Dictionaries are unordered mappings for storing objects.
Dictionaries use curly braces {} and colons : with key-value pairs to signify the keys and
their associated values
Dictionaries use key-value pairing. Lists use ordered sequences.
{‘key:1’:’value1’, ‘key:2’:’value2’}
Use dictionaries to retrieve objects by key name. Unordered and CANNOT be sorted.
ex.
input: prices_lookup = {'apple':'2.99', 'oranges':'1.99','milk':5.00}
input: prices_lookup['apple']
output: ‘2.99’
ex. #2
input: d = {'k1':123, 'k2': [0,1,2], 'k3':{'insidekey':100}}
input: d['k2'][2]
output: 2
.keys() will give all keys
.values() will give all values of each key
.items() gives keys WITH values
Tuples
Similar to lists but are IMMUTABLE
Once an element is inside a tuple, it cannot be reassigned
Tuples use parenthesis; (1,2,3)
Sets
Sets are unordered collections of unique elements.
There can only be one representative of the same object
Ex. In: myset=set()
In: myset.add(1) .add= used for adding something
In: myset
Out: {1}
Booleans
Operators that allow you to convey true or false statements
Will come in handy dealing with control flow and logic
Always capitalize T in True and F in false
1>2
1==1 use ==
Files
Create a file by using %%writefile (file name.txt) example: %%writefile myfile.txt
Press enter and you can write whatever you want there to be in the file
pwd = print working directory. Use this to see where files are being saved
To read the file, type .read() at the end of file name
In order to read the file again, you need to reset it by typing .seek(0) at the end
of file name
To show the file in lines, type .readlines() at the end of file name
After reading or editing a file, you must close the file using .close() at the end of
file name or you will have errors.
Using the “with open” method: with open (‘myfile.txt’) as my_new_file:
Contents = my_new_file.read()
Will avoid you from getting any errors.
TWO ON SECOND
THREE ON THIRD
And
In: 1<2 and 2<3
Out: True
if loc=='Auto Shop':
print("Cars are cool")
elif loc=='Bank':
print('Money is cool')
elif loc=='Store':
print('Welcome to the store')
else:
print('I do not know much')
Unpacking example:
In: mylist= [(1,2,3),(4,5,6),(7,8,9)]
In: for a,b,c in mylist:
print(b)
Out: 2
5
8
To unpack dictionaries:
In: d={'k1':1, 'k2':2,'k3':3}
Example:
In: x=0
while x<5:
print(f’The current value of x is {}’)
x=x+1
else:
print(‘X IS NOT LESS THAN 5’)
In: x=0
while x < 5:
if x==2:
break
print(x)
x+=1
Out:0
1
Enumerate function: Basically gives index counts for each character in a ‘string’.
In: word=’abcde’
Out: (0,’a’)
(1,’b’)
(2,’c’)
(3,’d’)
(4,’e’)
min(list name)- tells you whatever is the minimum value in your list
max(list name)- tells you whatever is the maximum value in your list
input()- allows you to input any information
ex. input('Enter a number here: ') - *if you input 7, the output will be 7
In: mylist=[1,2,3,4,5]
In: shuffle(mylist)
In: mylist
Out: [4,2,1,3,5]
List Comprehensions
Unique way of quickly creating a list with Python.
In: Mystring=’hello
In: mylist=[]
for letter in mystring:
mylist.append(letter)
In: mylist
Out: [‘h’, ’e’, ’l’, ’l’, ’o’]
Functions:
functions allow us to create blocks of code that can be easily executed,
without needing to constantly rewrite the entire block of code.
Def Keyword:
Syntax:
def name_of_function(): snake casing: all lowercase with
underscores between the words
Another Example:
In: def myfunc(a,b):
print(a+b)
return a+b Return function allows you to save the
result to a variable so later on when you call
the variable, it will return the result.
In: result=myfunc(10,20)
Out: 30
In: result
Out: 30
When using multiple return functions in Python:
def check_even_list(num_list):
for number in num_list:
if number%2==0:
return True
else:
pass
In: check_even_list([1,2,5,7,9])
Out: True Since there is an even number
here, it will return true
Tuple Unpacking with Python Functions:
In: work_hours=[('Abby',100),('Billy',4000),('Cassie',800)]
Trying to find the employee
of the month and how many
In: def employee_check(work_hours): hours they worked
In: employee_check(work_hours)
Out: (‘Billy’,4000)
Guessing game find the O (Three cup Monte):
shuffle(mylist)
return mylist
2. Create mylist
In: mylist=['','O','']
return int(guess)
CONTINUED…
In:
# INITIAL LIST Comment just to keep track of what functions
you are inputting
mylist=['','O','']
#CHECK GUESS
check_guess(mixedup_list,guess)
args and kwargs – Arguments and Keyword arguments
Without *args:
In: def myfunc(a,b):
#Returns 5% of the sum of a and b Comment (optional)
return sum((a,b,c,d))* 0.05
In: myfunc(40,60)
Out: 5