Notes on CS - python
Notes on CS - python
APIs
Application programming interface
EQUALITY VS IDENTITY
CS EXCEPTIONS
test = [1,2,3,4,5,6,8]
if 7 in test:
print('yes')
else:
print('no')
x = int(input('what is x? '))
print(f'x is {x}') # the f and {}, allows you to insert a varaible without string
concatenation (f string)
This input only accepts integers, but will crash if say, a string was inputted. To
avoid this we use try and except
try:
x = int(input('what is x? '))
print(f'x is {x}')
except ValueError:
print('X is not an integer')
For good programming practices, you should only try code that will actually raise
an exception, so usually limit your 'try' to one line of code
try:
x = int(input('what is x? '))
except ValueError:
print('X is not an integer')
else:
print(f'x is {x}')
Putting it in a a loop:
while True:
try:
x = int(input('what is x? '))
except ValueError:
print('X is not an integer')
else:
break #you could also instead get rid of this and put the break after x =
int(input('what is x? '))
print(f'x is {x}')
while True:
try:
x = int(input('what is x? '))
except ValueError:
pass #pass can be used to not do anything with the condition. By using
it here, the loop just continues as it is still True
else:
break
print(f'x is {x}')
F STRINGS
name = 'Om'
age = 22
print(f"Hello, My name is {name} and I'm {age} years old.")
LIBRARY MODULES
Random
coin = random.choice(['head','tails'])
print(coin)
from random import choice #loads the function's name (choice) into the current
namespace
coin = choice(['heads','tails'])
random.shuffle(x)
import random
cards = ['jack','queen','king']
random.shuffle(cards)
for i in cards:
print(i)
Statistics
import statistics
print(statistics.mean([100,90]))
import itertools
num = [1, 2, 3]
color = ['red', 'while', 'black']
value = [255, 256]
use zip()
for item1, item2, item3 in zip((1, 2, 3), ('a', 'b', 'c'), (True, False, True)):
print(item1, item2, item3)
--------------------------------------------------
same code but you must import itertools, and use itertools.zip_longest() to exhaust
all lists
---------------------------------------------------
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']
***********************************************************************************
***********************************
-------------------------------------------------------------
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(flattened_list)
Or you can use list comprehensions where the nest list is flattened out
***********************************************************************************
*********************************
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
# printing result
print ("Resultant list : " + str(res_list))
***********************************************************************************
***********************************
lst=[ 1, 6, 3, 5, 3, 4 ]
#checking if element 7 is present
# in the given list or not
i=7
# if element present then return
# exist otherwise not exist
if i in lst:
print("exist")
else:
print("not exist")
***********************************************************************************
***********************************
# initializing list
test_list = [4, 5, 8, 9, 10, 17]
# printing list
print("The original list : " + str(test_list))
# Printing result
print("Does any element satisfy specified condition ? : " + str(res))
CS LOOPING
print('meow \n'*3, end='') # by default, end = \n, which is why when you print
something new it prints to the next line, but by doing this, it means that the next
print will be on the same line.
DICTIONARIES
aka Hash Tables
students = {
'Hermoine': 'Gryffindor', where the names are the
'keys'
'Harry': 'Gryffindor',
'Ron': 'Gryffindor',
'Draco': 'Slytherin'
print(student['Hermione'])
students =[
{'Name': 'Hermione', 'House': 'Gryffindor', 'Patronus': 'Otter'},
{'Name': 'Harry', 'House': 'Gryffindor', 'Patronus': 'Stag'},
{'Name': 'Ron', 'House': 'Gryffindor', 'Patronus': 'Jack Russel Terrier'},
{'Name': 'Draco', 'House': 'Slytherin', 'Patronus': None} #The use of None,
clearly expresses that there intentinally is no value
]
def main():
print_square(3)
def print_square(pSize):
#for each row in square
for i in range(pSize):
#print brick
print('#', end='')
print()
main()
Sets are data structures that are a collection of unique, unordered elements,
meaning that:
1. No duplicate elements
2. Elements cannot be accessed via index
3. Mutable - the set itself can be modified, but the elements within the set must
be immutable
BASIC OPERATIONS
# Creating a set
my_set = {1, 2, 3}
empty_set = set() # Note: {} creates a dictionary, not a set
Set Operations
Union (|): Combines all unique elements from both sets.
Intersection (&): Keeps only the elements common to both sets.
Difference (-): Keeps elements from the first set not in the second.
Symmetric Difference (^): Keeps elements that are in one set or the other, but not
both.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
Membership Testing:
print(3 in my_set) # True
print(5 not in my_set) # True
Applications of Sets:
Removing Duplicates: Quickly deduplicate items in a list:
my_list = [1, 2, 2, 3, 4, 4]
unique_elements = set(my_list) # {1, 2, 3, 4}#
Fast Membership Testing: Since sets are implemented as hash tables, lookups are
much faster than in lists.
Set Limitations
Unordered: Not suitable when the order of elements matters.
Immutable Requirement: You cannot include mutable types like lists or dictionaries
as set elements.
string slicing
The ::, traverses through the whole list with the final number being the step
But if you want specific string slices for example the first two letters of apple,
the string slice would look like:
'apple'[0:2]
where the first num is the starting point and the second, the letters within the
range of the string regardless starting point
TYPE HINTING
Type hinting in Python is a feature that allows you to specify the expected data
types of variables, function parameters, and return values. It is primarily used to
improve code readability, maintainability, and to help with debugging and static
analysis by tools like type checkers (e.g., mypy). Type hints are optional and do
not affect the runtime behaviour of the program; they serve as a guide for
developers and tools.