0% found this document useful (0 votes)
7 views23 pages

Python Notes Updated

This document provides a comprehensive overview of Python programming, covering basic commands, data types, variables, strings, lists, dictionaries, tuples, sets, file handling, control flow, loops, and functions. It includes examples of syntax and usage for each concept, making it a useful reference for beginners. Key topics include string formatting, list comprehensions, and the use of logical operators and functions.

Uploaded by

DOOMFATHER69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views23 pages

Python Notes Updated

This document provides a comprehensive overview of Python programming, covering basic commands, data types, variables, strings, lists, dictionaries, tuples, sets, file handling, control flow, loops, and functions. It includes examples of syntax and usage for each concept, making it a useful reference for beginners. Key topics include string formatting, list comprehensions, and the use of logical operators and functions.

Uploaded by

DOOMFATHER69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Python Notes

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

 Strings (str) – Ordered sequence characters: “hello” ‘Sammy’ “2000”


 Lists(list)– Ordered sequence of objects: [10, “hello”, 200.3]
 Dictionaries (dict)- Unordered Key:Value pairs: {“mykey”:”value”, “name”: “Frankie”}
 Tuples (tup)- Ordered immutable sequence of objects: (10,”hello”, 200.3)
 Sets(set)- Unordered collection of unique objects: {“a”,”b”}
 Booleans (bool)- Logical value indicating True or False

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)

 .format() method: String here {} then also {}.format(‘something1’, ‘something2’)


Ex. #1. print('The {q} {b} {f}'.format(f='fox',b='brown',q='quick'))
The quick brown fox OR
Ex. #2. print('The {2} {1} {0}' .format('fox','brown','quick'))
The quick brown fox
 Float formatting
Ex. #3. result=104.12345
print("The result was {r:1.2f}" .format(r=result))
The result was 104.12
{value:width:precision f}

 f-strings method (formatted string method)


name="Jose"
print(f'Hello, his name is {name}')
Hello, his name is Jose

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.

Modes for opening/reading/editing files:


 Mode ‘r’ is read only
 mode ‘w’ is write only (will overwrite or create new!)
 mode ‘a’ is append only (will add to files)
 mode ‘r+’ is reading and writing
 mode ‘w+’ is writing and reading (overwrites existing files or creates a new file)
Examples:
In: %%writefile my_new_file.txt
ONE ON FIRST
TWO ON SECOND
THREE ON THIRD
In: with open ('my_new_file.txt',mode='r') as f:
print(f.read())
Out: ONE ON FIRST

TWO ON SECOND
THREE ON THIRD

In: with open ('my_new_file.txt',mode='a') as f:


f.write('FOUR ON FOURTH')
In: with open ('my_new_file.txt',mode='r') as f:
print(f.read())
Out: ONE ON FIRST
TWO ON SECOND
THREE ON THIRD
FOUR ON FOURTH

Reading and writing a new file example:


In: with open('jkhvshfsjdfbnkj.txt',mode='w') as f:
f.write('I CREATED THIS FILE!')
In: with open('jkhvshfsjdfbnkj.txt',mode='r') as f:
print(f.read())
Out: I CREATED THIS FILE!

Logical Operators & Chaining comparison operators

 We can use logical operators to combine comparisons:

 And
In: 1<2 and 2<3
Out: True

 Or Only needs one side to be true!


In: 1==6 or 2==2
Out: True

 Not Gives you the opposite boolean!


In: not(1==1)
Out: False
SECTION 5

If, elif, else statements


Control flow syntax makes use of colons and indentations (whitespace)
This indentation system is crucial to Python

 Syntax of an if/else statement:


if some_condition:
# execute some code you can also add elif in between to check
multiple conditions before the else statement is executed.
Elif some_other_condition:
# do something different
Else:
# do something else

In: loc = 'Bank'

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

Out: Money is cool


For Loops
Many objects in Python are iterable, meaning we can iterate over every element
in the object. Such as every element in a list or every character in a string. We can
use for loops to execute a block of code for every iteration.

Syntax of a for loop:


In: my_list =[1,2,3]
for item_name in my_list:
print(item_name)
Out: 1
2
3

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}

for key,value in d.items():  need to use .items()


print(value)
Grab only the words that start with ‘s’ in the below sentence:
In: st='Sam Print only the words that start with s in this sentence'
In: for word in st.split():
if word[0]=='s' or word[0]=='S':
print(word)
Out: Sam
start
s
sentence
While Loops:
 While loops will continue to execute a block of code while some condition remains true.
 For example, while my pool is not full, keep filling my pool with water

Syntax for while loop:


while some_boolean_condition
# do something
else:
# do something else

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

Out: The current value of x is 0


The current value of x is 1
The current value of x is 2
The current value of x is 3
The current value of x is 4
X IS NOT LESS THAN 5
Break: breaks out of the current closest enclosing loop(basically means to stop)
Continue: Goes to the top of the closest enclosing loop(basically means skip and move forward
the rest of the loop)
Pass: does nothing at all. (mostly used as a placeholder to avoid errors)

In: x=0
while x < 5:
if x==2:
break
print(x)
x+=1
Out:0
1

In: for letter in mystring:


if letter=='a':
continue
print(letter)
Out: S
m
m
y
Useful Operators:

Enumerate function: Basically gives index counts for each character in a ‘string’.
In: word=’abcde’

for item in enumerate(word):


print(item)

Out: (0,’a’)
(1,’b’)
(2,’c’)
(3,’d’)
(4,’e’)

Zip Function: used to attach lists together


In: mylist1=[1,2,3]
mylist2=['a','b','c']
mylist3=[100,200,300]

In: for item in zip(mylist1,mylist2,mylist3):


print(item)
Out: (1, 'a', 100)
(2, 'b', 200)
(3, 'c', 300)
in function: tells you if something is IN
In: 'a' in 'hello my name is uzair'
Out: True

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

importing libraries : from random import *click TAB

In: from random import shuffle  importing the shuffle function

In: mylist=[1,2,3,4,5]
In: shuffle(mylist)
In: mylist
Out: [4,2,1,3,5]

Picking a random number: EXAMPLE

In: from random import randint


randint(0,100)  minimum and maximum value

Out: 41  output is a random integer

Optional (assigning a random integer) - In: mynum=randint(0,100)


Out: 28
In: mynum
Out: 28
Input:
In:result= input(‘Favorite number’)
In:24
Out: ‘24’ This will always show up as a string in the output
In: float(result) To change to a floating point
Out: 24.0
In: int(result) To change to an integer
Out: 24

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’]

To simplify on a single line, you can do it THIS way:


In: mylist=[letter for letter in mystring]  You can perform
operations inside this loop ie.
multiplication, square root, etc.
In: mylist
Out: [‘h’, ’e’, ’l’, ’l’, ’o’]
In: mylist=[x*y for x in [2,4,6] for y in [1,10,1000]]  You can also have multiple for
loops within the same list
In: mylist
Out: [2, 20, 2000, 4, 40, 4000, 6, 60, 6000]
Section 6
Methods and Functions:
 use SHIFT+TAB for help while inputting functions
 use mylist. And click TAB to see all functions that are applicable

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

 def: a keyword that tells Python that this is a function.


In: def name_of_function(name):
print('hello'+ name)
In: name_of_function(‘ Uzair ‘)
Out: hello Uzair
Return function: allows you to save the result to a variable
In: def add_function(num1,num2):
return num1+num2
In: result=add_function(1,2)
In: print(result)
Out: 3

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

return False  multiple return statements


should be aligned with the “for”
statement.

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

current_max=0  Both of these are placeholders


employee_of_month=''  Both of these are placeholders

for employee,hours in work_hours:


if hours > current_max:
current_max=hours
employee_of_month=employee
else:
pass
return (employee_of_month,current_max)

In: employee_check(work_hours)
Out: (‘Billy’,4000)
Guessing game find the O (Three cup Monte):

1. Creating a function that


In: def shuffle_list(mylist): shuffles the list.

shuffle(mylist)
return mylist

2. Create mylist
In: mylist=['','O','']

In: def player_guess():


guess='' 3. Creating a function that asks
for your guess. And if the
while guess not in ['0','1','2']:
guess is not one of the
guess=input('Pick a number: 0,1, or 2') choices, it will ask again.

return int(guess)

In: def check_guess(mylist,guess):


 If your guess is at the same index as the
if mylist[guess]=='O': “O”. it will print “Correct”
4. Created a function that checks whether
print('Correct')
the guess is correct or wrong. It will tell
else: you whether you are correct or wrong, and
will also display the list to show you the
print('Wrong guess') correct position of the ball.
print(mylist)

CONTINUED…
In:
# INITIAL LIST Comment just to keep track of what functions
you are inputting
mylist=['','O','']

#SHUFFLE LIST 5. Must input all of these functions together in


mixedup_list=shuffle_list(mylist) order for the game to work. All of these must
be input within the same cell so the game can
restart once you run the cell again. It will also
assign a new position to the ball.
#USER GUESS
guess=player_guess()

#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

Using *args: *args is used for arguments and


allows you to input as many
In: def myfunc(*args): parameters as you would like. *args is
arbitrary and can be changed as long
return sum(args) * 0.05
as the single asterisk remains put.
In: myfunc(40,60,100) Using *args returns your function as a
tuple.
Out: 10

Using **kwargs: **kwargs is used for keyword


arguments and allows you to
In: def myfunc(**kwargs): enter as many parameters
later on in your function.
if 'fruit' in kwargs:
Hence the use of ‘veggie’
print('My fruit of choice is {}'.format(kwargs['fruit'])) even though veggie was not
mentioned in the original
else: block of code. **kwargs is
print('I did not find any fruit here') arbitrary and can be changed
as long as the two asterisks
In: myfunc(fruit='apple',veggie='lettuce') remain put. Using **kwargs
will return your function as a
Dictionary.
Out: My fruit of choice is apple

You might also like