Repository: pirple/Python-Is-Easy
Branch: master
Commit: 99c4e531c4cb
Files: 40
Total size: 134.4 KB
Directory structure:
gitextract_ej8bju1m/
├── "if" statements/
│ └── main.py
├── .gitignore
├── README.md
├── classes/
│ ├── Class-Inheritance.py
│ ├── Introduction-to-Classes.py
│ ├── Pets-Part-A.py
│ ├── Pets-Part-B.py
│ ├── Pets-Part-C.py
│ └── Pets-Part-D.py
├── dictionaries and sets/
│ ├── Dictionaries-and-Sets.py
│ └── Examples-of-Dictionaries-and-Sets.py
├── error handling/
│ └── main.py
├── final project/
│ ├── Blackjack-Part-A.py
│ ├── Blackjack-Part-B.py
│ ├── Blackjack-Part-C.py
│ ├── Blackjack-Part-D.py
│ ├── Blackjack-Part-E.py
│ └── Blackjack-Part-F.py
├── functions/
│ └── main.py
├── importing/
│ ├── Alternative-Import-Methods.py
│ ├── Guessing-Game-Part-A.py
│ ├── Guessing-Game-Part-B.py
│ ├── Introduction-to-Importing.py
│ ├── Math-Library.py
│ └── Time-Library.py
├── input and output/
│ ├── File-IO.py
│ ├── Introduction-to-IO.py
│ ├── Participant-Data-Part-A.py
│ ├── Participant-Data-Part-B.py
│ ├── Participant-Data-Part-C.py
│ ├── Participant-Data-Part-D.py
│ ├── Tic-Tac-Toe-Part-A.py
│ └── Tic-Tac-Toe-Part-B.py
├── lists/
│ └── main.py
├── loops/
│ ├── Breaking-and-Continuing-in-Loops.py
│ ├── Introduction-to-Loops.py
│ ├── Making-Shapes-With-Loops.py
│ ├── Nested-Loops.py
│ └── While-Loops.py
└── variables/
└── main.py
================================================
FILE CONTENTS
================================================
================================================
FILE: "if" statements/main.py
================================================
##
# "If" Statements Lecture
##
# -*- coding: utf-8 -*-
'''
Syntax:
if condition:
Action
'''
click = False #set variable click to False
Like = 0 #initialize Like equal to 0
if click == True: #Check if click is True
Like = Like + 1 #Increment Like by 1
click = False #set click to False
print(Like) #print the value
Temperature = 20 #set a variable Temperature to 20
Thermo = 15 #set a variable Thermo to 15
if Temperature < 15: #Check if Temperature is less than 15
Thermo = Thermo + 5 #if yes increment variable Thermo by 5
print(Thermo) #print the value Thermo
Temperature = 14 #set variable Temperature to 14
Thermo = 15 #set variable Thermo to 15
if Temperature < 15: #Check if Temperature is less than 15
Thermo = Thermo + 5 #if True increment Thermo by 5
print(Thermo) #print the value of Thermo
Temperature = 15 #set variable Temperature to 15
Thermo = 15 #set variable Thermo to 15
if Temperature <= 15: #Check if Temperature is less than or equal to 15
Thermo = Thermo + 5 #if True increment Thermo by 5
print(Thermo) #print the value of Thermo
if Temperature > 20: #Check if Temperature is greater than 20
Thermo = Thermo - 3 #if True decrement Thermo by 3
print(Thermo) #print the value of Thermo
Temperature = 20 #set the value of Temperature to 20
Thermo = 15 #set Thermo equals to 15
if Temperature <= 15: #Check if Temperature is less than or equal to 15
Thermo = Thermo + 5 #if True increment Thermo by 5
print(Thermo) #print value of Thermo
if Temperature >= 20: #Check if Temperature is greater than or equal to 20
Thermo = Thermo - 3 #if True decrement Thermo by 3
print(Thermo) #print value of Thermo
Time = "Day" #set variable Time to Day
Sleepy = False #set Sleepy equals to False
Pajamas = "Off" #initialize Pajamas equal to Off
'''
If Time equals to Night and Sleep is True then set Pajamas equal to On
'''
if Time == "Night" and Sleepy == True: #Check two condition and are ANDed
Pajamas = "On" #if both condition are True then set Pajamas = On
print(Pajamas) #print the value of Pajamas
Pajamas = "Off" #initialize Pajamas equal to Off
if Time == "Night" or Sleepy == True: #Check two condition and are ORed
Pajamas = "On" #if anyone of the condition is True set Pajamas equal to On
print(Pajamas) #print the value of Pajamas
Time = 'Night' #set variable Time to Night
Sleepy = 'True' #set variable Sleep equals to True
Pajamas = "Off" #initialize Pajamas equal to Off
if Time == "Night" or Sleepy == False: #Check two condition and are ORed
Pajamas = "On" #if anyone of the condition is True set Pajamas equal to On
print(Pajamas) #print the value of Pajamas
'''
intialize Time equals to Day, Sleepy equals to False, Pajamas to off and InBed equals to True
Check if Time equals to Night, set Pajamas equals to On, else if Time equals to Morning is True
set Pajamas equals to On and then print its value
'''
Time = 'Day'
Sleepy = 'False'
Pajamas = "off"
InBed = True
if Time == "Night":
Pajamas = "On"
elif Time == "Morning":
Pajamas = "On"
print(Pajamas)
Time = 'Morning' #set Time equals to Morning
Sleepy = 'False' #Set Sleepy to False
Pajamas = "Unknown" #set Pajamas to Unknown
InBed = True #set InBed variable to True
print(Pajamas) #print value of Pajamas
if Time == "Night": #if Time is equal to Night
Pajamas = "On" #set pajamas to On
elif Time == "Morning": #else if Time equal to Morning
Pajamas = "On" #set pajamas to On
else: #otherwise if any of the above two statement are not true
Pajamas = "Off" #set Pajamas Off
print(Pajamas) #print the value of Pajamas
================================================
FILE: .gitignore
================================================
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
================================================
FILE: README.md
================================================
# Python is Easy
> Code snippets for the "Python is Easy" course, available at Pirple.com/python
## About this Repository
These code snippets are for following along with the lectures, and running the code yourself.
Everything is organized by section. Click on a section to find the lecture code you're looking for.
## Never used Git or Github before?
No worries. You can learn how to use it in just a few minutes. Start by watching these videos:
#### Git
[https://git-scm.com/videos](https://git-scm.com/videos)
#### Github
[https://www.youtube.com/playlist?list=PLg7s6cbtAD15G8lNyoaYDuKZSKyJrgwB-](https://www.youtube.com/playlist?list=PLg7s6cbtAD15G8lNyoaYDuKZSKyJrgwB-)
After that, you'll know enough to grab this code yourself and "clone" it down to your machine.
================================================
FILE: classes/Class-Inheritance.py
================================================
##
# Class Inheritance Lecture
##
# -*- coding: utf-8 -*-
class Team:
#constructor passes two variables Name and Origin. The
#default value of variable Name is "Name" and that of variable Origin is "Origin".
#If no values are passed through a constructor its default values are Name and Origin.
def __init__(self, Name = "Name", Origin = "Origin"): #constructor
self.TeamName = Name #member assignment
self.TeamOrigin = Origin #member assignment
def DefineTeamName(self, Name): #class method
self.TeamName = Name
def DefineTeamOrigin(self, Origin): #class method
self.TeamOrigin = Origin
#class InheritanceClassName(ParentClass):
# def __init__(self, Input1, Input2):
# ParentClass.__init__(self)
# self.Attribute1 = Input1
# self.Attribute2 = Input2
# self.Attribute3 = 0
#
# def AnotherMethod(self):
# Action(s)
'''
Class Player is derived from the base class or parent class Team
'''
class Player(Team):
def __init__(self): #constructor
Team.__init__(self)
'''
The __init__ method of our Team class explicitly invokes the __init__method of the Player class.
'''
self.PlayerName = "None" #member variable assigned to None
self.PlayerPoints = 0 #member variable assigned to 0
'''
Methods: ScoredPoints and setName
ScoredPoints increments the PlayerPoints by 1.
setName sets the name of Player
'''
def ScoredPoint(self):
self.PlayerPoints += 1 #increments Playerpoints by 1
def setName(self, name):
self.PlayerName = name #assigned name to Player
Player1 = Player() #create an instance of a class Player
print(Player1.PlayerName) #print the value of member variable PlayerName
print(Player1.PlayerPoints) #print the value of member variable PlayerPoints
Player1.DefineTeamName("Sharks") #call methods DefineTeamName
print(Player1.TeamName) #print the value of base class from derived class
print(Player1.TeamOrigin) #print the value of member TeamOrigin of base class from derived class
class Player(Team):
'''
4 variables are passed into Contructor
'''
def __init__(self, PlayerName, PPoints, TeamName, TeamOrigin):
Team.__init__(self, TeamName, TeamOrigin)
self.PlayerName = PlayerName
self.PlayerPoints = PPoints
'''
Methods: ScoredPoints and setName
ScoredPoints increments the PlayerPoints by 1.
setName sets the name of Player
'''
def ScoredPoint(self):
self.PlayerPoints += 1
def setName(self, name):
self.PlayerName = name
'''
Override to print a readable string presentation of your object
'''
def __str__(self):
return self.PlayerName + " has scored: " + str(self.PlayerPoints) + " Points"
Player1 = Player("Sid", 0, "Sharks", "Chicago") #create an instance of a class Player
print(Player1.PlayerName) #print the value of member variable PlayerName
print(Player1.PlayerPoints) #print the value of member variable PlayerPoints
#Player1.DefineTeamName("Sharks")
print(Player1.TeamName) #print the value of base class from derived class
print(Player1.TeamOrigin) #print the value of member TeamOrigin of base class from derived class
Player1.ScoredPoint() #call method ScoredPoint
print(Player1.PlayerPoints) #access member PlayerPoints from outside the class and print it
Player1.setName("Lee") #call method setName
print(Player1.PlayerName) #print the value of member variable PlayerName
print(Player1) #print the string message.
================================================
FILE: classes/Introduction-to-Classes.py
================================================
##
# Introduction to Classes Lecture
##
# -*- coding: utf-8 -*-
"""
class is defined by a keyword class
Classname Team in defined
"""
class Team:
def __init__(self): #constructor with no arguments
self.TeamName = 'Name' #self represents the instance of the class and the variables of a class can be accessed using self
self.TeamOrigin = 'Origin' #set an attribute 'TeamOrigin to "Origin"
'''
DefinieTeamName and DefineTeamOrigin represents the methods of a class. Each method takes one
arguments
'''
def DefineTeamName(self, Name):
self.TeamName = Name
def DefineTeamOrigin(self, Origin):
self.TeamOrigin = Origin
Team1 = Team() #create an object of a class Team
'''
Methods and Member of a class can be accessed using a dot operator.
object.membername or object.methodname
'''
print(Team1.TeamName) #Access the member of a class using dot operator and print the value of a member
Team1.DefineTeamName("Tigers") #call methods of a class using a dot operator
print(Team1.TeamName) #print the value of a member TeamName
print(Team1.TeamOrigin) #print the value of a member TeamOrigin
Team1.DefineTeamOrigin("Chicago") #call method DefineTeamOrigin of a class Team
print(Team1.TeamOrigin) #print value of a member TeamOrigin
'''
Again Define a class Team
'''
class Team:
#constructor passes two variables Name and Origin. The
#default value of variable Name is "Name" and that of variable Origin is "Origin".
#If no values are passed through a constructor its default values are Name and Origin.
def __init__(self, Name = "Name", Origin = "Origin"): #constructor
self.TeamName = Name #member assignment
self.TeamOrigin = Origin #member assignment
def DefineTeamName(self, Name): #class method
self.TeamName = Name
def DefineTeamOrigin(self, Origin): #class method
self.TeamOrigin = Origin
Team1 = Team("Tigers", "Chicago") #creating an object of a class Team.
Team2 = Team("Hawks", "Newyork") #creating an instance of a class Team and passing two values.
Team3 = Team() #creating an object of a class with no values passed.
print(Team1.TeamName) #member can be accessed from outside the class using dot operator
Team1.DefineTeamName("Tigers") #call methods from outside the class
print(Team1.TeamName) #print the value of member TeamName
print(Team1.TeamOrigin) #print the value of member TeamOrigin
Team1.DefineTeamOrigin("Chicago") #call method DefineTeamOrigin
print(Team1.TeamOrigin) #print the value of member
print(Team2.TeamName) #print the value of member TeamName of object Team2
print(Team2.TeamOrigin) #print the value of member TeamOrigin of object Team2
print(Team3.TeamName) #print the value of member TeamName of object Team3
print(Team3.TeamOrigin) #print the value of member TeamOrigin of object Team3
================================================
FILE: classes/Pets-Part-A.py
================================================
##
# Pets, Part A Lecture
##
# -*- coding: utf-8 -*-
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,n,a,h,p):
# Define an attribute and assign the value of the n argument
self.name = n
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,a,h,p):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# getters
# Define a function to return an attribute of the class
def getName(self):
# The function will return the name attribute
return self.name
# setters
# Define a function which assigns a value to an attribute of the class
def setName(self,name):
self.name = name
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,a,h,p):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# getters
# Define a function to return an attribute of the class
def getName(self):
# The function will return the name attribute
return self.name
# setters
# Define a function which assigns a value to an attribute of the class
def setName(self,x):
self.name = x
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,a,h,p):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# getters
# Define a function to return an attribute of the class
def getName(self):
# The function will return the name attribute
return self.name
# Define a function to return an attribute of the class
def getAge(self):
# The function will return the age attribute
return self.age
# Define a function to return an attribute of the class
def getHunger(self):
# The function will return the hunger attribute
return self.hunger
# Define a function to return an attribute of the class
def getPlayful(self):
# The function will return the playful attribute
return self.playful
# setters
# Define a function which assigns a value to an attribute of the class
def setName(self,xname):
self.name = xname
# Define a function which assigns a value to an attribute of the class
def setAge(self,Age):
self.age = Age
# Define a function which assigns a value to an attribute of the class
def setHunger(self,hunger):
self.hunger = hunger
# Define a function which assigns a value to an attribute of the class
def setPlayful(self,play):
self.playful = play
# Create an instance of the Pet class and assign values to the attributes
Pet1 = Pet("Jim",3,False,True)
# Print the value returned by the getName() function of the Pet1 instance
# This will print "Jim"
print(Pet1.getName())
#Print the value returned by the getPlayful() function of the Pet1 instance
# This will print True
print(Pet1.getPlayful())
# Call the setName(xname) function of the Pet1 instance
# This will assign a new value to the name attribute of the Pet1 instance
Pet1.setName("Snowball")
# Print the value returned by the getName() function of the Pet1 instance
# This will print "Snowball"
print(Pet1.getName())
# Access and print the name attribute of the Pet1 instance
# This will print "Snowball"
print(Pet1.name)
# Assign the value "Jim" to the name attribute of the Pet1 instance
Pet1.name = "Jim"
# Access and print the name attribute of the Pet1 instance
# This will print "Jim"
print(Pet1.name)
================================================
FILE: classes/Pets-Part-B.py
================================================
##
# Pets, Part B Lecture
##
# -*- coding: utf-8 -*-
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,a,h,p):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# getters
# Define a function to return an attribute of the class
def getName(self):
# The function will return the name attribute
return self.name
# Define a function to return an attribute of the class
def getAge(self):
# The function will return the age attribute
return self.age
# Define a function to return an attribute of the class
def getHunger(self):
# The function will return the hunger attribute
return self.hunger
# Define a function to return an attribute of the class
def getPlayful(self):
# The function will return the playful attribute
return self.playful
# setters
# Define a function which assigns a value to an attribute of the class
def setName(self,xname):
self.name = xname
# Define a function which assigns a value to an attribute of the class
def setAge(self,Age):
self.age = Age
# Define a function which assigns a value to an attribute of the class
def setHunger(self,hunger):
self.hunger = hunger
# Define a function which assigns a value to an attribute of the class
def setPlayful(self,play):
self.playful = play
# The class is commented becuse two errors exist. One is in line 65 where the self argument is missing
# and the second error is in line 81 where the code should be self.FavoriteToy
# Define a class which inherits the Pet class
#class Dog(Pet):
#
# # Define a function which refers to the class in order to initiliaze the attributes of the class
# def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
# # Call the initializer of the parent class with the proper parameters
# # Error - the self argument is missing
# Pet.__init__(name,age,hunger,playful)
#
# # The following line will return an error if uncommented
# #self.__init__(name,age,hunger,playful)
#
# # Define an attribute and assign the value "None"
# self.breed = breed
# self.FavoriteToy = FavoriteToy
#
# # Define unction which refers to the class
# def wantsToPlay(self):
#
# # IF condition is True
# if self.playful == True:
# # Define the string which the function returns
# # Error - It should be self.FavoriteToy
# return("Dog wants to play with " + FavoriteToy)
#
# # ELSE condition
# else:
# # Define the string which the function returns
# return("Dog doesn't want to play")
#
# Create an instance of the Dog class and assign values to the attributes
#huskyDog = Dog("Snowball",5,False,True,"Husky","Stick")
#
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
#Play = huskyDog.wantsToPlay()
#
# Print the value of the Play variable
# This will print "Dog wants to play with Stick"
#print(Play)
# Define a class which inherits the Pet class
class Dog(Pet):
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
# Call the initializer of the parent class with the proper parameters
Pet.__init__(self,name,age,hunger,playful)
# The following line will return an error if uncommented
#self.__init__(name,age,hunger,playful)
# Define an attribute and assign the value "None"
self.breed = breed
self.FavoriteToy = FavoriteToy
# Define unction which refers to the class
def wantsToPlay(self):
# IF condition is True
if self.playful == True:
# Define the string which the function returns
return("Dog wants to play with " + self.FavoriteToy)
# ELSE condition
else:
# Define the string which the function returns
return("Dog doesn't want to play")
# Create an instance of the Dog class and assign values to the attributes
huskyDog = Dog("Snowball",5,False,True,"Husky","Stick")
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
Play = huskyDog.wantsToPlay()
# Print the value of the Play variable
# This will print "Dog wants to play with Stick"
print(Play)
# Assign the value False to the playful attribute of the huskyDog instance
huskyDog.playful = False
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
Play = huskyDog.wantsToPlay()
# Print the value of the Play variable
# This will print "Dog doesn't want to play"
print(Play)
================================================
FILE: classes/Pets-Part-C.py
================================================
##
# Pets, Part C Lecture
##
# -*- coding: utf-8 -*-
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,a,h,p):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# getters
# Define a function to return an attribute of the class
def getName(self):
# The function will return the name attribute
return self.name
# Define a function to return an attribute of the class
def getAge(self):
# The function will return the age attribute
return self.age
# Define a function to return an attribute of the class
def getHunger(self):
# The function will return the hunger attribute
return self.hunger
# Define a function to return an attribute of the class
def getPlayful(self):
# The function will return the playful attribute
return self.playful
# setters
# Define a function which assigns a value to an attribute of the class
def setName(self,xname):
self.name = xname
# Define a function which assigns a value to an attribute of the class
def setAge(self,Age):
self.age = Age
# Define a function which assigns a value to an attribute of the class
def setHunger(self,hunger):
self.hunger = hunger
# Define a function which assigns a value to an attribute of the class
def setPlayful(self,play):
self.playful = play
# Define a function which refers to the class and returns a string
def __str__(self):
# Define the string which the function returns
return (self.name + " is " +str(self.age) + " years old")
# The class is commented becuse two errors exist. One is in line 65 where the self argument is missing
# and the second error is in line 81 where the code should be self.FavoriteToy
# Define a class which inherits the Pet class
#class Dog(Pet):
#
# # Define a function which refers to the class in order to initiliaze the attributes of the class
# def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
# # Call the initializer of the parent class with the proper parameters
# # Error - the self argument is missing
# Pet.__init__(name,age,hunger,playful)
#
# # The following line will return an error if uncommented
# #self.__init__(name,age,hunger,playful)
#
# # Define an attribute and assign the value "None"
# self.breed = breed
# self.FavoriteToy = FavoriteToy
#
# # Define unction which refers to the class
# def wantsToPlay(self):
#
# # IF condition is True
# if self.playful == True:
# # Define the string which the function returns
# # Error - It should be self.FavoriteToy
# return("Dog wants to play with " + FavoriteToy)
#
# # ELSE condition
# else:
# # Define the string which the function returns
# return("Dog doesn't want to play")
#
# Create an instance of the Dog class and assign values to the attributes
#huskyDog = Dog("Snowball",5,False,True,"Husky","Stick")
#
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
#Play = huskyDog.wantsToPlay()
#
# Print the value of the Play variable
# This will print "Dog wants to play with Stick"
#print(Play)
# Define a class which inherits the Pet class
class Dog(Pet):
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
# Call the initializer of the parent class with the proper parameters
Pet.__init__(self,name,age,hunger,playful)
# The following line will return an error if uncommented
#self.__init__(name,age,hunger,playful)
# Define an attribute and assign the value of the breed argument
self.breed = breed
# Define an attribute and assign the value of the FavoriteToy argument
self.FavoriteToy = FavoriteToy
# Define unction which refers to the class
def wantsToPlay(self):
# IF condition is True
if self.playful == True:
# Define the string which the function returns
return("Dog wants to play with " + self.FavoriteToy)
# ELSE condition
else:
# Define the string which the function returns
return("Dog doesn't want to play")
# Define a class which inherits the Pet class
class Cat(Pet):
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,age,hunger,playful,place):
# Call the initializer of the parent class with the proper parameters
Pet.__init__(self,name,age,hunger,playful)
# Define an attribute and assign the value of the place argument
self.FavoritePlaceToSit = place
# Define unction which refers to the class
def wantsToSit(self):
# IF condition is True
if self.playful == False:
# Define the string which the function returns
# The following line will produce an error if uncommented due to the self.place part of the code
#print("The cat wants to sit in" ,self.place)
print("The cat wants to sit in" ,self.FavoritePlaceToSit)
# ELSE condition
else:
# Define the string which the function returns
print("The cat wants to play")
# Define a function which refers to the class and returns a string
def __str__(self):
# Define the string which the function returns
return (self.name + " likes to sit in " + self.FavoritePlaceToSit)
# Create an instance of the Dog class and assign values to the attributes
huskyDog = Dog("Snowball",5,False,True,"Husky","Stick")
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
Play = huskyDog.wantsToPlay()
# Print the value of the Play variable
# This will print "Dog wants to play with Stick"
print(Play)
# Assign the value False to the playful attribute of the huskyDog instance
huskyDog.playful = False
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
Play = huskyDog.wantsToPlay()
# Print the value of the Play variable
# This will print "Dog doesn't want to play"
print(Play)
# Create an instance of the Cat class and assign values to the attributes
typicalCat = Cat("Fluffy",3,False,False,"the sun ray")
# Call the wantsToSit() function of the typicalCat instance
# This will print "The cat wants to sit in the sun ray"
typicalCat.wantsToSit()
# This will print the returned string from the __str__ function of the typicalCat instance
# This will print "Fluffy likes to sit in the sun ray"
print(typicalCat)
# The __str__ function is not defined in the Dog function so it will return general inforamtion on the class
# This will print <class '__main__.Dog'>
print(Dog)
================================================
FILE: classes/Pets-Part-D.py
================================================
##
# Pets, Part D Lecture
##
# -*- coding: utf-8 -*-
# Define a class
class Pet:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,a,h,p):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the a argument
self.age = a
# Define an attribute and assign the value of the h argument
self.hunger = h
# Define an attribute and assign the value of the p argument
self.playful = p
# getters
# Define a function to return an attribute of the class
def getName(self):
# The function will return the name attribute
return self.name
# Define a function to return an attribute of the class
def getAge(self):
# The function will return the age attribute
return self.age
# Define a function to return an attribute of the class
def getHunger(self):
# The function will return the hunger attribute
return self.hunger
# Define a function to return an attribute of the class
def getPlayful(self):
# The function will return the playful attribute
return self.playful
# setters
# Define a function which assigns a value to an attribute of the class
def setName(self,xname):
self.name = xname
# Define a function which assigns a value to an attribute of the class
def setAge(self,Age):
self.age = Age
# Define a function which assigns a value to an attribute of the class
def setHunger(self,hunger):
self.hunger = hunger
# Define a function which assigns a value to an attribute of the class
def setPlayful(self,play):
self.playful = play
# Define a function which refers to the class and returns a string
def __str__(self):
# Define the string which the function returns
return (self.name + " is " +str(self.age) + " years old")
# The class is commented becuse two errors exist. One is in line 65 where the self argument is missing
# and the second error is in line 81 where the code should be self.FavoriteToy
# Define a class which inherits the Pet class
#class Dog(Pet):
#
# # Define a function which refers to the class in order to initiliaze the attributes of the class
# def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
# # Call the initializer of the parent class with the proper parameters
# # Error - the self argument is missing
# Pet.__init__(name,age,hunger,playful)
#
# # The following line will return an error if uncommented
# #self.__init__(name,age,hunger,playful)
#
# # Define an attribute and assign the value "None"
# self.breed = breed
# self.FavoriteToy = FavoriteToy
#
# # Define unction which refers to the class
# def wantsToPlay(self):
#
# # IF condition is True
# if self.playful == True:
# # Define the string which the function returns
# # Error - It should be self.FavoriteToy
# return("Dog wants to play with " + FavoriteToy)
#
# # ELSE condition
# else:
# # Define the string which the function returns
# return("Dog doesn't want to play")
#
# Create an instance of the Dog class and assign values to the attributes
#huskyDog = Dog("Snowball",5,False,True,"Husky","Stick")
#
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
#Play = huskyDog.wantsToPlay()
#
# Print the value of the Play variable
# This will print "Dog wants to play with Stick"
#print(Play)
# Define a class which inherits the Pet class
class Dog(Pet):
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
# Call the initializer of the parent class with the proper parameters
Pet.__init__(self,name,age,hunger,playful)
# The following line will return an error if uncommented
#self.__init__(name,age,hunger,playful)
# Define an attribute and assign the value of the breed argument
self.breed = breed
# Define an attribute and assign the value of the FavoriteToy argument
self.FavoriteToy = FavoriteToy
# Define unction which refers to the class
def wantsToPlay(self):
# IF condition is True
if self.playful == True:
# Define the string which the function returns
return("Dog wants to play with " + self.FavoriteToy)
# ELSE condition
else:
# Define the string which the function returns
return("Dog doesn't want to play")
# Define a class which inherits the Pet class
class Cat(Pet):
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,age,hunger,playful,place):
# Call the initializer of the parent class with the proper parameters
Pet.__init__(self,name,age,hunger,playful)
# Define an attribute and assign the value of the place argument
self.FavoritePlaceToSit = place
# Define unction which refers to the class
def wantsToSit(self):
# IF condition is True
if self.playful == False:
# Define the string which the function prints
# The following line will produce an error if uncommented due to the self.place part of the code
#print("The cat wants to sit in" ,self.place)
print("The cat wants to sit in" ,self.FavoritePlaceToSit)
# ELSE condition
else:
# Define the string which the function prints
print("The cat wants to play")
# Define a function which refers to the class and returns a string
def __str__(self):
# Define the string which the function returns
return (self.name + " likes to sit in " + self.FavoritePlaceToSit)
# Define a class
class Human:
# Define a function which refers to the class in order to initiliaze the attributes of the class
def __init__(self,name,Pets):
# Define an attribute and assign the value of the name argument
self.name = name
# Define an attribute and assign the value of the Pets argument
self.Pets = Pets
def hasPets(self):
# IF condition is True
# If the Human has Pets
if len(self.Pets) != 0:
# Define the string which the function returns
return "yes"
# ELSE condition
else:
# Define the string which the function returns
return "no"
# Create an instance of the Dog class and assign values to the attributes
huskyDog = Dog("Snowball",5,False,True,"Husky","Stick")
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
Play = huskyDog.wantsToPlay()
# Print the value of the Play variable
# This will print "Dog wants to play with Stick"
print(Play)
# Assign the value False to the playful attribute of the huskyDog instance
huskyDog.playful = False
# Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance
Play = huskyDog.wantsToPlay()
# Print the value of the Play variable
# This will print "Dog doesn't want to play"
print(Play)
# Create an instance of the Cat class and assign values to the attributes
typicalCat = Cat("Fluffy",3,False,False,"the sun ray")
# Call the wantsToSit() function of the typicalCat instance
# This will print "The cat wants to sit in the sun ray"
typicalCat.wantsToSit()
# This will print the returned string from the __str__ function of the typicalCat instance
# This will print "Fluffy likes to sit in the sun ray"
print(typicalCat)
# The __str__ function is not defined in the Dog function so it will return general inforamtion on the class
# This will print <class '__main__.Dog'>
print(Dog)
# This will print the returned string from the __str__ function of the huskyDog instance which is inherited by the Pet class
# This will print "Snowball is 5 years old"
print(huskyDog)
# Create an instance of the Human class and assign values to the attributes
yourAverageHuman = Human("Alice",[huskyDog,typicalCat])
# Assign to a variable the result returned by the hasPets() function of the yourAverageHuman instance
hasPet = yourAverageHuman.hasPets()
# Print the value of the hasPet variable
# This will print "yes"
print(hasPet)
# Print the first element in the Pets list attribute of the yourAverageHuman instance
# The huskyDog instance is the first element in the Pets list attribute of the yourAverageHuman instance
# This will print the returned string from the __str__ function of the huskyDog instance which is inherited by the Pet class
# This will print "Snowball is 5 years old"
print(yourAverageHuman.Pets[0])
# Print the second element in the Pets list attribute of the yourAverageHuman instance
# The typicalCat instance is the second element in the Pets list attribute of the yourAverageHuman instance
# This will print the returned string from the __str__ function of the typicalCat instance
# This will print "Fluffy likes to sit in the sun ray"
print(yourAverageHuman.Pets[1])
# Print the name attribute of the second element in the Pets list attribute of the yourAverageHuman instance
# The typicalCat instance is the second element in the Pets list attribute of the yourAverageHuman instance
# This will print "Fluffy"
print(yourAverageHuman.Pets[1].name)
# Print the name attribute of the first element in the Pets list attribute of the yourAverageHuman instance
# The huskyDog instance is the first element in the Pets list attribute of the yourAverageHuman instance
# This will print "Snowball"
print(yourAverageHuman.Pets[0].name)
================================================
FILE: dictionaries and sets/Dictionaries-and-Sets.py
================================================
##
# Dictionaries and Sets Lecture
##
# -*- coding: utf-8 -*-
"""
A set is a data structure in python like a list to store a variety of hetrogenous unique elements.
Hetrogenous means a set can contain primitive types integer , string , float in it.
Unique means that each element can occur only once in a set
"""
# Declaring a set 'Sets' with different string values in it
Sets={"Element1","Element2","Element1","Element4"}
# Printing variable 'Sets' using the 'print' function
print(Sets)
# Output
"""
{'Element1', 'Element4', 'Element2'}
"""
# Notice how the output is different from the input in two ways
# 1) Only unique elements are printed
# 2) Elements are not printed in the same order as they were stored because in sets order doesnt matter
# Here 'if' condition is used along with 'in' keyword to check whether the value "Element1" is present in set 'Sets'
if "Element1" in Sets:
# If the value "Element1" is found print "Yes" to console
print("Yes")
# Output
"""
Yes
"""
# Declaring a list variable 'CountryList' and assigning empty list to it by using '[]'
CountryList = []
# For loop is used with 'range(5)' indicating the loop will run 5 times from 0-4
for i in range(5):
# Taking input from user and assigning it to variable named 'Country' using 'input(range_value)' function
Country = input("Please Enter Your Country: ")
# 'append(variable_name)' function is used here which adds a new element into the list 'CountryList'
CountryList.append(Country)
# A new set 'CountrySet' is created using the 'set(variable_name)' function by passing the variable 'CountryList' which will convert the 'CountryList' to a set
CountrySet = set(CountryList)
# Printing list 'CountryList'
print(CountryList)
# Printing set 'CountrySet'
print(CountrySet)
# Output
"""
Please Enter Your Country: US
Please Enter Your Country: France
Please Enter Your Country: India
Please Enter Your Country: Brazil
Please Enter Your Country: France
['US', 'France', 'India', 'Brazil', 'France']
{'France', 'India', 'Brazil', 'US'}
"""
# First the program asks to entry country names 5 times and then the list and set is printed
# Notice how the set has changed order and only prints unique elements which is the property of set
# Here 'if' condition is used along with 'in' keyword to check whether the value "Brazil" is present in set 'CountrySet'
if "Brazil" in CountrySet:
# If the value "Brazil" is found print "attended" to console
print("attended")
# Output
"""
attended
"""
"""
A dictionary is another data structure in python that also supports hetrogenous data to be stored inside it.
Rather than using index like used in list , a dictionary supports key-value structure where the key is used like an index and value is stored besides it like how values are stored in a variable
A dictionary should also contain unique keys and can contain even lists inside of it.
"""
# Declaring a dictonary variable named 'Dictonary' and assigning keys and values to it
# "Key" , "Key1", "Key2" are the keys
# "Value" , "Value1" , "Value2" are the corresponding values
Dictionary={"Key":"Value","Key1":"Value1","Key2":"Value2"}
# Printing the dictonary variable 'Dictionary'
print(Dictionary)
# Output
"""
{'Key': 'Value', 'Key1': 'Value1', 'Key2': 'Value2'}
"""
# Declaring a list variable 'CountryList' and assigning empty list to it by using '[]'
CountryList = []
# For loop is used with 'range(5)' indicating the loop will run 5 times from 0-4
for i in range(5):
# Taking input from user and assigning it to variable named 'Country' using 'input(range_value)' function
Country = input("Please Enter Your Country: ")
# 'append(variable_name)' function is used here which adds a new element into the list 'CountryList'
CountryList.append(Country)
# Declaring a dictionary variable 'CountryDictionary' and assigning empty dictionary to it by using '{}'
CountryDictionary={}
# A for loop is used using 'for in syntax' to access the elements of list 'CountryList' and stored it in local variable named 'Country'
for Country in CountryList:
# If statement is used in order to check if the country name is present as a key in dictionary 'CountryDictionary'
if Country in CountryDictionary:
# upon finding the key the value is accessed using 'DictionaryName[key_name]' synatx and incremented one to it
CountryDictionary[Country] +=1
else:
# if the key is not found then creating a new key with country name and assigning one to it
# Notice how no error will be produced which was occuring in list when tried to access an element whcih didnt existed
CountryDictionary[Country] = 1
# Printing the dictionary variable 'CountryDictionary'
print(CountryDictionary)
# Output
"""
Please Enter Your Country: US
Please Enter Your Country: France
Please Enter Your Country: India
Please Enter Your Country: Brazil
Please Enter Your Country: France
{'France': 2, 'India': 1, 'Brazil': 1,'US': 1}
"""
# No order is mainatined in dictionary as well
================================================
FILE: dictionaries and sets/Examples-of-Dictionaries-and-Sets.py
================================================
##
# Examples of Dictionaries and Sets - Lecture
##
# Declaring a dictonary variable named 'BlackShoes' and assigning keys and values to it
# 42 , 41, 40 , 39 , 38 are the keys
# 2 , 3 , 4 , 1 , 0 are the corresponding values
BlackShoes={42:2,41:3,40:4,39:1,38:0}
# Printing the dictionary variable 'BlackShoes'
print(BlackShoes)
# Using a while loop which will run endlesly until a given condition is met
while (True): # True==True
# Taking input from user and assigning it to variable named 'purchaseSize' using 'input()' function
# notice \n in the code which is used to bring new line
# int(variable_name) converts the the variable to type integer
purchaseSize = int(input("Which shoe size would you like to buy?\n"))
# Accessing the value of key 'purchaseSize' and decreasing it by 1
BlackShoes[purchaseSize] -= 1 # BlackShoes[purchaseSize]=BlackShoes[purchaseSize]-1 both are same
# Printing the dictionary variable 'BlackShoes'
print(BlackShoes)
# Output
"""
{42: 2, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
42
{42: 1, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
39
{42: 1, 41: 3, 40: 4, 39: 0, 38: 0}
Which shoe size would you like to buy?
38
{42: 1, 41: 3, 40: 4, 39: 0, 38: -1}
"""
# Notice the issue in the code where the value of shoe size goes to negative and this needs to be fixed
# Declaring a dictonary variable named 'BlackShoes' and assigning keys and values to it
# 42 , 41, 40 , 39 , 38 are the keys
# 2 , 3 , 4 , 1 , 0 are the corresponding values
BlackShoes={42:2,41:3,40:4,39:1,38:0}
# Printing the dictionary variable 'BlackShoes'
print(BlackShoes)
# Using a while loop which will run endlesly until a given condition is met
while (True): # True==True
# Taking input from user and assigning it to variable named 'purchaseSize' using 'input()' function
# notice \n in the code which is used to bring new line
# int(variable_name) converts the the variable to type integer
purchaseSize = int(input("Which shoe size would you like to buy?\n"))
# If statement is used in order to check if the value of shoe size is greater than zero
if BlackShoes[purchaseSize] > 0:
# Accessing the value of key 'purchaseSize' and decreasing it by 1
BlackShoes[purchaseSize] -= 1 # BlackShoes[purchaseSize]=BlackShoes[purchaseSize]-1 both are same
# If size is not greater than zero then we print message using 'print()' function to user
else:
# Printing message
print("Shoes are no longer in stock")
# Printing the dictionary variable 'BlackShoes'
print(BlackShoes)
# Output
"""
{42: 2, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
42
{42: 1, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
38
Shoes are no longer in stock
{42: 1, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
"""
# Notice that the negative number problem is fixed but the loop is never ending and this needs to be fixed as well
# Declaring a dictonary variable named 'BlackShoes' and assigning keys and values to it
# 42 , 41, 40 , 39 , 38 are the keys
# 2 , 3 , 4 , 1 , 0 are the corresponding values
BlackShoes={42:2,41:3,40:4,39:1,38:0}
# Printing the dictionary variable 'BlackShoes'
print(BlackShoes)
# Using a while loop which will run endlesly until a given condition is met
while (True): # True==True
# Taking input from user and assigning it to variable named 'purchaseSize' using 'input()' function
# notice \n in the code which is used to bring new line
# int(variable_name) converts the the variable to type integer
purchaseSize = int(input("Which shoe size would you like to buy?\n"))
# If statement is used to check if the entered amount is less than 0
if purchaseSize < 0:
# if it is then 'break' keyword is used to terminate the loop
break
# If statement is used in order to check if the value of shoe size is greater than zero
if BlackShoes[purchaseSize] > 0:
# Accessing the value of key 'purchaseSize' and decreasing it by 1
BlackShoes[purchaseSize] -= 1 # BlackShoes[purchaseSize]=BlackShoes[purchaseSize]-1 both are same
# If size is not greater than zero then we print message using 'print()' function to user
else:
# Printing message
print("Shoes are no longer in stock")
# Printing the dictionary variable 'BlackShoes'
print(BlackShoes)
# Output
"""
{42: 2, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
38
Shoes are no longer in stock
{42: 2, 41: 3, 40: 4, 39: 1, 38: 0}
Which shoe size would you like to buy?
40
{42: 2, 41: 3, 40: 3, 39: 1, 38: 0}
Which shoe size would you like to buy?
-1
"""
================================================
FILE: error handling/main.py
================================================
##
# Error Handling Lecture
##
# float("123.4") - > 123.4
# float("N/A") - > error
"""
'try' 'except' is a way of handling errors in phyton
Its similiar to if else block the difference being that if any errors occur in the 'try' block , the 'expect' block will be called automatically
"""
try:
# Printing 'Hello' using the 'print()' function
print("Hello")
except:
# Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function
print("Entered exception")
# Output
"""
Hello
"""
# Hello is printed since no error occured in the try block
try:
# Printing 'Hello' using the 'print()' function
print(int("Hello"))
except:
# Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function
print("Entered exception")
# Output
"""
Entered exception
"""
# Entered exception is printed since error occured in the try block
try:
# Printing 'Hello' using the 'print()' function
print(int("Hello"))
except:
# Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function
print("Entered exception")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Entered exception
Past exception
"""
# Both the Entered exception and passed exception has been printed , this shows that the program doesnt stops if an error has occured
# Declared a variable 'keyword' with a value of "123"
keyword="123"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
except:
# Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function
print("Entered exception")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
123
Past exception
"""
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
except:
# Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function
print("Entered exception")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Entered exception
Past exception
"""
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
except:
# The pass keyword is used to indicate when no operation needs to be done in the block , this is also used to move the execution forward
pass
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Past exception
"""
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
except:
# The pass keyword is used to indicate when no operation needs to be done in the block , this is also used to move the execution forward
pass
# Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function
print("Entered exception")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Entered exception
Past exception
"""
# Both the Entered exception and Past exception has been printed , because 'pass' keyword is doesnt work like 'break'
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
except Exception as e:
# Printing the string version of the catched exception , The exception that has occured can be caught and stored in a variable
print(str(e))
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
invalid literal for int() with base 10: 'Hello'
Past exception
"""
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Pinting "got a ValueError" using 'print()' function
print("got a ValueError")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
got a ValueError
Past exception
"""
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Printing "got a ValueError" using 'print()' function
print("got a ValueError")
# except can be chained together like if elif statements
except:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
got a ValueError
Past exception
"""
# Since ValueError has occured only the 'except' block with 'ValueError' has been executed
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Printing "got a ValueError" using 'print()' function
print("got a ValueError")
# except can be chained together like if elif statements
except:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block
finally:
# Printing "finally" using 'print()' function
print("finally")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
got a ValueError
finally
Past exception
"""
# finally has also printed because it always executed
try:
# We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program
raise ValueError
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Printing "got a ValueError" using 'print()' function
print("got a ValueError")
# except can be chained together like if elif statements
except:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block
finally:
# Printing "finally" using 'print()' function
print("finally")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
got a ValueError
finally
Past exception
"""
# got a ValueError is printed because we rasied that error ourselves
try:
# We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program
raise NameError
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Printing "got a ValueError" using 'print()' function
print("got a ValueError")
# except can be chained together like if elif statements
except:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block
finally:
# Printing "finally" using 'print()' function
print("finally")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Other types of exception
finally
Past exception
"""
# Notice how "Other types of exception" is printed because we have not caught the 'NameError' in any 'except' block
try:
# We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program
raise NameError
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Printing "got a ValueError" using 'print()' function
print("got a ValueError")
# except can be chained together like if elif statements
except:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# We can raise the same error again to manually crash the program
raise
# The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block
finally:
# Printing "finally" using 'print()' function
print("finally")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
raise NameError
NameError
"""
try:
# We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program
# A message of "Error" has been passed when we 'raise' the error
raise NameError("Error")
# If known a specific error can be caught using the 'except' keyword
except ValueError:
# Printing "got a ValueError" using 'print()' function
print("got a ValueError")
# except can be chained together like if elif statements
# The error has been catched here and renamed it to 'e'
except Exception as e:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# Printing the String version of error 'e' using 'print()' function
print(str(e))
# The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block
finally:
# Printing "finally" using 'print()' function
print("finally")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Other tpyes of exception
Error
finally
Past exception
"""
# Notice the message "Error" has also been printed
# Declared a variable 'keyword' with a value of "Hello"
keyword="Hello"
try:
# Printing variable 'keyword' using the 'print()' function
print(int(keyword))
# We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program
# A message of "Error" has been passed when we 'raise' the error
raise NameError("Error")
# The error has been catched here and renamed it to 'e'
except Exception as e:
# Printing "Other types of exception" using 'print()' function
print("Other tpyes of exception")
# Printing the String version of error 'e' using 'print()' function
print(str(e))
# The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block
finally:
# Printing "finally" using 'print()' function
print("finally")
# Printing 'Past exception' using the 'print()' function
print("Past exception")
# Output
"""
Other tpyes of exception
invalid literal for int() with base 10: 'Hello'
finally
Past exception
"""
# Notice the message "Error" has also been printed
================================================
FILE: final project/Blackjack-Part-A.py
================================================
##
# Blackjack, Part A Lecture
##
# _*_ coding: utf-8 _*_
#Import shuffle function from random library
from random import shuffle
# Create a functions
def createDeck():
Deck = []
#Set a variable for faceValues
faceValues = ['A', 'J', 'Q', 'K']
for i in range(4): #There are 4 different suites
for card in range(2,11): #Adding numbers 2-10
Deck.append(str(card))
for card in faceValues:
Deck.append(card)
return Deck #Return products
#Set a variable to createDock function, and then print it
cardDeck = createDeck()
shuffle(cardDeck) #Mixing results with shuffle
print(cardDeck)
================================================
FILE: final project/Blackjack-Part-B.py
================================================
##
# Blackjack, Part B Lecture
##
# _*_ coding: utf-8 _*_
#Import shuffle function from random library
from random import shuffle
# Create a functions
def createDeck():
Deck = []
#Set a variable for faceValues
faceValues = ['A', 'J', 'Q', 'K']
for i in range(4): #There are 4 different suites
for card in range(2,11): #Adding numbers 2-10
Deck.append(str(card))
for card in faceValues:
Deck.append(card)
shuffle(Deck) #Mixing results with shuffle
return Deck #Return products
#Set a variable to createDock function, and then print it
cardDeck = createDeck()
print(cardDeck)
# Set a player class
class Player:
def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class
self.hand = hand
self.score = self.setScore()
print(self.score)
self.money = money
def __str__(self): #__str__ will return a human readable string
currentHand = " " #slef.hand = ["A","10"]
for card in self.hand:
currentHand += str(card) + " "
#Set a variable for finalStatus, and then return it
finalStatus = currentHand + "score " + str(self.score)
return finalStatus
#Set a setScore function, and then return it
def setScore(self) :
self.score = 0
print(self.score)
#Set a Dictionary for faceCards
faceCardsDict = {"A":11,"J":10,"Q":10,"K":10,
"2":2,"3":3,"4":4,"5":5,"6":6,
"7":7,"8":8,"9":9,"10":10}
#Set a variable for aceCounter
aceCounter = 0
#Convert card into score
for card in self.hand:
self.score += faceCardsDict[card]
if card == "A":
aceCounter +=1
if self.score > 21 and aceCounter !=0:
self.score -= 10
aceCounter -= 1
return self.score
#Set a variable for player1, and then print it
player1 = Player(["3","7","5"])
print(player1)
================================================
FILE: final project/Blackjack-Part-C.py
================================================
##
# Blackjack, Part C Lecture
##
# _*_ coding: utf-8 _*_
#Import shuffle function from random library
from random import shuffle
# Create a functions
def createDeck():
Deck = []
#Set a variable for faceValues
faceValues = ['A', 'J', 'Q', 'K']
for i in range(4): #There are 4 different suites
for card in range(2,11): #Adding numbers 2-10
Deck.append(str(card))
for card in faceValues:
Deck.append(card)
shuffle(Deck) #Mixing results with shuffle
return Deck #Return products
#Set a variable to createDock function, and then print it
cardDeck = createDeck()
print(cardDeck)
# Set a player class
class Player:
def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class
self.hand = hand
self.score = self.setScore()
self.money = money
def __str__(self): #__str__ will return a human readable string
currentHand = " " #slef.hand = ["A","10"]
for card in self.hand:
currentHand += str(card) + " "
#Set a variable for finalStatus, and then return it
finalStatus = currentHand + "score " + str(self.score)
return finalStatus
#Set a setScore function to count score, and then return it
def setScore(self) :
self.score = 0
#Set a Dictionary for faceCards
faceCardsDict = {"A":11,"J":10,"Q":10,"K":10,
"2":2,"3":3,"4":4,"5":5,"6":6,
"7":7,"8":8,"9":9,"10":10}
#Set a variable for aceCounter
aceCounter = 0
#Convert card into score
for card in self.hand:
self.score += faceCardsDict[card]
if card == "A":
aceCounter +=1
if self.score > 21 and aceCounter != 0:
self.score -= 10
aceCounter -= 1
return self.score
#Set a hit function to select a card, and then return it
def hit(self,card):
self.hand.append(card)
self.score = self.setScore()
#Set a function to add new player
def play(self,newHnad):
self.hand = newHnad
self.score = self.setScore()
#Set a function to put out money
def pay(self,amount):
self.money -= amount #decrease money from balance
#Set a function for winner
def win(self,amount):
self.money += amount # double amount for winner
#Set a variable for player1, and then print it
Player1 = Player(["3","7","5"])
print(Player1)
Player1.hit("A")
Player1.hit("A")
print(Player1) #Score after selecting a card
Player1.pay(20)
print(Player1.money) #Balance after puting money
Player1.win(40)
print(Player1.money) #Balance after winning
Player1.play(["A","K"])
print(Player1) #Score for new player
print(Player1.money) #After restarting the game
================================================
FILE: final project/Blackjack-Part-D.py
================================================
##
# Blackjack, Part D Lecture
##
# _*_ coding: utf-8 _*_
#Import shuffle function from random library
from random import shuffle
# Create a functions
def createDeck():
Deck = []
#Set a variable for faceValues
faceValues = ['A', 'J', 'Q', 'K']
for i in range(4): #There are 4 different suites
for card in range(2,11): #Adding numbers 2-10
Deck.append(str(card))
for card in faceValues:
Deck.append(card)
shuffle(Deck) #Mixing results with shuffle
return Deck #Return products
#Set a variable to createDock function, and then print it
cardDeck = createDeck()
print(cardDeck)
# Set a player class
class Player:
def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class
self.hand = hand
self.score = self.setScore()
self.money = money
self.bet = 0
def __str__(self): #__str__ will return a human readable string
currentHand = " " #slef.hand = ["A","10"]
for card in self.hand:
currentHand += str(card) + " "
#Set a variable for finalStatus, and then return it
finalStatus = currentHand + "score " + str(self.score)
return finalStatus
#Set a setScore function to count score, and then return it
def setScore(self) :
self.score = 0
#Set a Dictionary for faceCards
faceCardsDict = {"A":11,"J":10,"Q":10,"K":10,
"2":2,"3":3,"4":4,"5":5,"6":6,
"7":7,"8":8,"9":9,"10":10}
#Set a variable for aceCounter
aceCounter = 0
#Convert card into score
for card in self.hand:
self.score += faceCardsDict[card]
if card == "A":
aceCounter +=1
if self.score > 21 and aceCounter != 0:
self.score -= 10
aceCounter -= 1
return self.score
#Set a hit function to select a card, and then return it
def hit(self,card):
self.hand.append(card)
self.score = self.setScore()
#Set a function to add new player
def play(self,newHnad):
self.hand = newHnad
self.score = self.setScore()
#Set a function to put out money
def betMoney(self,amount):
self.money -= amount #decrease money from balance
self.bet += amount #
#Set a function for winner
def win(self,result):
if result == True:
if self.score == 21 and len(self.hand) == 2: # Set required score for winning blackjack
self.money += 2.5*self.bet # if player win with a blackjack
else:
self.money += 2*self.bet # if player win without a blackjack
self.bet = 0 # Reset the bet
else:
self.bet = 0 # If player loose a bet
#Set a variable for player1, and then print it
Player1 = Player(["3","7","5"])
print(Player1)
Player1.hit("A")
Player1.hit("A")
print(Player1) #Score after selecting a card
Player1.betMoney(20)
print(Player1.money,Player1.bet) #Balance after puting money and bet amount
Player1.win(True)
print(Player1.money,Player1.bet) #Balance after winning without a blackjack
Player1.play(["A","K"])
print(Player1) #Score for new player
Player1.betMoney(20)
Player1.win(True)
print(Player1.money,Player1.bet) #Balance after winning with a blackjack
================================================
FILE: final project/Blackjack-Part-E.py
================================================
##
# Blackjack, Part E Lecture
##
# _*_ coding: utf-8 _*_
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from random import shuffle #import shuffle function from random module
def createDeck(): #define a function to Create the Deck
Deck = [] #create Deck as a List
faceValues = ["A", "J", "Q", "K" ] #define faceValues with a list
for i in range(4): #add values 4 times via a for loop so there are 4 different suits
for card in range(2,11): #loop through values between 2 to 10 not including 11. tese numbers represent cards
Deck.append(str(card)) #add cards to Deck. converting Integers to Strins for more convinience
for card in faceValues: #loop through faceValues list
Deck.append(card) #add faceValues to Deck
shuffle(Deck) #suffle the Deck
return Deck #return the Deck
class Player: #here we will be creating Player class
def __init__(self,hand = [],money = 100): #__init__ function used to initialize a object. it is usually used to assign values for attributes of the object created by class
self.hand = hand #define hand attribute for the class player
self.score = self.setScore() #define score attribute for the Player and call to setScore function. return value from setScore will be assigned to score attribute
self.money = money #define money attribute for the class player
self.bet = 0 #add a new attribute to Player called bet.
def __str__(self): #overriding the __str__ function. it is used to print hand and score of the player
CurrentHand = "" #define a temporary variable to hold the current cards of the player
for card in self.hand: #loop through the player 'hand' and add each card to CurrentHand
CurrentHand += str(card) + " " #it is more convinient to add cards as strings to CurrentHand. so use str(card)
finalStaus = CurrentHand + "score: " + str(self.score) #finalStaus will be in the format "A 10 score:21" "A 10 2 score:23"
return finalStaus #return finalStatus. which is printed by this function.
def setScore(self): #define setScore method for player class
self.score = 0 #it is good practice to initialize the variable.
faceCardsDict = {"A":11, "J":10, "Q":10, "K":10, #create a Dictionary and map each card a value
"2":2, "3":3, "4":4, "5":5, "6":6,
"7":7, "8":8, "9":9, "10":10}
aceCounter = 0 #You need to count the number of Aces. here counter is initialized.
for card in self.hand: #loop throught the hand of the player and add value of each card to players score
self.score += faceCardsDict[card]
if card == "A": #if the card is a Ace,
aceCounter +=1 #then increment the aceCounter
if self.score > 21 and aceCounter != 0: #if the acore is above 21 and player has a Ace
self.score -= 10 #new Ace value will be 1. hence score will be reduced by 10
aceCounter -= 1 #as one Ace is consumed, reduce 1 from aceCounter
return self.score #return the score of the player
def hit(self, card): #hit function is used to ada a card to hand
self.hand.append(card) #new card will be append to the Player's hand
self.score = self.setScore() #player score will be recalculated
def play(self, newHand): #play function will be used to restart the game or resest the hand. it will take a 'hand' as an argument
self.hand = newHand #new hand will be assigned to Player's hand
self.score = self.setScore() #recalculate the Player's score
def betMoney(self,amount): #change pay function to betMoney
self.money -= amount #reduce bet amount from player's money
self.bet += amount #add bet amount to Player's bet amount
def win(self, result): #change win function. now it takes boolean argument.
if result == True: #if win funtion recieve true
if self.score == 21 and len(self.hand) == 2: #if Blackjack is earned
self.money += 2.5 * self.bet #2.5 times of bet amount will be added to Player's money.
else: #if win but not a Blackjack
self.money += 2 * self.bet #two times of bet amount will be added to Players money
self.bet = 0 #we should erase bet amount after that
else:
self.bet = 0 #if player is lost we only have to do erase bet amount. so it won't effect future play
def printHouse(House): #this method will print all cards of House except first card
for card in range(len(House.hand)): #loop through the hand of House
if card == 0: #if it is the first card
print("X", end=" ") #just print 'X'. continue printing in same line with space gap
elif card == len(House.hand) - 1: #if the card is the last one in the hand
print(House.hand[card]) #just print it. no need of space
else: #else
print(House.hand[card], end=" ") #just print the card and keep a gap of space
cardDeck = createDeck() #what is returned from the createDeck() function will be assigned to 'cardDeck'
print(cardDeck) #print the cardDeck
firstHand = [cardDeck.pop(),cardDeck.pop()] #add last two cards to firstHand,
secondHand = [cardDeck.pop(),cardDeck.pop()] #add next last two cards to secondHand
Player1 = Player(firstHand) #Player1 recieve firstHand
House = Player(secondHand) #House recieve secondHand
print(Player1) #Print hand and score of Player1
printHouse(House) #Print hand and score of House
while(Player1.score < 21): #this loop will continue as long as Player1 score is less than 21
action = input("Do you want another card?(y/n)") #ask from user whether he needs another card. recieve user input
if action == "y": #if he press 'y'
Player1.hit(cardDeck.pop()) #Player1 recieve a new card
print(Player1) #Print hand and score of Player1
printHouse(House) #Print hand and score of House
else:
break #if user press 'n', exit the loop
================================================
FILE: final project/Blackjack-Part-F.py
================================================
##
# Blackjack, Part F Lecture
##
# _*_ coding: utf-8 _*_
from __future__ import print_function
#Import shuffle function from random library
from random import shuffle
# Set a createDeck function
def createDeck():
Deck = []
#Set a variable for faceValues
faceValues = ['A', 'J', 'Q', 'K']
for i in range(4): # There are 4 different suites
for card in range(2,11): # Adding numbers 2-10
Deck.append(str(card))
for card in faceValues:
Deck.append(card)
shuffle(Deck) # Mixing results with shuffle
return Deck # Return products
# Set a player class
class Player:
def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class
self.hand = hand
self.score = self.setScore()
self.money = money
self.bet = 0
def __str__(self): #__str__ will return a human readable string
currentHand = " "
for card in self.hand:
currentHand += str(card) + " "
#Set a variable for finalStatus, and then return it
finalStatus = currentHand + "score " + str(self.score)
return finalStatus
#Set a setScore function to count score, and then return it
def setScore(self) :
self.score = 0
#Set a Dictionary for faceCards
faceCardsDict = {"A":11,"J":10,"Q":10,"K":10,
"2":2,"3":3,"4":4,"5":5,"6":6,
"7":7,"8":8,"9":9,"10":10}
#Set a variable for aceCounter
aceCounter = 0
#Convert card into score
for card in self.hand:
self.score += faceCardsDict[card]
if card == "A":
aceCounter +=1
if self.score > 21 and aceCounter != 0:
self.score -= 10
aceCounter -= 1
return self.score
#Set a hit function to select a card, and then return it
def hit(self,card):
self.hand.append(card)
self.score = self.setScore()
#Set a function to add new player
def play(self,newHand):
self.hand = newHand
self.score = self.setScore()
#Set a function to put out money
def betMoney(self,amount):
self.money -= amount # Decrease money from balance
self.bet += amount
#Set a function for winner
def win(self,result):
if result == True:
if self.score == 21 and len(self.hand) == 2: # Set required score for winning blackjack
self.money += 2.5*self.bet # if player win with a blackjack
else:
self.money += 2*self.bet # if player win without a blackjack
self.bet = 0 # Reset the bet
else:
self.bet = 0 # If player loose a bet
#Set a function to check the result win or draw
def draw(self):
self.money += self.bet
self.bet = 0
#Set a function to check blackjack
def hasBlackjack(self):
if self.score == 21 and len(self.hand) == 2:
return True
else:
return False
# Set a printHouse function to print the house and score
def printHouse(House):
for card in range(len(House.hand)):
if card == 0:
print("X",end = " ")
elif card == len(House.hand) -1:
print(House.hand[card])
else:
print(House.hand[card], end = " ")
#Set a variable to createDock function, and then print it
cardDeck = createDeck()
# Pop function select the last shuffle number
# Set a variable for First players last shuffle number
firstHand =[cardDeck.pop(),cardDeck.pop()]
# Set a variable for Second players last shuffle number
secondHand = [cardDeck.pop(),cardDeck.pop()]
# Set a variable to First player score, and then print it
Player1 = Player(firstHand)
# Set a variable to Second player score, and then print it
House = Player(secondHand)
cardDeck = createDeck()
while(True):
if len(cardDeck) <20:
cardDeck = createDeck()
firstHand = [cardDeck.pop(),cardDeck.pop()]
secondHand = [cardDeck.pop(),cardDeck.pop()]
Player1.play(firstHand)
House.play(secondHand)
# Set a variable to ask player for bet amount
Bet = int(input("Please enter your bet: "))
print(cardDeck)
Player1.betMoney(Bet)
printHouse(House)
print(Player1)
#Define results on Blackjack win
if Player1.hasBlackjack():
if House.hasBlackjack():
Player1.draw()
else:
Player1.win(True)
else:
# if players score is below 21, ask him to add more card
while(Player1.score < 21):# While (true==true)
action = input("Do you want another card?(y/n): ")
if action == "y":
Player1.hit(cardDeck.pop())
print(Player1)
printHouse(House)
else:
break
# Define how long player can add card
while(House.score < 16):
print(House)
House.hit(cardDeck.pop())
if Player1.score > 21:
if House.score > 21:
Player1.draw()
else:
Player1.win(False)
elif Player1.score > House.score:
Player1.win(True)
elif Player1.score == House.score:
Player1.draw()
else:
if House.score > 21:
Player1.win(True)
else:
Player1.win(False)
print(Player1.money)
print(House)
================================================
FILE: functions/main.py
================================================
##
# Functions Lecture
##
# -*- coding: utf-8 -*-
# Assignment on Functions
'''
Syntax for a function:
def FunctionName(Input):
Action
return Output
'''
# define a function using a keyword def
'''
function name: addOne
input: Number
output: Output
'''
#The function addOne takes a Number as input and then adds 1 and then returns it
def addOne(Number):
Output = Number + 1 #add 1 to a Number
return Output #return output
Var = 0 #intialize to 0
print(Var) #print value
'''
an argument is passed through a function.
'''
Var2 = addOne(Var) #calling a function addOne and is assigned to a variable
Var3 = addOne(Var2) #calling a function addOne and is assigned to a variable
Var4 = addOne(2) #a value is directly passed through a function and the output is
#assigned to a variable
#print Var2, Var3 and Var4
print(Var2)
print(Var3)
print(Var4)
Var4 = addOne(2.1) #float value is passed into a function
print(Var4) #print the value
Var4 = addOne(2.1+3.4) #two float numbers are added and passed into a function
print(Var4) #print the value
'''
function addOneAddTwo takes two variable as an input and then returns a variable.
'''
def addOneAddTwo(NumberOne, NumberTwo):
Output = NumberOne + 1 #add 1 to a variable NumberOne
# Output = Output + NumberTwo + 2
Output += NumberTwo + 2 #add 2, NumberTwo variable and Output
return Output #return Output variable
Sum = addOneAddTwo(1, 2) #call the function addOneTwo and pass two arguments directly
print(Sum) #print output
Sum = addOneAddTwo(Var2, Var3) #call the function addOneTwo and pass two variable arguments
print(Sum) #print output
================================================
FILE: importing/Alternative-Import-Methods.py
================================================
##
# Alternative Import Methods Lecture
##
# _*_ coding: utf-8 _*_
# Importing the library 'random' as 'r' where 'r' is its nickname
## from random import *
import random as r
# import the function from the library
## from random import randInt
# Assign a random integer value to the variable 'randInt'
## random.seed(1)
randInt = r.randint(0,10) #start<=N<=end
print(randInt)
# Assign a random float value to the variable 'randFloat' between 0 and 1 only
randFloat = r.random() #0.0<=N<1.0
print(randFloat)
# Assign a random float value to the variable 'randFloat' between any specified range
randUniform = r.uniform(1,1100) #start<=N<=end
print(randUniform)
# Create a list 'simpleList' and print a random integer from that list
simpleList = [1,3,5,7,11]
pickElement = r.choice(simpleList)
print(pickElement)
print(simpleList)
# shuffle the list using 'shuffle' function of 'random' library
r.shuffle(simpleList)
print(simpleList)
================================================
FILE: importing/Guessing-Game-Part-A.py
================================================
##
# Guessing Game, Part A Lecture
##
# _*_ coding: utf-8 _*_
# import the fuction 'randint' from library random
from random import randint
## randint(a,b) -> a<=N<=b
# set the variable 'randVal' with a random value between 0 to 100
randVal = randint(0,100)
while(True):
guess = int(input('Please enter your guess:'))
# check if 'guess' and 'randVal' are equal
if guess == randVal:
# get out of the loop if they are equal
break
# check if 'guess' is less than 'randVal'
elif guess < randVal:
print('Your guess was too low')
# check if 'guess' is more than 'randVal'
else:
print('Too high')
# print the correct answer
print('You guessed correctly with:',guess)
================================================
FILE: importing/Guessing-Game-Part-B.py
================================================
##
# Guessing Game, Part B Lecture
##
# _*_ coding: utf-8 _*_
# import 'random' fuction of 'random' library
from random import random
# import 'clock' function of 'time' library
from time import clock
# Set the value of variable 'randVal' as a random number
randVal = random() # 0.0 <=N <1.0
## print(randVal)
## time.clock() -> timevalue
## time.clock() -> timevalue2
# Set the values of upper and lower as 1.0 and 0.0 respectively
upper = 1.0
lower = 0.0
## guess = 0.5 -> Too Low -> lower = 0.5
## guess = 0.9 -> Too High -> upper = 0.9
## guess = 0.5
# Set the variable 'startTime' as the currect processor time
startTime = clock()
while(True):
# set the variable 'guess' as the avarage of 'upper' and 'lower'
guess = (upper+lower)/2
# check if 'guess' and 'randVal' are equal
if guess == randVal:
# get out of the loop if they are equal
break
# check if 'guess' is less than 'randVal'
elif guess<randVal:
lower = guess
# check if 'guess' is more than 'randVal'
else :
upper = guess
# Set the variable 'endTime' as the currect processor time
endTime = clock()
# print the 'guess'
print(guess)
# print the time it took to run the loop
print('It took us:', endTime-startTime,'seconds')
================================================
FILE: importing/Introduction-to-Importing.py
================================================
##
# Introduction to Importing Lecture
##
# _*_ coding: utf-8 _*_
# Importing the library 'random' as 'r' where 'r' is its nickname
import random as r
# Assign a random integer value to the variable 'randInt'
# random.seed(1)
randInt = r.randint(0,10) #start<=N<=end
print(randInt)
# Assign a random float value to the variable 'randFloat' between 0 and 1 only
randFloat = r.random() #0.0<=N<1.0
print(randFloat)
# Assign a random float value to the variable 'randFloat' between any specified range
randUniform = r.uniform(1,11) #start<=N<=end
print(randUniform)
================================================
FILE: importing/Math-Library.py
================================================
##
# Math Library Lecture
##
# _*_ coding: utf-8 _*_
# import the library 'math'
import math
# square root of the variable 'Val' using 'sqrt' function
Val = 3.14
sqrtVal = math.sqrt(Val)
print(sqrtVal) # sqrtVal**(2) = sqrtVal^2
# exponential value of the variable 'Val' using 'exp' function
expVal = math.exp(Val) #e^(Val)
print(expVal)
# factorial of the variable 'Val' using 'factorial' function and print it
factVal = math.factorial(math.floor(Val)) #5! = 5*4*3*2*1
print(factVal)
# sine value of the variable 'Val' using sin function and print it
sinVal = math.sin(Val)
print(sinVal)
# the nearest integer which is less than the value of 'Val' and print it
floorVal = math.floor(Val)
print(floorVal)
# the nearest integer which is greater than the value of 'Val' and print it
ceilingVal = math.ceil(Val)
print(ceilingVal)
================================================
FILE: importing/Time-Library.py
================================================
##
# The Time Library Lecture
##
# _*_ coding: utf-8 _*_
# import the 'time' library and print the time, processor takes to print the "Hello World"
import time
currentTime = time.clock()
print("Hello")
print("World")
pastTime = time.clock()
print(pastTime - currentTime)
# sleep the processor for 3 seconds using 'sleep' function
print("1")
time.sleep(3)
print("2")
# print the integers from 1 to 10 in the interval break of 1 second
for i in range(1,11):
print(i)
time.sleep(1)
================================================
FILE: input and output/File-IO.py
================================================
##
# File Input and Output Lecture
##
# _*_ coding: utf-8 _*_
# Genral form to open a file with an option ("r":read, "w": write, "a": append, "r+": read and write)
# File = open("Filename","r") # "r", "w", "a", "r+"
# Once done with the file we can close it
# File.close()
# Create a list: sperate elements by a comma
Countries = ["London", "Paris", "New York", "Utah", "IceLand"]
# Let's call our list a VacationSpots
VacationSpots = ["London", "Paris", "New York", "Utah", "IceLand"]
# Creat a file
# The option "w" will create the file if it doesn't exist but will override it if it exists already
# This will create the file at the same folder of your python file code
VacationFile = open("VacationPlaces","w")
# We loop over our list to take each element and put it inside our file
for Spots in VacationSpots:
VacationFile.write(Spots) # Spots in this case has to be a string
# Or convert it to string if it is not
# VacationFile.write(str(Spots))
# close the file
VacationFile.close()
print("done")
# Open the file again: it is not mandatory to use the same variable
VacationFile = open("VacationPlaces","r")
# The following instruction will read all the content of our file and assign it to TheWholeFile
# Note: this is usefull for small files but we will see other methods for bigger files
TheWholeFile = VacationFile.read()
print(TheWholeFile)
# Always close the file once done using it
VacationFile.close()
# We notice that the ouptut doesn't look very well
# The pointer will just write any new element directly after the previous one
# LondonParisNew YorkUtahIceLand
# To solve this: we can add a space after each write operation
VacationFile = open("VacationPlaces","w")
for Spots in VacationSpots:
# VacationFile.write(Spots+ " ")
# Or to separate them by ","
# VacationFile.write(Spots+ ", ")
# We can also put elements in a new line
VacationFile.write(Spots+ "\n")
VacationFile.close()
# We can read the file one by one
# Line will have all the data for one line
VacationFile = open("VacationPlaces","r")
# We can read each line into a variable
# We have a pointer that will read the file from the beginning
FirstLine = VacationFile.readline()
print(FirstLine)
# If we read the line again, the pointer will move to the next element
SecondLine = VacationFile.readline()
print(SecondLine)
# In this case we will start by the third line
for line in VacationFile:
print(line) # We will a blank line separator since we have put \n between our elements
# To specify how the end of line should be
print(line, end = "") # take away the newLine
VacationFile.close()
# Append a new spot
FinalSpot = "Thailand\n"
# Remember to not use "w" option, otherwise all the content of the file will be deleted
VacationFile = open("VacationPlaces", "a") # use the append option
# Write to the end of the file
VacationFile.write(FinalSpot)
VacationFile.close()
VacationFile = open("VacationPlaces","r") # Open file as reading
# Loop over the file, line by line
for line in VacationFile:
print(line, end = "")
VacationFile.close()
# Another method to open a file without having to close it at the end
# The file will be saved inside the variable VacationFile
with open("VacationPlaces","r") as VacationFile:
for line in VacationFile:
print(line)
# The file is closed automatically
# So the below instruction is no more valid since file is already closed
# VacationFile.read()
"""
# We can do the above operation for multiple files
# Example : read the content from 5 files (VacationPlaces1 ... VacationPlaces4)
for i in range(5):
with open("VacationPlaces"+str(i),"r") as VacationFile:
for line in VacationFile:
print(line)
"""
================================================
FILE: input and output/Introduction-to-IO.py
================================================
##
# Introduction to Input and Output Lecture
##
# _*_ coding: utf-8 _*_
# Display a message to the user to write an input that will be saved into the Var variable
Var = input("Message to the user")
Name = input("Please to enter your name: ")
# Read back the name
print(Name)
# All inputs are going to be imported as strings
Age = input("Please enter your age: ")
# Print out the Age
print(Age)
# However, we cannot print the Age + 1 for example since Age is a string (ie: "21"+1)
#print(Age+1)
# For example: this will work
print("21"+"1") # Gives 211
# Or in case both of them are integers
print(21+1)
# So we need to convert our input to an integer
# But note that you can not put caracters like "twenty one"
Age = int(input("Please enter your age: ")) # Age here will be an integer
# The following instruction becames valid for now
print(Age+1)
# Again, this is not valid because we are trying to add an integer(Age) to a string("1")
#print(Age+"1")
# We can for now convert both of the inputs to strings
print(str(Age)+"1") # str(Age) = str(21) -> "21"
# Age = 21
# Another method is to convert the Age later
Age = input("Please enter your age: ") # Age here will be an integer
# The following instruction becames valid for now
print(int(Age)+1) # This will temporary convert Age string to integer
# Create an empty list
Scores = []
# Ask the user for 5 different scores using a loop
for i in range(5): # Create a range , variable i will start by value 0 to 4 at the end of the loop ([0,4[)
# currentScore = int(input("Please enter the score: "))
# Or we can also print which score to put: but accept only integers
# currentScore = int(input("Please enter the score " + str(i+1) + ": ")) # Add 1 because i will start by 0
# We can also convert it to float so also decimals could be taken into account
currentScore = float(input("Please enter the score " + str(i+1) + ": "))
# Append the score to our list (at the end) using the predefined function : append
Scores.append(currentScore)
# Print the score entered by the user, we use comma to format our variable to string automatically
# print("The score you entered was: ",currentScore)
# We can put something else afterwards
# print("The score you entered was: ",currentScore, "nice")
# We can use "\n" to put our score in a new line: "\" is used to mention a special caracter
# print("The score you entered was:\n",currentScore)
# To convert our score to an integer
print("The score you entered was: \n"+str(currentScore))
# print is actually a function that takes those inputs separated by "," and prints them
# def FunctionName(input1,input2):
# Action
# What happens inside our loop ? (Below an example for integers)
# Scores = []
# Scores = [70] # First loop i = 0
# Scores = [70, 12] # First loop i = 1
# Scores = [70, 12, 45] # First loop i = 2
# Scores = [70, 12, 45, 56] # First loop i = 3
# Scores = [70, 12, 45, 56, 99] # First loop i = 4
# Print the list Scores
print(Scores)
================================================
FILE: input and output/Participant-Data-Part-A.py
================================================
##
# Participant Data, Part A Lecture
##
# _*_ coding: utf-8 _*_
# Create the number of participants that are allowed to register
ParticipantNumber = 2
ParticipantData = [] # For now an empty list to store Participant Data
# Create a counter for the registered participants
registeredParticipants = 0
# This is the file where we are going to write our data
outputFile = open("PaticipantData.txt","w")
# Loop over the participants
while(registeredParticipants < ParticipantNumber):
# Add a temporary data holder as a list
tempPartData = [] # name, country of origin, age
# Ask for user input to add his name
name = input("Please enter your name: ")
# Append the name to the temporary data
tempPartData.append(name)
country = input("Please enter your country of origin: ")
# Append the country to the temporary data
tempPartData.append(country)
# Ask for user input to add his age
age = int(input("Please enter your age: ")) # Convert the input to integer
# Append the age to the temporary data
tempPartData.append(age)
# Print the tempData
print (tempPartData)
# Save our temporary data to the ParticipantData
ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]]
print(ParticipantData)
# Increase the registeredParticipants number
registeredParticipants +=1 # = registeredParticipants + 1
# Write everything to a file
# Each participant is represented by a list
for participant in ParticipantData:
# loop over particpant data
for data in participant:
outputFile.write(str(data)) # Convert data to string and write it to the file
# We need to add extra formatting otherwise we will have it similar to MaxU.s.21
outputFile.write(" ") # MaxU.s.21
# Add each participant data in a new line
outputFile.write("\n")
outputFile.close()
================================================
FILE: input and output/Participant-Data-Part-B.py
================================================
##
# Participant Data, Part B Lecture
##
# _*_ coding: utf-8 _*_
# Create the number of participants that are allowed to register
ParticipantNumber = 5
ParticipantData = [] # For now an empty list to store Participant Data
# Create a counter for the registered participants
registeredParticipants = 0
# This is the file where we are going to write our data
outputFile = open("PaticipantData.txt","w")
# Loop over the participants
while(registeredParticipants < ParticipantNumber):
# Add a temporary data holder as a list
tempPartData = [] # name, country of origin, age
# Ask for user input to add his name
name = input("Please enter your name: ")
# Append the name to the temporary data
tempPartData.append(name)
country = input("Please enter your country of origin: ")
# Append the country to the temporary data
tempPartData.append(country)
# Ask for user input to add his age
age = int(input("Please enter your age: ")) # Convert the input to integer
# Append the age to the temporary data
tempPartData.append(age)
# Print the tempData
print (tempPartData)
# Save our temporary data to the ParticipantData
ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]]
print(ParticipantData)
# Increase the registeredParticipants number
registeredParticipants +=1 # = registeredParticipants + 1
# Write everything to a file
# Each participant is represented by a list
for participant in ParticipantData:
# loop over particpant data
for data in participant:
outputFile.write(str(data)) # Convert data to string and write it to the file
# We need to add extra formatting otherwise we will have it similar to MaxU.s.21
outputFile.write(" ") # MaxU.s.21
# Add each participant data in a new line
outputFile.write("\n")
# Always remember to close your file
outputFile.close()
# Reading all this data from the file
inputFile = open("PaticipantData.txt","r")
# Store all the file data into an inputList
inputList = []
# Read through the file line by line using a for loop
for line in inputFile:
# We need to read back from the file all participant data
tempParticipant = line.strip("\n").split()
# This is equivalent to the following
# "Max U.S. 21 \n".strip("\n") -> "Max U.S. 21 " // Takes out the \n
# "Max U.S. 21 ".split() -> ["Max","U.S.","21"] // Split the string and puts it's part into a list
print(tempParticipant)
# Let's append the data to the inputList
inputList.append(tempParticipant)
print(inputList)
# let's save the data into a dictionnary
Age = {}
# loop over the list to get each participant's age
for part in inputList:
# Use a temporary variable
tempAge = int(part[-1]) # ie: int('21') -> 21
# We can access the last element using this method
# Only add the Age to the dictionnary if it doesn't exist already
if tempAge in Age:
Age[tempAge] += 1 # means there is one more person with the same age
else:
Age[tempAge] = 1 # Otherwise, put it inside the dictionnary and give it value 1
print(Age) # ie: {25: 2, 22: 1, 21: 1, 26: 1}
# Always remember to close your file
outputFile.close()
================================================
FILE: input and output/Participant-Data-Part-C.py
================================================
##
# Participant Data, Part C Lecture
##
# _*_ coding: utf-8 _*_
# Create the number of participants that are allowed to register
ParticipantNumber = 5
ParticipantData = [] # For now an empty list to store Participant Data
# Create a counter for the registered participants
registeredParticipants = 0
# This is the file where we are going to write our data
outputFile = open("PaticipantData.txt","w")
# Loop over the participants
while(registeredParticipants < ParticipantNumber):
# Add a temporary data holder as a list
tempPartData = [] # name, country of origin, age
# Ask for user input to add his name
name = input("Please enter your name: ")
# Append the name to the temporary data
tempPartData.append(name)
country = input("Please enter your country of origin: ")
# Append the country to the temporary data
tempPartData.append(country)
# Ask for user input to add his age
age = int(input("Please enter your age: ")) # Convert the input to integer
# Append the age to the temporary data
tempPartData.append(age)
# Print the tempData
print (tempPartData)
# Save our temporary data to the ParticipantData
ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]]
print(ParticipantData)
# Increase the registeredParticipants number
registeredParticipants +=1 # = registeredParticipants + 1
# Write everything to a file
# Each participant is represented by a list
for participant in ParticipantData:
# loop over particpant data
for data in participant:
outputFile.write(str(data)) # Convert data to string and write it to the file
# We need to add extra formatting otherwise we will have it similar to MaxU.s.21
outputFile.write(" ") # MaxU.s.21
# Add each participant data in a new line
outputFile.write("\n")
# Always remember to close your file
outputFile.close()
# Reading all this data from the file
inputFile = open("PaticipantData.txt","r")
# Store all the file data into an inputList
inputList = []
# Read through the file line by line using a for loop
for line in inputFile:
# We need to read back from the file all participant data
tempParticipant = line.strip("\n").split()
# This is equivalent to the following
# "Max U.S. 21 \n".strip("\n") -> "Max U.S. 21 " // Takes out the \n
# "Max U.S. 21 ".split() -> ["Max","U.S.","21"] // Split the string and puts it's part into a list
print(tempParticipant)
# Let's append the data to the inputList
inputList.append(tempParticipant)
print(inputList)
# let's save the data into a dictionnary
Age = {}
# loop over the list to get each participant's age
for part in inputList:
# Use a temporary variable
tempAge = int(part[-1]) # ie: int('21') -> 21
# We can access the last element using this method
# Only add the Age to the dictionnary if it doesn't exist already
if tempAge in Age:
Age[tempAge] += 1 # means there is one more person with the same age
else:
Age[tempAge] = 1 # Otherwise, put it inside the dictionnary and give it value 1
print(Age) # ie: {25: 2, 22: 1, 21: 1, 26: 1}
# We can also get other participant's data like country int(part[1]) or name int(part[0])
Countries = {}
# loop over the list to get each participant's country
for part in inputList:
# Use a temporary variable
tempCountry = part[1] # No need to convert : it's already a string
# We can access the last element using this method
# Only add the Age to the dictionnary if it doesn't exist already
if tempCountry in Countries:
Countries[tempCountry] += 1 # means there is one more person with the same age
else:
Countries[tempCountry] = 1 # Otherwise, put it inside the dictionnary and give it value 1
print("Countries that attended:",Countries)
# Find the oldest age
Oldest = 0 # Let's assume this is the minimum value our age can have
Youngest = 100 # Let's assume this is the maximum value our age can have
mostOccuringAge = 0 # To save the most occurant age
counter = 0
# Loop over the Age dictionnary
for tempAge in Age:
# In the first time Oldest = first tempAge since the previous value was 0
# In each loop: if we have found a new bigger value, we will assign it to variable Oldest
if tempAge > Oldest:
Oldest = tempAge
# Otherwise, Oldest will not change and we'll assign it to the Youngest
if tempAge < Youngest:
Youngest = tempAge
# Access the value of each key in dictionary, counter will get the value for most occuring age
if Age[tempAge] >= counter:
counter = Age[tempAge]
# Get the dictionnary key equivalent to mostOccurongAge
mostOccuringAge = tempAge
# Print the Oldest Age
print(Oldest)
print(Youngest)
print("Most occuring age is:",mostOccuringAge,"with",counter,"participants")
# Always remember to close your file
inputFile.close()
================================================
FILE: input and output/Participant-Data-Part-D.py
================================================
##
# Participant Data, Part D Lecture
##
# _*_ coding: utf-8 _*_
# Create the number of participants that are allowed to register
ParticipantNumber = 5
ParticipantData = [] # For now an empty list to store Participant Data
# Create a counter for the registered participants
registeredParticipants = 0
"""
# This is the file where we are going to write our data
outputFile = open("PaticipantData.txt","w")
# Loop over the participants
while(registeredParticipants < ParticipantNumber):
# Add a temporary data holder as a list
tempPartData = [] # name, country of origin, age
# Ask for user input to add his name
name = input("Please enter your name: ")
# Append the name to the temporary data
tempPartData.append(name)
country = input("Please enter your country of origin: ")
# Append the country to the temporary data
tempPartData.append(country)
# Ask for user input to add his age
age = int(input("Please enter your age: ")) # Convert the input to integer
# Append the age to the temporary data
tempPartData.append(age)
# Print the tempData
print (tempPartData)
# Save our temporary data to the ParticipantData
ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]]
print(ParticipantData)
# Increase the registeredParticipants number
registeredParticipants +=1 # = registeredParticipants + 1
# Write everything to a file
# Each participant is represented by a list
for participant in ParticipantData:
# loop over particpant data
for data in participant:
outputFile.write(str(data)) # Convert data to string and write it to the file
# We need to add extra formatting otherwise we will have it similar to MaxU.s.21
outputFile.write(" ") # MaxU.s.21
# Add each participant data in a new line
outputFile.write("\n")
# Always remember to close your file
outputFile.close()
"""
# Reading all this data from the file
inputFile = open("PaticipantData.txt","r")
# Store all the file data into an inputList
inputList = []
# Read through the file line by line using a for loop
for line in inputFile:
# We need to read back from the file all participant data
tempParticipant = line.strip("\n").split()
# This is equivalent to the following
# "Max U.S. 21 \n".strip("\n") -> "Max U.S. 21 " // Takes out the \n
# "Max U.S. 21 ".split() -> ["Max","U.S.","21"] // Split the string and puts it's part into a list
print(tempParticipant)
# Let's append the data to the inputList
inputList.append(tempParticipant)
print(inputList)
# let's save the data into a dictionnary
Age = {}
# loop over the list to get each participant's age
for part in inputList:
# Use a temporary variable
tempAge = int(part[-1]) # ie: int('21') -> 21
# We can access the last element using this method
# Only add the Age to the dictionnary if it doesn't exist already
if tempAge in Age:
Age[tempAge] += 1 # means there is one more person with the same age
else:
Age[tempAge] = 1 # Otherwise, put it inside the dictionnary and give it value 1
print(Age) # ie: {25: 2, 22: 1, 21: 1, 26: 1}
# Find the oldest age
Oldest = 0 # Let's assume this is the minimum value our age can have
# Loop over the Age dictionnary
for tempAge in Age:
# In the first time Oldest = first tempAge since the previous value was 0
# In each loop: if we have found a new bigger value, we will assign it to variable Oldest
if tempAge > Oldest:
Oldest = tempAge
# Otherwise, Oldest will not change
# Print the Oldest Age
# Always remember to close your file
inputFile.close()
================================================
FILE: input and output/Tic-Tac-Toe-Part-A.py
================================================
##
# Tic Tac Toe, Part A Lecture
##
# _*_ coding: utf-8 _*_
"""
# The game should be similar to
# | | 0
#----- 1
# | | 2
#----- 3
# | | 4
"""
#!python3
# Define a function
def drawField():
for row in range(5): #0,1,2,3,4
# if row is even row write " | | "
if row%2 == 0:
# print writing lines
for column in range(5): # will take values 0,1,2,3,4
# if column is even, we will print a space
if column%2 == 0:
if column != 4:
print(" ",end="") # Continue in the same line
else:
print(" ") # Jump to the next line
else:
print("|",end="")
else:
print("-----")
"""
# We need to do the following
1. Apply and Save the move
2. Check which player turn is "X" or "O"
"""
# Create a variable for the Players
Player = 1
# Create a list with each element corresponds to a column
# currentField = [element1, element2, element3]
# Let's simulate our playing field
# In the first time, each list that correpond to a column will contains 3 empty spaces for the rows
currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # A list that contains 3 lists
# Create an infinite loop for the gamez
while(True): # True == True / is always true (We can also use while(1))
# Display the player's turn
print("Players turn: ",Player)
# Ask user for input: to specify the desired row and column
MoveRow = int(input("Please enter the row\n")) # Convert the row to integer
MoveColumn = int(input("Please enter the column\n")) # Convert the column to integer
if Player == 1:
# Make move for player 1
# Access our current field
currentField[MoveColumn][MoveRow] = "X"
# Once Player 1 make his move we change the Player to 2
Player = 2
else:
# Make move for player 2
currentField[MoveColumn][MoveRow] = "O"
Player = 1
# At the end, print the current field
print(currentField)
================================================
FILE: input and output/Tic-Tac-Toe-Part-B.py
================================================
##
# Tic Tac Toe, Part B Lecture
##
# _*_ coding: utf-8 _*_
"""
# The game should be similar to
# | | 0
#----- 1
# | | 2
#----- 3
# | | 4
"""
#!python3
# Define the function drawField that will print the game field
# We will try to put our current field into the draw field
def drawField(field):
for row in range(5): #0,1,2,3,4
#0,.,1,.,2
# if row is even row write " | | "
if row%2 == 0:
practicalRow = int(row/2)
# print writing lines
# In this case , we have to adapt our field (3*3) to the actual drawing (5*5)
# We can divde by 2 to get the correct maping
for column in range(5): # will take values 0 (in drawing) -> 0 (in actual field), 1->., 2->1, 3->., 4->2
# if column is even, we will print a space
# The even columns gives us the move of each player
if column%2 == 0: # Values 0,2,4
# The actual column that should be used in our field
# Make sure our values are integers
practicalColumn = int(column/2) # Values 0,1,2
if column != 4:
# Print the specific field
print(field[practicalColumn][practicalRow],end="") # Continue in the same line
else:
print(field[practicalColumn][practicalRow]) # Jump to the next line
else:
# The odd value just give us vertical lines
print("|",end="")
else:
print("-----")
"""
# We need to do the following
1. Apply and Save the move
2. Check which player turn is "X" or "O"
"""
# Create a variable for the Players
Player = 1
# Create a list with each element corresponds to a column
# currentField = [element1, element2, element3]
# Let's simulate our playing field
# In the first time, each list that correpond to a column will contains 3 empty spaces for the rows
currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # A list that contains 3 lists
# We will draw the current field
drawField(currentField)
# Create an infinite loop for the gamez
while(True): # True == True / is always true (We can also use while(1))
# Display the player's turn
print("Players turn: ",Player)
# Ask user for input: to specify the desired row and column
MoveRow = int(input("Please enter the row\n")) # Convert the row to integer
MoveColumn = int(input("Please enter the column\n")) # Convert the column to integer
if Player == 1:
# Make move for player 1
# Access our current field
# We only want to make one move when that specific field is empty
if currentField[MoveColumn][MoveRow] == " ":
currentField[MoveColumn][MoveRow] = "X"
# Once Player 1 make his move we change the Player to 2
Player = 2
else:
# Make move for player 2
if currentField[MoveColumn][MoveRow] == " ":
currentField[MoveColumn][MoveRow] = "O"
Player = 1
# At the end, draw the current field representation
drawField(currentField)
================================================
FILE: lists/main.py
================================================
##
# Lists Lecture
##
# -*- coding: utf-8 -*-
TestList = ["element1", "element2", "element3"] #TestList is a list with three elements
#Scores is a list with different data types
Scores = [70, 85, 67.5, 90, 80]
print(Scores) #print Scores list
'''
elements of a list can be accessed with a index inside a square bracket
Accessing list elements. The first element of a list starts from 0
'''
print(Scores[0]) #prints 1st element of a list
print(Scores[1]) #prints 2nd element of a list
print(Scores[2]) #prints 3rd element of a list
print(Scores[3]) #prints 4th element of a list
print(Scores[4]) #prints 5th element of a list
'''
Accessing list in a reverse order
'''
print(Scores[-1]) #prints last element of a list
print(Scores[-2]) #prints 2nd last element of a list
print(Scores[-3]) #prints 3rd last element of a list
print(Scores[-4]) #prints 4th last element of a list
print(Scores[-5]) #prints 5th last element of a list
'''
Accessing multiple elements from a list.
It can be done using List[first : last]
'''
print(Scores[0:2]) #access elements from index 0 to index 1
print(Scores[0:3]) #access elements from index 0 to index 2
print(Scores[1:3]) #access elements from index 1 to index 2
print(Scores[2:]) #access all elements from index 2 to end
print(Scores[1:]) #access all elements from index 1 to end
'''
Values of a list can be changed
'''
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print a list named Scores
Scores[0] = 75 #assign a value of 75 to the first element of a list Scores
print(Scores) #print the Scores
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
Scores[0] = 6.0 #assign a float value 6.0 to the first element of a list
print(Scores) #print Scores
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print Scores
Scores[0] = "Hello" #assign a string 'Hello' to the first element of a list
print(Scores) #print Scores
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print Scores
Scores[1:3] = [] #remove elements 2nd to 3rd from the list
print(Scores) #print Scores
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print Scores
Scores[2:3] = [] #remove 3rd element from the list.
print(Scores) #print Scores list
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print Scores list
Scores[2] = [] #assign an empty list to element 3rd (index 2nd)
print(Scores) #print Scores
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print Scores
Scores[2] = ["Hello", "World"] #assign a list to 3rd element (index 2nd)
print(Scores) #print Scores
print(Scores[2]) #accessing the 3rd element
'''
Accessing list within a list
'''
print(Scores[2][0]) #access the list within a list
print(Scores[2][1])
Scores = [70, 85, 67.5, 90, 80] #initialize list with values
print(Scores) #print Scores
Scores.append(82) #appending value at the end of list
print(Scores) #print Scores
================================================
FILE: loops/Breaking-and-Continuing-in-Loops.py
================================================
##
# Breaking and Continuing in Loops Lecture
##
# -*- coding: utf-8 -*-
Participants = ["Jen", "Alex", "Tina", "Joe", "Ben"] #create a list of 5 elements.
position = 0 #set position is equal to 0
for name in Participants: #loop over each element of list
if name == "Tina": #check if the element of list matches to "Tina"
break #come outside of loop if the condition is met
position = position + 1 #increment variable position by 1
print(position) #print the value of position
position = 0 #set position is equal to 0
for name in Participants: #loop over each element of list
if name == "Tina": #check if the element of list matches to "Tina"
print("About to break") #print message
break #come outside of loop if the condition is met
print("About to increment") #print message
position = position + 1 #increment variable position by 1
print(position) #print the value of position
'''
finds the index of matched string from the list
'''
Index = 0 #set Index to 0
for currentIndex in range(len(Participants)): #loop over all elements in list
print(currentIndex) #print value of currentIndex
if Participants[currentIndex] == "Joe": #check if list element is equal to Joe
print("Have Breaked") #print message
break #come out of the loop
print("Not Breaked") #print message
print(currentIndex+1) #print currentIndex of matched element
for number in range(10): #loop from range of 0 to 10
if number%3 == 0: #check remainder is 0 if divided by 3
print(number) #print value of a number
print("Divisible by 3") #print message
continue #continue
print(number) #print value of number
print("Not Divisible by 3") #print message
================================================
FILE: loops/Introduction-to-Loops.py
================================================
##
# Introduction to Loops Lecture
##
# -*- coding: utf-8 -*-
Word = "Hello" #initialize a variable Word with string "Hello"
Letters = [] #create an empty list
'''
loop through each character of a string, print each character. Check if the character
in a string matches e, print a string and then append it into List
'''
for w in Word: #loop over each character
print(w) #print a character
if w == "e": #check if a character matches 'e'
print("What a funny letter")
Letters.append(w) #Append each character into List.
print(Letters) #print the list
'''
Loop through each character stored in list Letters and then print each character
'''
for l in Letters: #Print each character in the list named Letters
print(l)
'''
Create a list of 5 elements. Loop through each element in the list and print it.
'''
Numbers = [1, 2, 3, 4, 5] #creating a list named Numbers with 5 integer elements
for l in Numbers: #loop over each element in list using for loop
print(l) #print each element
'''
print all the numbers which has a remainder of zero when divisible by 2.
'''
for l in Numbers: #loop over all elements in the list
if l%2 == 0: #check if remainder is 0 when divided by 2
print(l) #print the number
'''
print all the numbers which has a remainder of one when divisible by 2.
'''
for l in Numbers: #loop over all elements in the list
if l%2 == 1: #check if remainder is 1 when divided by 2
print(l) #print the number
Numbers = [] #create an empty list
for num in range(10): #loop over elements from 0 to 9
Numbers.append(num) #append each number to List
print(num) #print each number
print(Numbers) #print the list.
'''
Above process is repeated with value changed to 100. It prints all numbers from 0 to 99 and are appended
in list Numbers.
'''
Numbers = [] #create an empty list
for num in range(100): #loop over elements from 0 to 9
Numbers.append(num) #append each number to List
print(num) #print each number
print(Numbers) #print the list
'''
range is a function which takes an integer as an input.
range(1, 10, 2): 1 is the start, 10 is end and 2 is the step size
'''
Numbers = [] #create an empty list
for num in range(1, 10, 2): #loop over an elements from 1 to 10 with difference of 2
Numbers.append(num) #append each number to List
print(num) #print each number
print(Numbers) #print the list
Numbers = [] #create an empty list
for num in range(-1, -12, -2): #loop over an elements from -1 to -12 with difference of -2
Numbers.append(num) #append each number to List
print(num) #print each number
print(Numbers) #print list
'''
Above example is repeated with a range now changed from -1 to -13 at a difference of 3.
'''
Numbers = []
for num in range(-1, -13, 3):
Numbers.append(num)
print(num)
print(Numbers)
================================================
FILE: loops/Making-Shapes-With-Loops.py
================================================
##
# Making Shapes With Loops Lecture
##
# -*- coding: utf-8 -*-
Length = 10 #set a variable name Length = 10
'''
On each loop character c is printed n number of times which is defined by pos.
"c"*2 means character c is repeated twice
'''
for pos in range(1, 10): #loop from 1 to 9
print("c"*pos) #print character c
Length = 10 #set a variable name Length = 10
ToPrint = "a" #a variable name ToPrint is assigned a character "a"
for pos in range(1, Length + 1): #loop from 1 to value of Length + 1
print(ToPrint*pos) #print character n number of times
'''
Loop in a decreasing order from 10 to 0 and print a character n times on each decreasing loop
'''
for pos in range(Length, 0, -1):
print(ToPrint*pos)
'''
Loop in a increasing order from 1 to 12 and print a character n times on each increasing loop
'''
Length = 12
ToPrint = "1" #a variable name ToPrint is assigned a character "1"
for pos in range(1, Length + 1):
print(ToPrint*pos)
'''
Loop in a decreasing order from 12 to 0 and print a character "1" n times on each decreasing loop
'''
for pos in range(Length, 0, -1):
print(ToPrint*pos)
================================================
FILE: loops/Nested-Loops.py
================================================
##
# Nested Loops Lecture
##
# -*- coding: utf-8 -*-
# | |
#-----
# | |
#-----
# | |
'''
for loop
'''
for row in range(5): #loop 5 times
if row%2 == 0: #if remainder is equal to zero when divided by 2
print(" | | ") #print message
else: #if above condition is false
print("-----") #print message
'''
| |
-----
| |
-----
| |
printing the above shapes
'''
for row in range(5): #loop 5 times
if row%2 == 0: #if remainder is equal to zero when divided by 2
for column in range(1, 6): #created a nested loop of range from 1 to 6
if column%2 == 1: #check if remainder is 1 when divided by 2
if column != 5: #if variable column not equal to 5
print(" ", end = "") #print space and in the same line
else:
print(" ") #print in next line
else:
print("|", end = "") #print a pipe in same line
else:
print("-----") #print dash
================================================
FILE: loops/While-Loops.py
================================================
##
# While Loops Lecture
##
# -*- coding: utf-8 -*-
'''
While Loops
Syntax:
while condition:
Action1
Action2
ACtion3
'''
counter = 1 #set counter variable equal to 1
'''
The while loop runs until the condition is True, updates the counter, prints the counter.
It comes out of the loop if the condition fails.
'''
while (counter <= 10): #checks condition
print(counter) #print value of counter
counter = counter + 1 #increments counter by 1
counter = 1 #sets counter variable equal to 1
Sum = 0 #initialize sum to 0
while (counter <= 10): #checks condition
print(counter) #print value of counter
Sum = Sum + counter #add sum and counter value
counter = counter + 1 #increments counter by 1
print(Sum) #print the value of sum
'''
print the sum of values from 1 to 100
'''
counter = 1 #set counter equal to 1
Sum = 0 #intialize sum to 0
while (counter <= 100): #check the value of counter until it is less than or equal to 100
print(counter) #print the value of counter
Sum = Sum + counter #add the sum and counter
counter = counter + 1 #increment counter by 1
print(Sum) #print Sum
KeepTrack = 1
Sum = 0
while (KeepTrack <= 100):
print(KeepTrack)
Sum = Sum + KeepTrack
KeepTrack = KeepTrack + 1
print(Sum)
Letters = ["a", "b", "c", "d", "e"] #initialize a list with 5 character elements
Index = 0 #set index equal to 0
while (Index < len(Letters)): #Compare variable Index with length of list
print(Index) #print value of Index
print(Letters[Index]) #print each element in a List
Index = Index + 1 #Increment value of Index by 1.
'''
Starts from Index 4. Since the length of list is equal to 5. the loop runs only once
and prints the last element only.
'''
Index = 4 #set index equal to 4
while (Index < len(Letters)): #Compare variable Index with length of list
print(Index) #print value of Index
print(Letters[Index]) #print each element in a List
Index = Index + 1 #Increment value of Index by 1.
'''
The code below does not print anything since the loop starts from 5 and condition does not meet.
'''
Index = 5
while (Index < len(Letters)):
print(Index)
print(Letters[Index])
Index = Index + 1
height = 5000 #set variable height equal to 5000.
velocity = 50 #set variable velocity equal to 50
time = 0 #set variable time equal to 0
while (height > 0): #check if variable height > 0
height = height - velocity #decrement height with velocity and assign the value to height.
time = time + 1 #increment time by value 1
print(height) #print value of height
print(time) #print value of time
================================================
FILE: variables/main.py
================================================
##
# Variables Lecture
##
# -*- coding: utf-8 -*-
# 'one' is the name of the variable
# '=' is called the assignment operator we use to store values in a variable
# '1' is the actual value stored inside the variable 'one'
one = 1
# 'two' is the name of the variable
# '=' is called the assignment operator we use to store values in a variable
# '2' is the actual value stored inside the variable 'two'
two = 2
# 'three' is the name of the variable
# '=' is called the assignment operator we use to store values in a variable
# '3' is the actual value stored inside the variable 'three'
three = 3
# 'print()' is a function we use in python to print some value or content on the screen
# name of the variable can be passed inside the print function to display its value on screen
print(one)
print(two)
print(three)
print(two)
print(one)
# The above code will print the following
# Notice how the same variable is being used again for printing
"""
1
2
3
2
1
"""
print(one)
print(two)
print(three)
# the value of a variable can be overwritten again by using the assignment operator '=' to store a new unique value
two = 4
print(two)
print(one)
# The above code will print the following
# Notice the value of variable 'two' is reassigned to '4' in the output
"""
1
2
3
4
1
"""
# apart from storing integer values , decimal values can also be stored inside a variable
# notice how the decimal value '1.1' is stored inside a variable called 'decimal'
decimal = 1.1
# The above code will print the following
"""
1.1
"""
# text values also called strings can be stored inside a variable
# notice how the value 'Hello' is stored inside a variable 'StringVar'
StringVar = "Hello"
# The above code will print the following
"""
Hello
"""
# will produce and error with the following message
"""
StringVar = "Hello" + 1
TypeError: must be str, not int
"""
# uncomment this code execute the script to see error
#StringVar = "Hello" + 1
# this happens because variables cant be of two types of 'int' denotes to integer and 'str' denotes to string
StringVar = "Hello" + "1"
# The above code will print the following
# The above code works beause now both 1 and hello are strings
"""
Hello1
"""
# The def keyword is used to begin fuction declaration and then the name of function is wriiten
def FunctionName():
# Declaring local variable
newVar="World"
# Printing local variable
print(newVar)
# Used to indicate global variable is used
global one
# Printing global one variable
print(one)
# Returing a value , also used for ending a function
return
# The function being called by using its name along with ()
FunctionName()
# Printing a local variable
print(newVar)
# The following error is produced with due to the fact that 'newVar is a local variable'
"""
NameError: name 'newVar' is not defined
"""
# Shorthand way of declaration variables
one , two , three = 1,2,3
print(one)
print(two)
print(three)
# The above code will print the following
"""
1
2
3
"""
# Declaraing a variable and storing the value 5 into it
Five = 3+2
print(Five)
# The above code will print the following
"""
5
"""
# Will produce error because we cant add two variables with one value on the right of assignment operator
Five + Six = 3+2
# This will produce an error as well
# left = what you're giving the value to
# right = what the value is
5 = Five
# Trying to print the value of variable 'Five'
print(Five)
# Declared a variable 'count' and stored the value 0 to it
count = 0
# Printing count value
print(count)
# Output
"""
0
"""
# Reassign the value of count to 1
count = 1
# Printing count value
print(count)
# Output
"""
1
"""
# This will also increase the count value by adding 1 to the previous value of count
count = count + 1
# Printing count value
print(count)
# Output
"""
2
"""
# This will also increase the count value by adding 1 to the previous value of count
count = count + 1
# Printing count value
print(count)
# Output
"""
3
"""
# This will also increase the count value by adding 1 to the previous value of count
# Short hand notation of the same line as 'count=count+1'
count+=1
# Printing count value
print(count)
# Output
"""
4
"""
# Assign 0 value to variable count
count = 0
# Print the value
print(count)
# Incrementing count value
count = count + 1
# Print the value
print(count)
# Multiply the value of count by 3
count*=3
# Print the value
print(count)
# Output
"""
0
1
3
"""
# Assign 0 value to variable count
count = 0
# Print the value
print(count)
# Incrementing count value
count = count + 1
# Print the value
print(count)
# Multiply the value of count by 3
count/=3
# Print the value
print(count)
# Output
"""
0
1
0.333333333333
"""
gitextract_ej8bju1m/
├── "if" statements/
│ └── main.py
├── .gitignore
├── README.md
├── classes/
│ ├── Class-Inheritance.py
│ ├── Introduction-to-Classes.py
│ ├── Pets-Part-A.py
│ ├── Pets-Part-B.py
│ ├── Pets-Part-C.py
│ └── Pets-Part-D.py
├── dictionaries and sets/
│ ├── Dictionaries-and-Sets.py
│ └── Examples-of-Dictionaries-and-Sets.py
├── error handling/
│ └── main.py
├── final project/
│ ├── Blackjack-Part-A.py
│ ├── Blackjack-Part-B.py
│ ├── Blackjack-Part-C.py
│ ├── Blackjack-Part-D.py
│ ├── Blackjack-Part-E.py
│ └── Blackjack-Part-F.py
├── functions/
│ └── main.py
├── importing/
│ ├── Alternative-Import-Methods.py
│ ├── Guessing-Game-Part-A.py
│ ├── Guessing-Game-Part-B.py
│ ├── Introduction-to-Importing.py
│ ├── Math-Library.py
│ └── Time-Library.py
├── input and output/
│ ├── File-IO.py
│ ├── Introduction-to-IO.py
│ ├── Participant-Data-Part-A.py
│ ├── Participant-Data-Part-B.py
│ ├── Participant-Data-Part-C.py
│ ├── Participant-Data-Part-D.py
│ ├── Tic-Tac-Toe-Part-A.py
│ └── Tic-Tac-Toe-Part-B.py
├── lists/
│ └── main.py
├── loops/
│ ├── Breaking-and-Continuing-in-Loops.py
│ ├── Introduction-to-Loops.py
│ ├── Making-Shapes-With-Loops.py
│ ├── Nested-Loops.py
│ └── While-Loops.py
└── variables/
└── main.py
SYMBOL INDEX (144 symbols across 16 files)
FILE: classes/Class-Inheritance.py
class Team (line 7) | class Team:
method __init__ (line 11) | def __init__(self, Name = "Name", Origin = "Origin"): #con...
method DefineTeamName (line 15) | def DefineTeamName(self, Name): #clas...
method DefineTeamOrigin (line 18) | def DefineTeamOrigin(self, Origin): #clas...
class Player (line 34) | class Player(Team):
method __init__ (line 35) | def __init__(self): #constructor
method ScoredPoint (line 48) | def ScoredPoint(self):
method setName (line 51) | def setName(self, name):
method __init__ (line 67) | def __init__(self, PlayerName, PPoints, TeamName, TeamOrigin):
method ScoredPoint (line 77) | def ScoredPoint(self):
method setName (line 80) | def setName(self, name):
method __str__ (line 86) | def __str__(self):
class Player (line 63) | class Player(Team):
method __init__ (line 35) | def __init__(self): #constructor
method ScoredPoint (line 48) | def ScoredPoint(self):
method setName (line 51) | def setName(self, name):
method __init__ (line 67) | def __init__(self, PlayerName, PPoints, TeamName, TeamOrigin):
method ScoredPoint (line 77) | def ScoredPoint(self):
method setName (line 80) | def setName(self, name):
method __str__ (line 86) | def __str__(self):
FILE: classes/Introduction-to-Classes.py
class Team (line 14) | class Team:
method __init__ (line 15) | def __init__(self): #constructor with no argu...
method DefineTeamName (line 23) | def DefineTeamName(self, Name):
method DefineTeamOrigin (line 26) | def DefineTeamOrigin(self, Origin):
method __init__ (line 48) | def __init__(self, Name = "Name", Origin = "Origin"): #con...
method DefineTeamName (line 52) | def DefineTeamName(self, Name): #clas...
method DefineTeamOrigin (line 55) | def DefineTeamOrigin(self, Origin): #clas...
class Team (line 44) | class Team:
method __init__ (line 15) | def __init__(self): #constructor with no argu...
method DefineTeamName (line 23) | def DefineTeamName(self, Name):
method DefineTeamOrigin (line 26) | def DefineTeamOrigin(self, Origin):
method __init__ (line 48) | def __init__(self, Name = "Name", Origin = "Origin"): #con...
method DefineTeamName (line 52) | def DefineTeamName(self, Name): #clas...
method DefineTeamOrigin (line 55) | def DefineTeamOrigin(self, Origin): #clas...
FILE: classes/Pets-Part-A.py
class Pet (line 8) | class Pet:
method __init__ (line 11) | def __init__(self,n,a,h,p):
method __init__ (line 25) | def __init__(self,name,a,h,p):
method getName (line 37) | def getName(self):
method setName (line 43) | def setName(self,name):
method __init__ (line 50) | def __init__(self,name,a,h,p):
method getName (line 62) | def getName(self):
method setName (line 68) | def setName(self,x):
method __init__ (line 76) | def __init__(self,name,a,h,p):
method getName (line 88) | def getName(self):
method getAge (line 93) | def getAge(self):
method getHunger (line 98) | def getHunger(self):
method getPlayful (line 103) | def getPlayful(self):
method setName (line 109) | def setName(self,xname):
method setAge (line 113) | def setAge(self,Age):
method setHunger (line 117) | def setHunger(self,hunger):
method setPlayful (line 121) | def setPlayful(self,play):
class Pet (line 22) | class Pet:
method __init__ (line 11) | def __init__(self,n,a,h,p):
method __init__ (line 25) | def __init__(self,name,a,h,p):
method getName (line 37) | def getName(self):
method setName (line 43) | def setName(self,name):
method __init__ (line 50) | def __init__(self,name,a,h,p):
method getName (line 62) | def getName(self):
method setName (line 68) | def setName(self,x):
method __init__ (line 76) | def __init__(self,name,a,h,p):
method getName (line 88) | def getName(self):
method getAge (line 93) | def getAge(self):
method getHunger (line 98) | def getHunger(self):
method getPlayful (line 103) | def getPlayful(self):
method setName (line 109) | def setName(self,xname):
method setAge (line 113) | def setAge(self,Age):
method setHunger (line 117) | def setHunger(self,hunger):
method setPlayful (line 121) | def setPlayful(self,play):
class Pet (line 47) | class Pet:
method __init__ (line 11) | def __init__(self,n,a,h,p):
method __init__ (line 25) | def __init__(self,name,a,h,p):
method getName (line 37) | def getName(self):
method setName (line 43) | def setName(self,name):
method __init__ (line 50) | def __init__(self,name,a,h,p):
method getName (line 62) | def getName(self):
method setName (line 68) | def setName(self,x):
method __init__ (line 76) | def __init__(self,name,a,h,p):
method getName (line 88) | def getName(self):
method getAge (line 93) | def getAge(self):
method getHunger (line 98) | def getHunger(self):
method getPlayful (line 103) | def getPlayful(self):
method setName (line 109) | def setName(self,xname):
method setAge (line 113) | def setAge(self,Age):
method setHunger (line 117) | def setHunger(self,hunger):
method setPlayful (line 121) | def setPlayful(self,play):
class Pet (line 73) | class Pet:
method __init__ (line 11) | def __init__(self,n,a,h,p):
method __init__ (line 25) | def __init__(self,name,a,h,p):
method getName (line 37) | def getName(self):
method setName (line 43) | def setName(self,name):
method __init__ (line 50) | def __init__(self,name,a,h,p):
method getName (line 62) | def getName(self):
method setName (line 68) | def setName(self,x):
method __init__ (line 76) | def __init__(self,name,a,h,p):
method getName (line 88) | def getName(self):
method getAge (line 93) | def getAge(self):
method getHunger (line 98) | def getHunger(self):
method getPlayful (line 103) | def getPlayful(self):
method setName (line 109) | def setName(self,xname):
method setAge (line 113) | def setAge(self,Age):
method setHunger (line 117) | def setHunger(self,hunger):
method setPlayful (line 121) | def setPlayful(self,play):
FILE: classes/Pets-Part-B.py
class Pet (line 9) | class Pet:
method __init__ (line 12) | def __init__(self,name,a,h,p):
method getName (line 24) | def getName(self):
method getAge (line 29) | def getAge(self):
method getHunger (line 34) | def getHunger(self):
method getPlayful (line 39) | def getPlayful(self):
method setName (line 45) | def setName(self,xname):
method setAge (line 49) | def setAge(self,Age):
method setHunger (line 53) | def setHunger(self,hunger):
method setPlayful (line 57) | def setPlayful(self,play):
class Dog (line 106) | class Dog(Pet):
method __init__ (line 109) | def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
method wantsToPlay (line 121) | def wantsToPlay(self):
FILE: classes/Pets-Part-C.py
class Pet (line 9) | class Pet:
method __init__ (line 12) | def __init__(self,name,a,h,p):
method getName (line 24) | def getName(self):
method getAge (line 29) | def getAge(self):
method getHunger (line 34) | def getHunger(self):
method getPlayful (line 39) | def getPlayful(self):
method setName (line 45) | def setName(self,xname):
method setAge (line 49) | def setAge(self,Age):
method setHunger (line 53) | def setHunger(self,hunger):
method setPlayful (line 57) | def setPlayful(self,play):
method __str__ (line 61) | def __str__(self):
class Dog (line 111) | class Dog(Pet):
method __init__ (line 114) | def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
method wantsToPlay (line 127) | def wantsToPlay(self):
class Cat (line 139) | class Cat(Pet):
method __init__ (line 142) | def __init__(self,name,age,hunger,playful,place):
method wantsToSit (line 151) | def wantsToSit(self):
method __str__ (line 164) | def __str__(self):
FILE: classes/Pets-Part-D.py
class Pet (line 9) | class Pet:
method __init__ (line 12) | def __init__(self,name,a,h,p):
method getName (line 24) | def getName(self):
method getAge (line 29) | def getAge(self):
method getHunger (line 34) | def getHunger(self):
method getPlayful (line 39) | def getPlayful(self):
method setName (line 45) | def setName(self,xname):
method setAge (line 49) | def setAge(self,Age):
method setHunger (line 53) | def setHunger(self,hunger):
method setPlayful (line 57) | def setPlayful(self,play):
method __str__ (line 61) | def __str__(self):
class Dog (line 111) | class Dog(Pet):
method __init__ (line 114) | def __init__(self,name,age,hunger,playful,breed,FavoriteToy):
method wantsToPlay (line 127) | def wantsToPlay(self):
class Cat (line 139) | class Cat(Pet):
method __init__ (line 142) | def __init__(self,name,age,hunger,playful,place):
method wantsToSit (line 151) | def wantsToSit(self):
method __str__ (line 164) | def __str__(self):
class Human (line 169) | class Human:
method __init__ (line 171) | def __init__(self,name,Pets):
method hasPets (line 177) | def hasPets(self):
FILE: final project/Blackjack-Part-A.py
function createDeck (line 11) | def createDeck():
FILE: final project/Blackjack-Part-B.py
function createDeck (line 11) | def createDeck():
class Player (line 29) | class Player:
method __init__ (line 30) | def __init__(self,hand = [],money = 100): #__init__ is the constructor...
method __str__ (line 36) | def __str__(self): #__str__ will return a human readable string
method setScore (line 46) | def setScore(self) :
FILE: final project/Blackjack-Part-C.py
function createDeck (line 12) | def createDeck():
class Player (line 30) | class Player:
method __init__ (line 31) | def __init__(self,hand = [],money = 100): #__init__ is the constructor...
method __str__ (line 36) | def __str__(self): #__str__ will return a human readable string
method setScore (line 47) | def setScore(self) :
method hit (line 67) | def hit(self,card):
method play (line 72) | def play(self,newHnad):
method pay (line 77) | def pay(self,amount):
method win (line 81) | def win(self,amount):
FILE: final project/Blackjack-Part-D.py
function createDeck (line 12) | def createDeck():
class Player (line 30) | class Player:
method __init__ (line 31) | def __init__(self,hand = [],money = 100): #__init__ is the constructor...
method __str__ (line 37) | def __str__(self): #__str__ will return a human readable string
method setScore (line 48) | def setScore(self) :
method hit (line 68) | def hit(self,card):
method play (line 73) | def play(self,newHnad):
method betMoney (line 78) | def betMoney(self,amount):
method win (line 83) | def win(self,result):
FILE: final project/Blackjack-Part-E.py
function createDeck (line 12) | def createDeck(): #define a function to Create the...
class Player (line 26) | class Player: #here we will be creating Pla...
method __init__ (line 27) | def __init__(self,hand = [],money = 100): #__init__ function us...
method __str__ (line 33) | def __str__(self): #overriding the __str__ function. i...
method setScore (line 41) | def setScore(self): #define setScore method for player...
method hit (line 57) | def hit(self, card): #hit function is used to a...
method play (line 61) | def play(self, newHand): #play function will be use...
method betMoney (line 65) | def betMoney(self,amount): #change pay function to be...
method win (line 69) | def win(self, result): #change win function. now ...
function printHouse (line 79) | def printHouse(House): #this method will print ...
FILE: final project/Blackjack-Part-F.py
function createDeck (line 13) | def createDeck():
class Player (line 29) | class Player:
method __init__ (line 30) | def __init__(self,hand = [],money = 100): #__init__ is the constru...
method __str__ (line 36) | def __str__(self): #__str__ will return a human readable string
method setScore (line 47) | def setScore(self) :
method hit (line 67) | def hit(self,card):
method play (line 72) | def play(self,newHand):
method betMoney (line 77) | def betMoney(self,amount):
method win (line 82) | def win(self,result):
method draw (line 94) | def draw(self):
method hasBlackjack (line 99) | def hasBlackjack(self):
function printHouse (line 107) | def printHouse(House):
FILE: functions/main.py
function addOne (line 22) | def addOne(Number):
function addOneAddTwo (line 48) | def addOneAddTwo(NumberOne, NumberTwo):
FILE: input and output/Tic-Tac-Toe-Part-A.py
function drawField (line 19) | def drawField():
FILE: input and output/Tic-Tac-Toe-Part-B.py
function drawField (line 22) | def drawField(field):
FILE: variables/main.py
function FunctionName (line 94) | def FunctionName():
Condensed preview — 40 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (148K chars).
[
{
"path": "\"if\" statements/main.py",
"chars": 4416,
"preview": "##\r\n# \"If\" Statements Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\nSyntax:\r\nif condition:\r\n Action\r\n'''\r\nclick = Fa"
},
{
"path": ".gitignore",
"chars": 99,
"preview": "# OS generated files\n.DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nIcon?\nehthumbs.db\nThumbs.db\n"
},
{
"path": "README.md",
"chars": 781,
"preview": "# Python is Easy\n\n> Code snippets for the \"Python is Easy\" course, available at Pirple.com/python\n\n\n## About this Reposi"
},
{
"path": "classes/Class-Inheritance.py",
"chars": 4055,
"preview": "##\r\n# Class Inheritance Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\nclass Team: \r\n #constructor passes two varia"
},
{
"path": "classes/Introduction-to-Classes.py",
"chars": 3834,
"preview": "##\r\n# Introduction to Classes Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n\"\"\"\r\nclass is defined by a keyword class\r\n\r\nCl"
},
{
"path": "classes/Pets-Part-A.py",
"chars": 4709,
"preview": "##\n# Pets, Part A Lecture\n##\n\n# -*- coding: utf-8 -*-\n\n# Define a class\nclass Pet:\n\n # Define a function which refers t"
},
{
"path": "classes/Pets-Part-B.py",
"chars": 4907,
"preview": "##\n# Pets, Part B Lecture\n##\n\n# -*- coding: utf-8 -*-\n\n\n# Define a class\nclass Pet:\n\n # Define a function which refers "
},
{
"path": "classes/Pets-Part-C.py",
"chars": 6975,
"preview": "##\n# Pets, Part C Lecture\n##\n\n# -*- coding: utf-8 -*-\n\n\n# Define a class\nclass Pet:\n\n # Define a function which refers "
},
{
"path": "classes/Pets-Part-D.py",
"chars": 9461,
"preview": "##\n# Pets, Part D Lecture\n##\n\n# -*- coding: utf-8 -*-\n\n\n# Define a class\nclass Pet:\n\n # Define a function which refers "
},
{
"path": "dictionaries and sets/Dictionaries-and-Sets.py",
"chars": 5161,
"preview": "##\r\n# Dictionaries and Sets Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n\"\"\"\r\nA set is a data structure in python like a "
},
{
"path": "dictionaries and sets/Examples-of-Dictionaries-and-Sets.py",
"chars": 4864,
"preview": "##\r\n# Examples of Dictionaries and Sets - Lecture\r\n##\r\n\r\n\r\n# Declaring a dictonary variable named 'BlackShoes' and assig"
},
{
"path": "error handling/main.py",
"chars": 11281,
"preview": "##\r\n# Error Handling Lecture\r\n##\r\n\r\n\r\n# float(\"123.4\") - > 123.4\r\n# float(\"N/A\") - > error\r\n\r\n\"\"\"\r\n'try' 'except' is a w"
},
{
"path": "final project/Blackjack-Part-A.py",
"chars": 673,
"preview": "##\r\n# Blackjack, Part A Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n#Import shuffle function from random library\r\nfrom ran"
},
{
"path": "final project/Blackjack-Part-B.py",
"chars": 2065,
"preview": "##\r\n# Blackjack, Part B Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n#Import shuffle function from random library\r\nfrom ran"
},
{
"path": "final project/Blackjack-Part-C.py",
"chars": 2900,
"preview": "##\r\n# Blackjack, Part C Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n#Import shuffle function from random library\r\nfrom r"
},
{
"path": "final project/Blackjack-Part-D.py",
"chars": 3440,
"preview": "##\r\n# Blackjack, Part D Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n#Import shuffle function from random library\r\nfrom r"
},
{
"path": "final project/Blackjack-Part-E.py",
"chars": 7444,
"preview": "##\r\n# Blackjack, Part E Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n#! /usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfr"
},
{
"path": "final project/Blackjack-Part-F.py",
"chars": 5718,
"preview": "##\r\n# Blackjack, Part F Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\nfrom __future__ import print_function\r\n#Import shuff"
},
{
"path": "functions/main.py",
"chars": 2102,
"preview": "##\n# Functions Lecture\n##\n\n# -*- coding: utf-8 -*-\n\n# Assignment on Functions\n'''\nSyntax for a function:\n\ndef FunctionNa"
},
{
"path": "importing/Alternative-Import-Methods.py",
"chars": 941,
"preview": "##\n# Alternative Import Methods Lecture\n##\n\n# _*_ coding: utf-8 _*_\n\n# Importing the library 'random' as 'r' where 'r' i"
},
{
"path": "importing/Guessing-Game-Part-A.py",
"chars": 727,
"preview": "##\n# Guessing Game, Part A Lecture\n##\n\n# _*_ coding: utf-8 _*_\n\n# import the fuction 'randint' from library random\nfrom "
},
{
"path": "importing/Guessing-Game-Part-B.py",
"chars": 1261,
"preview": "##\n# Guessing Game, Part B Lecture\n##\n\n# _*_ coding: utf-8 _*_\n\n# import 'random' fuction of 'random' library\nfrom rando"
},
{
"path": "importing/Introduction-to-Importing.py",
"chars": 568,
"preview": "##\n# Introduction to Importing Lecture\n##\n\n# _*_ coding: utf-8 _*_\n\n# Importing the library 'random' as 'r' where 'r' is"
},
{
"path": "importing/Math-Library.py",
"chars": 835,
"preview": "##\n# Math Library Lecture\n##\n\n# _*_ coding: utf-8 _*_\n\n# import the library 'math'\nimport math\n\n# square root of the var"
},
{
"path": "importing/Time-Library.py",
"chars": 492,
"preview": "##\n# The Time Library Lecture\n##\n\n# _*_ coding: utf-8 _*_\n\n# import the 'time' library and print the time, processor tak"
},
{
"path": "input and output/File-IO.py",
"chars": 3833,
"preview": "##\r\n# File Input and Output Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n# Genral form to open a file with an option (\"r\""
},
{
"path": "input and output/Introduction-to-IO.py",
"chars": 3165,
"preview": "##\r\n# Introduction to Input and Output Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n# Display a message to the user to wr"
},
{
"path": "input and output/Participant-Data-Part-A.py",
"chars": 1938,
"preview": "##\r\n# Participant Data, Part A Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n# Create the number of participants that are "
},
{
"path": "input and output/Participant-Data-Part-B.py",
"chars": 3321,
"preview": "##\r\n# Participant Data, Part B Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n# Create the number of participants that are "
},
{
"path": "input and output/Participant-Data-Part-C.py",
"chars": 5095,
"preview": "##\r\n# Participant Data, Part C Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n# Create the number of participants that are "
},
{
"path": "input and output/Participant-Data-Part-D.py",
"chars": 3773,
"preview": "##\r\n# Participant Data, Part D Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n# Create the number of participants that are "
},
{
"path": "input and output/Tic-Tac-Toe-Part-A.py",
"chars": 2163,
"preview": "##\r\n# Tic Tac Toe, Part A Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\"\"\"\r\n# The game should be similar to\r\n# | | 0\r\n#---"
},
{
"path": "input and output/Tic-Tac-Toe-Part-B.py",
"chars": 3303,
"preview": "##\r\n# Tic Tac Toe, Part B Lecture\r\n##\r\n\r\n# _*_ coding: utf-8 _*_\r\n\r\n\r\n\"\"\"\r\n# The game should be similar to\r\n# | | 0\r\n#-"
},
{
"path": "lists/main.py",
"chars": 4343,
"preview": "##\n# Lists Lecture\n##\n\n# -*- coding: utf-8 -*-\n\n\nTestList = [\"element1\", \"element2\", \"element3\"] #TestList i"
},
{
"path": "loops/Breaking-and-Continuing-in-Loops.py",
"chars": 2775,
"preview": "##\r\n# Breaking and Continuing in Loops Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\nParticipants = [\"Jen\", \"Alex\", \"Tina\""
},
{
"path": "loops/Introduction-to-Loops.py",
"chars": 3550,
"preview": "##\r\n# Introduction to Loops Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n\r\nWord = \"Hello\" #initiali"
},
{
"path": "loops/Making-Shapes-With-Loops.py",
"chars": 1246,
"preview": "##\r\n# Making Shapes With Loops Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\nLength = 10 #set a variable na"
},
{
"path": "loops/Nested-Loops.py",
"chars": 1161,
"preview": "##\r\n# Nested Loops Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n# | |\r\n#-----\r\n# | |\r\n#-----\r\n# | |\r\n'''\r\nfor loop\r\n'''\r\n"
},
{
"path": "loops/While-Loops.py",
"chars": 3291,
"preview": "##\r\n# While Loops Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\nWhile Loops\r\nSyntax:\r\n while condition:\r\n Act"
},
{
"path": "variables/main.py",
"chars": 4925,
"preview": "##\r\n# Variables Lecture\r\n##\r\n\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n# 'one' is the name of the variable\r\n# '=' is called the ass"
}
]
About this extraction
This page contains the full source code of the pirple/Python-Is-Easy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 40 files (134.4 KB), approximately 34.6k tokens, and a symbol index with 144 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.