Python
Author BootCamp
Goal Spoofer
Genres Code Data Science Technology
Day 1 - Print et Input
\n = sauter une ligne entre le texte(ex : print("Day 1 - Python Print Function
\nHello world") )
+ = On peut combiner différents strings entre elles (ex: print("Day 1 - Python
Print Function \nHello world" +"\n \nHello worldtest" ) )
❤️ Python READS LEFT TO RIGHT
Input exampe : print("Day 1 - Python Print Function \nHello world" +"\n
\nHello worldtest" ) ⇒ What’s your name? ⇒ “Liron” ⇒ Hello Liron.
len() function returns the number of items in an object.
When the object is a string, the len() function returns the number of
characters in the string.
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
A variable name cannot be any of the Python keywords.
We can replace parts of the string like this with the Method Replace:
my_text = "hello , my name's george."
Python 1
my_text = my_text.replace("george","John").
#The name george will be replaced by John.
Day 2 - Data Types and string
manipulation
Data always start from 0 in python/programming
To substract H from hello we can do : print(”Hello” [0])
1_7 = 17 , the underscore when written for NUMBERS is just for human
vizualisation and is ignored by the program
All whole number are Integer
Float = numbers with decimals like 3.141
Boolean = can have only true value True / False (T majuscule /F majuscule;
c’est des type)
str() function converts the specified value into a string.
print(type()) = know what data type you are working with (string, float, etc)
for multiplication use * and division / ; division no matter what it gives you a
float
** = exponent
The order of priority on Python Math PEMDAS (PARENTHESES - exponents
- Multiplications /Division - Addition/Substraction) So in equal importance
operation careful to the order and the order goes as always left to right.
+=/-=/*= / /=: to do a function (i.e score = score +1 ⇒ score+=)
print() cant show different data types you need to translate them to the
same like for example (Score = 1 ;Print(”you are “+ str(score/height))
Better than a converstion we can use an f-string : example print(f”you
are{score}”)
Input data should be transformed after ex( Years = input(”how old are you”)
Years_as_int = int(Years))
A multiple line string variable can be written with three “ or ‘ like this :
# Create review_one
review_one = """I really enjoy the courses,
Python 2
and they are easy to fit into my busy schedule.
I wish I had started using your platform sooner.
I'll be recommending you to my friends!!
"""
# Create review_two
review_two = '''One year ago, I was unsure of how to make progress
in my career.
Now, I work as a Prompt Engineer, and I can't thank you enough!
Keep up the great work.'''
Snake case naming variable example == day_of
Camel Case naming variable example == DayOf
Methods are a funtion that is only avaible to a specific data type
Day 3 - Control Flow and Logical
Operators
if xxxx:
print
if xxxx:
elif xxxx:
else:
print
Python 3
eleif= else if
Difference between if/elif/else and Multiple if == All or multiple conditions of
Multiple if can be executed at the same time , while for the 1st option , only
one part of the condition can be true.
Match-Case statements
are an alternative to if/else statement and known as a switch in other
programming languages.
Match case is easier to read , and works better when a lot of cases are
needed.
def day_of_week(day):
case 1:
return 'It is monday'
case 2:
return 'It is tuesday'
case _:
return 'not a valid date'
# case _: is a wild card basically else
Python 4
# to combine multiple cases do this :
case 1 | 2 :
# it is possible to add if statements as an extra condition check
month = 5
day = 4
match day:
case 1 | 2 | 3 | 4 | 5 if month == 4:
print("A weekday in April")
case 1 | 2 | 3 | 4 | 5 if month == 5:
print("A weekday in May")
case _:
print("No match")
Day 4 - Random
first you need to import the module of random that is pre maid in python by
including :
import random
lists format:
Python 5
List_name = [item1 ,item2]
#every list item is numbered from 0 to ... and t to retrieve something fro
m the list
list_name [1]
#to change an item
list_name[1] = "chunkus"
#to add
list_name.append or expand
#to fusion two list if fruits and vegetables are two lists
name_randomiusoz= [fruits, vegetables]
In Python, :: shows up in slicing, which is a way to extract parts of a list
(or string, tuple, etc.).
The general slicing syntax is:
list[start:end:step]
Python data structures
You can retrieve a list from a string with the string method
[Link]() method is a way to chose at random from a list:
import random
mylist = ["apple", "banana", "cherry"]
print([Link](mylist))
To not get out of a list range we can do this for example:
#This gets the number of how many items the list has
num_items = len(names)
random_choice = [Link](0, num_items - 1)
Day 5 - Loops
Python 6
fruits = ["apple","tree"]
for dru in fruits :
print (fruit + " Pie")
#example of len() method but done by a loop
for student in student_heights:
number_of_students +=1
#it adds one number for each student
Range function
Day 6 - Function and Day 8 - Functions
with Input
#To create a fuction
def name_of_the_function ():
print("hoes mad, hoes mad")
#To call a fuction
name_of_the_function ()
#While Loop
i=1
while i < 6:
print(i)
i += 1
#Input
def name_of_fucntion(input)
#function with multiple inputs
def name_of_function(name, location):
print(f"hello {name}")
print(f"what is it like in {location}")
name_of_function("liron","laval")
Python 7
#also possible to specify with argument goes with each perimeter
name_of_function(location="laval", name="liron")
Day 9 - Dictionnaires and Nesting
Dictionnaires in python regroup and tag relatif informations , it is like a table
with the key and value.
Liron = {key: value, key2: value2}
print(Liron["key"]) #It will print the value not the key
#adding new value in the library after
Liron["key3"] = "Value3"
#Wipe an existing dictionary
Liron = {}
#looping through a dictionnary
#if you loop in the classical way tou will get the key not the value to g
et the value :
Python 8
for key in dictionnary_name:
print(dictionnary_name[key])
Nesting is putting multiple data like in a dictionnary(or a list,etc) since you
cant add multiples values directly you can nest
#Nesting dictionary in dictionary
travail_log = {
"France": {"Cities_visited : ["Paris","Lille","Dijon"]}
}
#nesting dictionnary in a list
travel_log = [
{"country": "France, "Cities_visited": ["Paris,"Lille"]}
]
Day 10 - Functions with outputs
#example
def my_function():
result = 3 * 2
return result
#RESULT IS THE OUTPUT but the proper way to do is :
def my_function():
return 3*2
#CAREFUL RETURN = THE END OF THE FUNCTION NOTHING PAST TH
AT IS EXECUTED IN THE FUNCTION BUT YOU CAN HAVE MULTIPLE RE
TURN VALUES IN ONE LIKE THIS:
return f"Result : {formated_f_name} {formated_l_name}
Docstring is documentation , like comments to know about premaid
functions
#it has to be the first line of the function
""" This function should be only used if you are using a nuclear
energy central to power your mom"""
Python 9
The difference between print and return : you might think it is easier to put
print so you can save some time , but an operation might be used later in a
different form which print isnt ok with.
❤️ Return is a value, print is just text.
Day 12 - Scope
scope is the notion that notions developped under some kind of notions like
def , exist only in that notion and not in the whole code.
It is recommended to use global variables in code but not change them
global variables can be defined outside the function
you can do operations in a global variables without modyfing that variable
including by using return ; ex:
global name_of_the_global_variable
name_of_the_global_variable + 1
#or you can do this with return(vid 3)
return name_of_the_global_variable + 1
💟 while , if , for dont count in creating scope because there is no
block scope in python contrary to other languages
Global scope can be useful for constants (like pi)
IT WOULD BE SMART TO WRITE GLOBAL CONSTANTS IN ALL UPPERCASE
Example
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:
x = "awesome"
def myfunc():
Python 10
global x
x = "fantastic"
myfunc()
print("Python is " + x)
The best way to use global variables is with return for example :
enemies = 1
def increase_enemies():
return enemies + 1
enemies = increase_enemies()
Day 13 - Debugging Tips
Play computer = go line by line checking the form is correct.
use print in terminal to see if it is working
[Link]/[Link]#mode=display
Run the code often and before finishing it all
stackoverflow
Day 16 et 17 - OOP
attributes = what do it have + methods : what does it do
attribute = variable attached to the object.
constructor/initializing an object = to set(variables , counters, switches,etc)
to their starting values at the beginning of a program
Python 11
Car = CarBluePrint()
#car is the object; CarBluePrint() is the class
[Link]
#Car is the object , speed the attribute
[Link]()
#methods(functions) is stop()
Packages are code that people have written, with different files ; while
modules are integrated in python and more simple/general.
Python 12
[Link]
#example
#in terminal pip install prettytable(I actually did from the vscode men
u becuase it was not working)
from prettytable import PrettyTable
table = PrettyTable()
#PrettyTable can be changed with x or anything
#to change attributes :
[Link] = "l" #aligns to the left , check documentation for more
To create a class
class User:
#create object
user_1 = User()
#tip ; add pass to finish a object/function that is empty right now and yo
u dont want to show an error ex:
class User :
pass
#create attribute for that class
user_1.id= "001"#.id can be anything you name , it is not predetermined
#how to create a constructor/initialize = __init__
class user:
def __init__(self, user_id):
[Link] = user_id
#self here is an actual object that is being initialized ", a default
parameter, named 'self' is always passed in its argument. This self repre
sents the object of the class itself."
#self can be changed with anything but not recommanded , self i
s the object , the rest attributes
#everytime the init is triggered for every obejct/attribute call.
#you can put a default value when its logical ex : followers .
#adding methods to a class:
def follow (self, user):
Python 13
[Link] += 1
[Link] += 1
Day 21 - Class Inheritance
#animal here is the super class
class Fish(Animal)
def __init__(self):
super().__init__()
Python Inheritance
W3Schools offers free online tutorials, references and
exercises in all the major languages of the web. Covering
popular subjects like HTML, CSS, JavaScript, Python,
[Link]
[Link]
Slicing
piano_keys = ["a","b","c","d","e","f","g"]
Python 14
print (piano_keys[2:5])
#you can chose also an icreament(go up by 2 for example):
piano_keys[2:5:2]#often we put -1 so we can start from the beginning of
the list, its a trick.
Day 18 - Importing modules and other
You can import modules in the simple way : import ModuleName ex: import
turtle
Do not have to write turtle everytime we can import it this way :
from turtle import Turtle
#fril us a keyword as is import, turtle is the module name and Tutrle i
s the thing in the module
tim = Turtle()
tom = Turtle()
#this way we can AVOID TO DO THIS:
tim = [Link]()
tom = [Link]()
#to import everything(but this makes it hard because it can be confu
sing(check 2ndline)
from turtle import *
forward(100)
#this is maybe better to import random ; but generally it's still almost
never used.
You can alias modules
import turtle as T
tim = [Link]()
Some modules cant be imported and need to be installed
A tuple is a data type (ex (1, 3, 8) , it like a list but for predeterminated
stuff like rgb color. But you cant change(/reassign) its value in the code
once it is determinated. It is inmutable/carved in stone.
but you can put the tuple in a list , and then change the list.
Python 15
[Link](350,50,147)
#to create a tuble :
It is also possible to use the tuple() constructor to make a tuple.
thistuple = tuple(("apple", "banana", "cherry")) # note the double
round-brackets
#actually this is workign no more ?!? or
tuple1 =()
Higher order function are function that contain in themselve as a
parameter or return , a function as an output.
ex:
def calculator(n1, n2, func):
Day 25
To open files
open("my_file.txt")
you can save it in a variable
file = open("my_file.txt")
.read returns the content as a string
contents = [Link]() #contents is just the name of a variabe
print(contents)
we need to close the file , beacause it takes some of the resources
[Link]()
We can also use the with keyword, and than name as what we open ; W
E DONT HAVE TO CLOSE OUR FILE WITH THIS METHOD
with open("my_file.txt") as f:
contents = [Link]()
print(contents)
Python 16
.write to write on text but for ti to work you need to open the file not on
'only-read mode', whcib is the default. Attention , this .write , deletes all
the prior data/text.
with open("my_text.txt", mode="w") as file:
[Link]("New text.")
to just add , change the mode from w(wich means write ; mode="w") to
a(append)
Absolute file paths start from the root (/c:/Liron/Dossier/[Link])
Relative file paths can be used if the file is in the same folder(./[Link])
./ means look in the current folder ; if we need to go one step up , just add .
(../[Link])
the readlines() method returns a list containing each line in the file as a list
item.
Use the hint parameter to limit the number of lines returned. If the total
number of bytes returned exceeds the specified number, no more lines are
returned.
The strip() method removes any leading, and trailing whitespaces.
Leading means at the beginning of the string, trailing means at the end.
You can specify which character(s) to remove, if not, any whitespaces will
be removed.
Pandas
Pandas has two primary data structures. Series(1 dimensional) and
dataframe (2 dimensional) , handle the vast majority of typical use cases in
finance , statistics , social science and many areas of engineering.
Data frame is the equivalent of the dataframe.
Series is the equivalent to a list , to a single column. The whole table is the
data frame.
data.to_dict()
Day 26 — List Comprehension
Python 17
List Comprehnsion is unique to python, it is the creation of a list from a
previous list. Instead of doing it with for loop like this :
numbers = [1, 2, 3]
new_list = []
for n in numbers:
add_1 = n + 1
new_list.append(add_1)
We can do this with list comprehension
new_list = [new_item for item in list]
#which gives us :
new_list = [n + 1 for n in numbers]
List Comprehension can be used for many more things.
#with a name for example
name = "Angela"
letters_list =[letter for letter in name]
result of print (letters_list):
['A', 'n', 'g', 'e', 'l', 'a']
python sequences mean stuff that have an order and that describes : list ,
range , string , tuple.
conditional list comprehension
new_list = [new_item for item in list if test ]
Dictionary Comprehension
new_dict = {new_key:new_value for item in list}
#we can take this further by creating a new dictionnary based on the val
ues of another dictionary
Python 18
new_dict ={new_key:new_value for (key,value) in [Link]()} and even
add a condition
How to iterate over a pandas DataFrame
for (key, value) in student_dict.items():
print(value)
Day 27 and 28 — Tkinter , args ,kwargs
and GUI Programs
To import Tkinter
import tkinter
window = [Link]()
[Link]() #this is to keep the window open and should be IN T
HE END OF THE PROGRAM OTHERWISE DOENST WORK
To create a label
my_label = [Link](text="My First GUI", font=("Arial",24))
my_label.pack()
To use advances python arguments , we can have arguments with default
values , so we dont have to rewrite those values when we call the funciton ,
but we can change them when we call them .
def my_function(a=1 , b=2 , c=3)
my_function(b=5)
To use unlimited arguemnts
def add(*args):
for n in args:
print(n)
Python 19
#args can be any word , it is the * that gives it that character
to Creat many keyword arguemnts use the **
def calculate(n, **kwargs)
print(kwargs)
#for key , value in [Link]():
#print(key)
#print(value)
n += kwargs["add"]
n+= kwargs["multiply"]
print(n)
calculate(2, add=3, multiply=3)
class Car:
def __init__'self, **kw):
[Link] = kw["make"]
[Link] = kw{'model']
my_car = Car(make="Nissan",model="gtr")
#but if the values are not specified we will get en error so it is better to use
get and the unspecified value we return as None
class Car:
def __init__'self, **kw):
[Link] = [Link]["make"]
[Link] = [Link]{'model']
my_car = Car(make="Nissan",model="gtr")
For Tkinter , options control things like the color and border width of a widget.
Options can be set in three ways:
Python 20
At object creation time , using keyword arguments
fred = Button (self, fg="red" , bg="blue")
After object creation , treating the option name like a dictionary index
fred["fg"] = "red"
fred{"bg"] = "blue"
Use the config() method to uptade multiple attrs subsequent to object
creation
[Link](fg="red", bg="blue")
The entry
Python 21