Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions Start/1. PythonFeatures/assignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,26 @@
# regular assignment statements assign a value
x = 5
print(x)

# the assignment operator is part of an expression

(x:= 10)
print(x)

# The assignment expression is useful for writing concise code
# thestr = input("Value? ")
# while thestr != "exit":
# print(thestr)
# thestr = input("Value? ")

# while (thestr := input("Value? ")) != "exit":
# print(thestr)

# The walrus operator can help reduce redundant function calls
values = [12, 0, 10, 5, 9, 18, 41, 23, 30, 16, 18, 9, 18, 22]
l = len(values)
s = sum(values)
# l = len(values)
# s = sum(values)
val_data = {
"length": l,
"total": s,
"length": (l := len(values)),
"total": (s := sum(values)),
"average": s/l
}
pprint.pp(val_data)
9 changes: 9 additions & 0 deletions Start/1. PythonFeatures/doc_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@


def myFunction(arg1, arg2=None):
"""myFunction(arg1, arg2=None)--> Doesn't do anything but print the arguments

Parameters
----------
arg1 : any
The first argument.Whatever you want it to be.
arg2 : any, optional
The second argument (default is None).Do what you like.
"""
print(arg1, arg2)


Expand Down
11 changes: 9 additions & 2 deletions Start/1. PythonFeatures/print_pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@
# output for increased readability
# basic print() function
values=["one", "two", "three", "four", "five"]
print(*values)
# print(*values)

# use the 'sep' argument to control the separator between values:
# print(*values, sep=" -- ")


# use the 'end' argument to control the line ending characters
# let's auto-print the current line number along with each item

# for i in range(0, len(values)):
# print(values[i], end=f" [line: {str(i+1)}]\n")

# you can even redirect print() output to a file:
# newfile = open("printoutput.txt", "w")
# print(*values, sep=" -- ", file=newfile, flush=True)


# pprint() can be used to print more complex data
Expand All @@ -28,6 +32,7 @@
{ "game": "Semifinal", "Attendance" : 68294, "France" : 2, "Morocco" : 0},
{ "game": "Semifinal", "Attendance" : 88966, "Argentina" : 3, "Croatia" : 0}
]
#pprint.pp(worldcupdata, indent=3, width=40, underscore_numbers=True)


# pprint also works on newer complex structures, like dataclasses!
Expand All @@ -45,3 +50,5 @@ class wcdata:
wcdata("Semifinal", 68294, "France" , "Morocco" , "2 -- 0" ),
wcdata("Semifinal", 88966, "Argentina" , "Croatia" , "3 -- 0" ),
]

pprint.pp(worldcupdata2)
35 changes: 29 additions & 6 deletions Start/1. PythonFeatures/pyscope.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
# Example file for Advanced Python by Joe Marini
# Understanding Python scope
# # Example file for Advanced Python by Joe Marini
# # Understanding Python scope


# declare a variable within the global scope
# # declare a variable within the global scope
# x=1

# # define a local function with a variable "x"
# def test():
# global x
# x=10
# print(f"x inside function is: {x}")

# define a local function with a variable "x"
# # Run the test function and observe the two results
# test()
# print(x)

# x=x+5
# print(x)
# test()

# Run the test function and observe the two results
# Nested functions create inner scopes. These are called closures:
def multipler_maker(factor):
def multiplier(number):
return number * factor
return multiplier

# Create a multiplier function that multiplies by 2
doubler = multipler_maker(2)
# Create a multiplier function that multiplies by 3
tripler = multipler_maker(3)

print(doubler(10))
print(doubler(15))
print(tripler(10))
print(tripler(15))

# Nested functions create inner scopes. These are called closures:
12 changes: 8 additions & 4 deletions Start/1. PythonFeatures/specialnames.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
# Example file for Advanced Python by Joe Marini
# Using special module names


# __name__ is the name of the module

import collections
print("Module name is: " + __name__)

# __file__ contains the path to the file from which the module was loaded

print("File path is: " + __file__)

# __package__ indicates the package that the module belongs to.
print("Package is: " + str(__package__))
print("Collections package is: " + str(collections.__package__))

if __name__ == "__main__":
print("This is the main module")
12 changes: 9 additions & 3 deletions Start/2. Iterators/basic_iterators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@
daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]

# use regular interation over the days
for d in days:
print(d)
# for d in days:
# print(d)

# use iter() to create an iterator over a collection
# the next() function retrieves the next value from an iterator

# i = iter(days)
# print(next(i))
# print(next(i))
# print(next(i))

# iterate using a function and a sentinel
with open("testfile.txt", "r") as f:
for line in iter(f.readline, ""):
print(line)
23 changes: 18 additions & 5 deletions Start/2. Iterators/for_else.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,24 @@ def findname(target):
if name == target:
print("Name found");
return True

print("Name not found")
return False
else:
print("Name not found")
return False

print(findname("Creed"))
print(findname("Tom"))
# print(findname("Creed"))
# print(findname("Tom"))

# Check if a number is prime
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
print(f"{num} is not a prime number because it is divisible by {i}")
return False
else:
print(f"{num} is a prime number")
return True

print(is_prime(17))
print(is_prime(18))
17 changes: 15 additions & 2 deletions Start/2. Iterators/itertools1.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,27 @@
names = ["Joe", "Jane", "Jim"]

# cycle iterator can be used to cycle over a collection infinitely

# cycler = itertools.cycle(names)
# print(next(cycler))
# print(next(cycler))
# print(next(cycler))
# print(next(cycler))

# use count to create a simple counter
counter = itertools.count(100,10)
# print(next(counter))
# print(next(counter))
# print(next(counter))


# accumulate creates an iterator that accumulates values
vals = [10,20,30,40,50,40,30]

acc = itertools.accumulate(vals)
#print(list(acc))

# amortize a loan over a set number of payments for a 2000 loan at 4%
payments = [100, 125, 200, 105, 100, 120, 110, 130, 150, 100, 110, 120]
update = lambda balance,payment: round(balance * 1.04) - payment
balances = itertools.accumulate(payments, update, initial=2_000)
print(list(balances))

9 changes: 8 additions & 1 deletion Start/2. Iterators/itertools2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@


# chain() creates a single iterable from multiple

x = itertools.chain('ABCDEFG', [1,2,3,4,5], ['$','%','@','&'])
#print(list(x))

# make a prepend function
def prepend(value, iterator):
# use chain to prepend the value to the front of the iterator
return itertools.chain([value], iterator)

#print(list(prepend(0, [1,2,3,4,5])))

# chain.from_iterable is an alternate usage of chain
s1 = "ABCDEFG"
s2 = [1,2,3,4,5]
s3 = ['$','%','@','&']
result = itertools.chain.from_iterable([s1, s2, s3])
print(list(result))
15 changes: 8 additions & 7 deletions Start/2. Iterators/itertools3.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@

# dropwhile and takewhile will return values until
# a certain condition is met that stops them


def testFunction(x):
return x < 40
# dropwhile() drops values until the predicate expression is True

#print(list(itertools.dropwhile(testFunction, vals)))

# takewhile() is the opposite of dropwhile() - it returns values from
# the iterable while the predicate is True, then stops

#print(list(itertools.takewhile(testFunction, vals)))

# filterfalse() returns elements from the iterable for which the predicate
# function returns False.


result = itertools.filterfalse(lambda x: x % 2 != 0, vals)
#print(list(result))
# These functions can work on complex objects
@dataclass
class wcdata:
Expand All @@ -31,10 +31,11 @@ class wcdata:
team1: str
team2: str
score: str

worldcupdata = [
wcdata("Final", 88966, "Argentina" , "France" , "3 (4) -- 3 (2)" ),
wcdata("3rd Place", 44137, "Croatia" , "Morocco" , "2 -- 1" ),
wcdata("Semifinal", 68294, "France" , "Morocco" , "2 -- 0" ),
wcdata("Semifinal", 88966, "Argentina" , "Croatia" , "3 -- 0" ),
]
result = itertools.filterfalse(lambda x: x.attendance > 80000, worldcupdata)
pprint.pp(list(result))
16 changes: 15 additions & 1 deletion Start/2. Iterators/itertools4.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,27 @@
# product() produces the cartesian product of input iterables
cards = "A23456789TJQK"
suits = "SCHD"
deck = list(itertools.product(cards, suits))
# print(f"No.of cards: {len(deck)} cards ")
# print(f"Cards: {deck}")


# permutations() creates tuples of a given length with no repeated elements
teams = ("A","B","C","D")

result = itertools.permutations(teams, 2)
permutation_list = list(result)
#print(f"Permutations: {permutation_list}")
#print(f"No. of Permutations: {len(permutation_list)} ")

# combinations() will create combinations of a given length with no repeats
result = itertools.combinations("ABCD", 3)
combination_list = list(result)
#print(f"Combinations: {combination_list}")
#print(f"No. of Combinations: {len(combination_list)} ")


# combinations_with_replacement() will create combinations of a given length with repeats
result = itertools.combinations_with_replacement("ABCD", 3)
combination_list = list(result)
print(f"Combinations with replacement: {combination_list}")
print(f"No. of Combinations with replacement: {len(combination_list)} ")
24 changes: 17 additions & 7 deletions Start/2. Iterators/more_iterators.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
# Example file for Advanced Python by Joe Marini

import itertools

# define a list of days in English and French
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]
daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven"]#, "Sam"]

# for d in range(len(days)):
# print(d+1, days[d])
# the enumerate function

# for i,d in enumerate(days):
# print(i+1, d)


# use zip to combine sequences
# for d in zip(days, daysFr):
# print(d)


# use enumerate and zip together

# # use enumerate and zip together
# for i,d in enumerate(zip(days, daysFr), start=1):
# print(i, d[0], '=', d[1], "in French")

# use zip_longest
seq1 = ["A","B","C","D","E","F"]
seq2 = [1, 2, 3, 4]
seq3 = "xyz"


result = itertools.zip_longest(seq1, seq2, seq3, fillvalue="-")
print("Result:")
for item in result:
print(item)
Loading