├── "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 /"if" statements/main.py: -------------------------------------------------------------------------------- 1 | ## 2 | # "If" Statements Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | ''' 8 | Syntax: 9 | if condition: 10 | Action 11 | ''' 12 | click = False #set variable click to False 13 | Like = 0 #initialize Like equal to 0 14 | 15 | if click == True: #Check if click is True 16 | Like = Like + 1 #Increment Like by 1 17 | click = False #set click to False 18 | 19 | print(Like) #print the value 20 | Temperature = 20 #set a variable Temperature to 20 21 | Thermo = 15 #set a variable Thermo to 15 22 | if Temperature < 15: #Check if Temperature is less than 15 23 | Thermo = Thermo + 5 #if yes increment variable Thermo by 5 24 | 25 | print(Thermo) #print the value Thermo 26 | 27 | Temperature = 14 #set variable Temperature to 14 28 | Thermo = 15 #set variable Thermo to 15 29 | if Temperature < 15: #Check if Temperature is less than 15 30 | Thermo = Thermo + 5 #if True increment Thermo by 5 31 | 32 | print(Thermo) #print the value of Thermo 33 | 34 | Temperature = 15 #set variable Temperature to 15 35 | Thermo = 15 #set variable Thermo to 15 36 | if Temperature <= 15: #Check if Temperature is less than or equal to 15 37 | Thermo = Thermo + 5 #if True increment Thermo by 5 38 | 39 | print(Thermo) #print the value of Thermo 40 | 41 | if Temperature > 20: #Check if Temperature is greater than 20 42 | Thermo = Thermo - 3 #if True decrement Thermo by 3 43 | 44 | print(Thermo) #print the value of Thermo 45 | Temperature = 20 #set the value of Temperature to 20 46 | Thermo = 15 #set Thermo equals to 15 47 | if Temperature <= 15: #Check if Temperature is less than or equal to 15 48 | Thermo = Thermo + 5 #if True increment Thermo by 5 49 | 50 | print(Thermo) #print value of Thermo 51 | 52 | if Temperature >= 20: #Check if Temperature is greater than or equal to 20 53 | Thermo = Thermo - 3 #if True decrement Thermo by 3 54 | 55 | print(Thermo) #print value of Thermo 56 | 57 | 58 | Time = "Day" #set variable Time to Day 59 | Sleepy = False #set Sleepy equals to False 60 | Pajamas = "Off" #initialize Pajamas equal to Off 61 | ''' 62 | If Time equals to Night and Sleep is True then set Pajamas equal to On 63 | ''' 64 | if Time == "Night" and Sleepy == True: #Check two condition and are ANDed 65 | Pajamas = "On" #if both condition are True then set Pajamas = On 66 | print(Pajamas) #print the value of Pajamas 67 | 68 | Pajamas = "Off" #initialize Pajamas equal to Off 69 | if Time == "Night" or Sleepy == True: #Check two condition and are ORed 70 | Pajamas = "On" #if anyone of the condition is True set Pajamas equal to On 71 | print(Pajamas) #print the value of Pajamas 72 | 73 | Time = 'Night' #set variable Time to Night 74 | Sleepy = 'True' #set variable Sleep equals to True 75 | Pajamas = "Off" #initialize Pajamas equal to Off 76 | if Time == "Night" or Sleepy == False: #Check two condition and are ORed 77 | Pajamas = "On" #if anyone of the condition is True set Pajamas equal to On 78 | print(Pajamas) #print the value of Pajamas 79 | 80 | ''' 81 | intialize Time equals to Day, Sleepy equals to False, Pajamas to off and InBed equals to True 82 | Check if Time equals to Night, set Pajamas equals to On, else if Time equals to Morning is True 83 | set Pajamas equals to On and then print its value 84 | ''' 85 | Time = 'Day' 86 | Sleepy = 'False' 87 | Pajamas = "off" 88 | InBed = True 89 | if Time == "Night": 90 | Pajamas = "On" 91 | elif Time == "Morning": 92 | Pajamas = "On" 93 | print(Pajamas) 94 | 95 | Time = 'Morning' #set Time equals to Morning 96 | Sleepy = 'False' #Set Sleepy to False 97 | Pajamas = "Unknown" #set Pajamas to Unknown 98 | InBed = True #set InBed variable to True 99 | print(Pajamas) #print value of Pajamas 100 | if Time == "Night": #if Time is equal to Night 101 | Pajamas = "On" #set pajamas to On 102 | elif Time == "Morning": #else if Time equal to Morning 103 | Pajamas = "On" #set pajamas to On 104 | else: #otherwise if any of the above two statement are not true 105 | Pajamas = "Off" #set Pajamas Off 106 | print(Pajamas) #print the value of Pajamas 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OS generated files 2 | .DS_Store 3 | .DS_Store? 4 | ._* 5 | .Spotlight-V100 6 | .Trashes 7 | Icon? 8 | ehthumbs.db 9 | Thumbs.db 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python is Easy 2 | 3 | > Code snippets for the "Python is Easy" course, available at Pirple.com/python 4 | 5 | 6 | ## About this Repository 7 | 8 | These code snippets are for following along with the lectures, and running the code yourself. 9 | 10 | Everything is organized by section. Click on a section to find the lecture code you're looking for. 11 | 12 | 13 | ## Never used Git or Github before? 14 | 15 | No worries. You can learn how to use it in just a few minutes. Start by watching these videos: 16 | 17 | 18 | #### Git 19 | [https://git-scm.com/videos](https://git-scm.com/videos) 20 | 21 | #### Github 22 | [https://www.youtube.com/playlist?list=PLg7s6cbtAD15G8lNyoaYDuKZSKyJrgwB-](https://www.youtube.com/playlist?list=PLg7s6cbtAD15G8lNyoaYDuKZSKyJrgwB-) 23 | 24 | After that, you'll know enough to grab this code yourself and "clone" it down to your machine. 25 | -------------------------------------------------------------------------------- /classes/Class-Inheritance.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Class Inheritance Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | class Team: 8 | #constructor passes two variables Name and Origin. The 9 | #default value of variable Name is "Name" and that of variable Origin is "Origin". 10 | #If no values are passed through a constructor its default values are Name and Origin. 11 | def __init__(self, Name = "Name", Origin = "Origin"): #constructor 12 | self.TeamName = Name #member assignment 13 | self.TeamOrigin = Origin #member assignment 14 | 15 | def DefineTeamName(self, Name): #class method 16 | self.TeamName = Name 17 | 18 | def DefineTeamOrigin(self, Origin): #class method 19 | self.TeamOrigin = Origin 20 | 21 | #class InheritanceClassName(ParentClass): 22 | # def __init__(self, Input1, Input2): 23 | # ParentClass.__init__(self) 24 | # self.Attribute1 = Input1 25 | # self.Attribute2 = Input2 26 | # self.Attribute3 = 0 27 | # 28 | # def AnotherMethod(self): 29 | # Action(s) 30 | 31 | ''' 32 | Class Player is derived from the base class or parent class Team 33 | ''' 34 | class Player(Team): 35 | def __init__(self): #constructor 36 | Team.__init__(self) 37 | ''' 38 | The __init__ method of our Team class explicitly invokes the __init__method of the Player class. 39 | ''' 40 | self.PlayerName = "None" #member variable assigned to None 41 | self.PlayerPoints = 0 #member variable assigned to 0 42 | 43 | ''' 44 | Methods: ScoredPoints and setName 45 | ScoredPoints increments the PlayerPoints by 1. 46 | setName sets the name of Player 47 | ''' 48 | def ScoredPoint(self): 49 | self.PlayerPoints += 1 #increments Playerpoints by 1 50 | 51 | def setName(self, name): 52 | self.PlayerName = name #assigned name to Player 53 | 54 | 55 | Player1 = Player() #create an instance of a class Player 56 | print(Player1.PlayerName) #print the value of member variable PlayerName 57 | print(Player1.PlayerPoints) #print the value of member variable PlayerPoints 58 | Player1.DefineTeamName("Sharks") #call methods DefineTeamName 59 | print(Player1.TeamName) #print the value of base class from derived class 60 | print(Player1.TeamOrigin) #print the value of member TeamOrigin of base class from derived class 61 | 62 | 63 | class Player(Team): 64 | ''' 65 | 4 variables are passed into Contructor 66 | ''' 67 | def __init__(self, PlayerName, PPoints, TeamName, TeamOrigin): 68 | Team.__init__(self, TeamName, TeamOrigin) 69 | self.PlayerName = PlayerName 70 | self.PlayerPoints = PPoints 71 | 72 | ''' 73 | Methods: ScoredPoints and setName 74 | ScoredPoints increments the PlayerPoints by 1. 75 | setName sets the name of Player 76 | ''' 77 | def ScoredPoint(self): 78 | self.PlayerPoints += 1 79 | 80 | def setName(self, name): 81 | self.PlayerName = name 82 | 83 | ''' 84 | Override to print a readable string presentation of your object 85 | ''' 86 | def __str__(self): 87 | return self.PlayerName + " has scored: " + str(self.PlayerPoints) + " Points" 88 | 89 | Player1 = Player("Sid", 0, "Sharks", "Chicago") #create an instance of a class Player 90 | print(Player1.PlayerName) #print the value of member variable PlayerName 91 | print(Player1.PlayerPoints) #print the value of member variable PlayerPoints 92 | #Player1.DefineTeamName("Sharks") 93 | print(Player1.TeamName) #print the value of base class from derived class 94 | print(Player1.TeamOrigin) #print the value of member TeamOrigin of base class from derived class 95 | Player1.ScoredPoint() #call method ScoredPoint 96 | print(Player1.PlayerPoints) #access member PlayerPoints from outside the class and print it 97 | Player1.setName("Lee") #call method setName 98 | print(Player1.PlayerName) #print the value of member variable PlayerName 99 | print(Player1) #print the string message. 100 | -------------------------------------------------------------------------------- /classes/Introduction-to-Classes.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Introduction to Classes Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | """ 9 | class is defined by a keyword class 10 | 11 | Classname Team in defined 12 | """ 13 | 14 | class Team: 15 | def __init__(self): #constructor with no arguments 16 | self.TeamName = 'Name' #self represents the instance of the class and the variables of a class can be accessed using self 17 | self.TeamOrigin = 'Origin' #set an attribute 'TeamOrigin to "Origin" 18 | 19 | ''' 20 | DefinieTeamName and DefineTeamOrigin represents the methods of a class. Each method takes one 21 | arguments 22 | ''' 23 | def DefineTeamName(self, Name): 24 | self.TeamName = Name 25 | 26 | def DefineTeamOrigin(self, Origin): 27 | self.TeamOrigin = Origin 28 | 29 | Team1 = Team() #create an object of a class Team 30 | ''' 31 | Methods and Member of a class can be accessed using a dot operator. 32 | object.membername or object.methodname 33 | ''' 34 | print(Team1.TeamName) #Access the member of a class using dot operator and print the value of a member 35 | Team1.DefineTeamName("Tigers") #call methods of a class using a dot operator 36 | print(Team1.TeamName) #print the value of a member TeamName 37 | print(Team1.TeamOrigin) #print the value of a member TeamOrigin 38 | Team1.DefineTeamOrigin("Chicago") #call method DefineTeamOrigin of a class Team 39 | print(Team1.TeamOrigin) #print value of a member TeamOrigin 40 | 41 | ''' 42 | Again Define a class Team 43 | ''' 44 | class Team: 45 | #constructor passes two variables Name and Origin. The 46 | #default value of variable Name is "Name" and that of variable Origin is "Origin". 47 | #If no values are passed through a constructor its default values are Name and Origin. 48 | def __init__(self, Name = "Name", Origin = "Origin"): #constructor 49 | self.TeamName = Name #member assignment 50 | self.TeamOrigin = Origin #member assignment 51 | 52 | def DefineTeamName(self, Name): #class method 53 | self.TeamName = Name 54 | 55 | def DefineTeamOrigin(self, Origin): #class method 56 | self.TeamOrigin = Origin 57 | 58 | Team1 = Team("Tigers", "Chicago") #creating an object of a class Team. 59 | Team2 = Team("Hawks", "Newyork") #creating an instance of a class Team and passing two values. 60 | Team3 = Team() #creating an object of a class with no values passed. 61 | print(Team1.TeamName) #member can be accessed from outside the class using dot operator 62 | Team1.DefineTeamName("Tigers") #call methods from outside the class 63 | print(Team1.TeamName) #print the value of member TeamName 64 | print(Team1.TeamOrigin) #print the value of member TeamOrigin 65 | Team1.DefineTeamOrigin("Chicago") #call method DefineTeamOrigin 66 | print(Team1.TeamOrigin) #print the value of member 67 | print(Team2.TeamName) #print the value of member TeamName of object Team2 68 | print(Team2.TeamOrigin) #print the value of member TeamOrigin of object Team2 69 | print(Team3.TeamName) #print the value of member TeamName of object Team3 70 | print(Team3.TeamOrigin) #print the value of member TeamOrigin of object Team3 71 | -------------------------------------------------------------------------------- /classes/Pets-Part-A.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Pets, Part A Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | # Define a class 8 | class Pet: 9 | 10 | # Define a function which refers to the class in order to initiliaze the attributes of the class 11 | def __init__(self,n,a,h,p): 12 | # Define an attribute and assign the value of the n argument 13 | self.name = n 14 | # Define an attribute and assign the value of the a argument 15 | self.age = a 16 | # Define an attribute and assign the value of the h argument 17 | self.hunger = h 18 | # Define an attribute and assign the value of the p argument 19 | self.playful = p 20 | 21 | # Define a class 22 | class Pet: 23 | 24 | # Define a function which refers to the class in order to initiliaze the attributes of the class 25 | def __init__(self,name,a,h,p): 26 | # Define an attribute and assign the value of the name argument 27 | self.name = name 28 | # Define an attribute and assign the value of the a argument 29 | self.age = a 30 | # Define an attribute and assign the value of the h argument 31 | self.hunger = h 32 | # Define an attribute and assign the value of the p argument 33 | self.playful = p 34 | 35 | # getters 36 | # Define a function to return an attribute of the class 37 | def getName(self): 38 | # The function will return the name attribute 39 | return self.name 40 | 41 | # setters 42 | # Define a function which assigns a value to an attribute of the class 43 | def setName(self,name): 44 | self.name = name 45 | 46 | # Define a class 47 | class Pet: 48 | 49 | # Define a function which refers to the class in order to initiliaze the attributes of the class 50 | def __init__(self,name,a,h,p): 51 | # Define an attribute and assign the value of the name argument 52 | self.name = name 53 | # Define an attribute and assign the value of the a argument 54 | self.age = a 55 | # Define an attribute and assign the value of the h argument 56 | self.hunger = h 57 | # Define an attribute and assign the value of the p argument 58 | self.playful = p 59 | 60 | # getters 61 | # Define a function to return an attribute of the class 62 | def getName(self): 63 | # The function will return the name attribute 64 | return self.name 65 | 66 | # setters 67 | # Define a function which assigns a value to an attribute of the class 68 | def setName(self,x): 69 | self.name = x 70 | 71 | 72 | # Define a class 73 | class Pet: 74 | 75 | # Define a function which refers to the class in order to initiliaze the attributes of the class 76 | def __init__(self,name,a,h,p): 77 | # Define an attribute and assign the value of the name argument 78 | self.name = name 79 | # Define an attribute and assign the value of the a argument 80 | self.age = a 81 | # Define an attribute and assign the value of the h argument 82 | self.hunger = h 83 | # Define an attribute and assign the value of the p argument 84 | self.playful = p 85 | 86 | # getters 87 | # Define a function to return an attribute of the class 88 | def getName(self): 89 | # The function will return the name attribute 90 | return self.name 91 | 92 | # Define a function to return an attribute of the class 93 | def getAge(self): 94 | # The function will return the age attribute 95 | return self.age 96 | 97 | # Define a function to return an attribute of the class 98 | def getHunger(self): 99 | # The function will return the hunger attribute 100 | return self.hunger 101 | 102 | # Define a function to return an attribute of the class 103 | def getPlayful(self): 104 | # The function will return the playful attribute 105 | return self.playful 106 | 107 | # setters 108 | # Define a function which assigns a value to an attribute of the class 109 | def setName(self,xname): 110 | self.name = xname 111 | 112 | # Define a function which assigns a value to an attribute of the class 113 | def setAge(self,Age): 114 | self.age = Age 115 | 116 | # Define a function which assigns a value to an attribute of the class 117 | def setHunger(self,hunger): 118 | self.hunger = hunger 119 | 120 | # Define a function which assigns a value to an attribute of the class 121 | def setPlayful(self,play): 122 | self.playful = play 123 | 124 | # Create an instance of the Pet class and assign values to the attributes 125 | Pet1 = Pet("Jim",3,False,True) 126 | 127 | # Print the value returned by the getName() function of the Pet1 instance 128 | # This will print "Jim" 129 | print(Pet1.getName()) 130 | #Print the value returned by the getPlayful() function of the Pet1 instance 131 | # This will print True 132 | print(Pet1.getPlayful()) 133 | 134 | # Call the setName(xname) function of the Pet1 instance 135 | # This will assign a new value to the name attribute of the Pet1 instance 136 | Pet1.setName("Snowball") 137 | # Print the value returned by the getName() function of the Pet1 instance 138 | # This will print "Snowball" 139 | print(Pet1.getName()) 140 | 141 | # Access and print the name attribute of the Pet1 instance 142 | # This will print "Snowball" 143 | print(Pet1.name) 144 | 145 | # Assign the value "Jim" to the name attribute of the Pet1 instance 146 | Pet1.name = "Jim" 147 | # Access and print the name attribute of the Pet1 instance 148 | # This will print "Jim" 149 | print(Pet1.name) 150 | -------------------------------------------------------------------------------- /classes/Pets-Part-B.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Pets, Part B Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | # Define a class 9 | class Pet: 10 | 11 | # Define a function which refers to the class in order to initiliaze the attributes of the class 12 | def __init__(self,name,a,h,p): 13 | # Define an attribute and assign the value of the name argument 14 | self.name = name 15 | # Define an attribute and assign the value of the a argument 16 | self.age = a 17 | # Define an attribute and assign the value of the h argument 18 | self.hunger = h 19 | # Define an attribute and assign the value of the p argument 20 | self.playful = p 21 | 22 | # getters 23 | # Define a function to return an attribute of the class 24 | def getName(self): 25 | # The function will return the name attribute 26 | return self.name 27 | 28 | # Define a function to return an attribute of the class 29 | def getAge(self): 30 | # The function will return the age attribute 31 | return self.age 32 | 33 | # Define a function to return an attribute of the class 34 | def getHunger(self): 35 | # The function will return the hunger attribute 36 | return self.hunger 37 | 38 | # Define a function to return an attribute of the class 39 | def getPlayful(self): 40 | # The function will return the playful attribute 41 | return self.playful 42 | 43 | # setters 44 | # Define a function which assigns a value to an attribute of the class 45 | def setName(self,xname): 46 | self.name = xname 47 | 48 | # Define a function which assigns a value to an attribute of the class 49 | def setAge(self,Age): 50 | self.age = Age 51 | 52 | # Define a function which assigns a value to an attribute of the class 53 | def setHunger(self,hunger): 54 | self.hunger = hunger 55 | 56 | # Define a function which assigns a value to an attribute of the class 57 | def setPlayful(self,play): 58 | self.playful = play 59 | 60 | 61 | # The class is commented becuse two errors exist. One is in line 65 where the self argument is missing 62 | # and the second error is in line 81 where the code should be self.FavoriteToy 63 | # Define a class which inherits the Pet class 64 | #class Dog(Pet): 65 | # 66 | # # Define a function which refers to the class in order to initiliaze the attributes of the class 67 | # def __init__(self,name,age,hunger,playful,breed,FavoriteToy): 68 | # # Call the initializer of the parent class with the proper parameters 69 | # # Error - the self argument is missing 70 | # Pet.__init__(name,age,hunger,playful) 71 | # 72 | # # The following line will return an error if uncommented 73 | # #self.__init__(name,age,hunger,playful) 74 | # 75 | # # Define an attribute and assign the value "None" 76 | # self.breed = breed 77 | # self.FavoriteToy = FavoriteToy 78 | # 79 | # # Define unction which refers to the class 80 | # def wantsToPlay(self): 81 | # 82 | # # IF condition is True 83 | # if self.playful == True: 84 | # # Define the string which the function returns 85 | # # Error - It should be self.FavoriteToy 86 | # return("Dog wants to play with " + FavoriteToy) 87 | # 88 | # # ELSE condition 89 | # else: 90 | # # Define the string which the function returns 91 | # return("Dog doesn't want to play") 92 | # 93 | # Create an instance of the Dog class and assign values to the attributes 94 | #huskyDog = Dog("Snowball",5,False,True,"Husky","Stick") 95 | # 96 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 97 | #Play = huskyDog.wantsToPlay() 98 | # 99 | # Print the value of the Play variable 100 | # This will print "Dog wants to play with Stick" 101 | #print(Play) 102 | 103 | 104 | 105 | # Define a class which inherits the Pet class 106 | class Dog(Pet): 107 | 108 | # Define a function which refers to the class in order to initiliaze the attributes of the class 109 | def __init__(self,name,age,hunger,playful,breed,FavoriteToy): 110 | # Call the initializer of the parent class with the proper parameters 111 | Pet.__init__(self,name,age,hunger,playful) 112 | 113 | # The following line will return an error if uncommented 114 | #self.__init__(name,age,hunger,playful) 115 | 116 | # Define an attribute and assign the value "None" 117 | self.breed = breed 118 | self.FavoriteToy = FavoriteToy 119 | 120 | # Define unction which refers to the class 121 | def wantsToPlay(self): 122 | 123 | # IF condition is True 124 | if self.playful == True: 125 | # Define the string which the function returns 126 | return("Dog wants to play with " + self.FavoriteToy) 127 | 128 | # ELSE condition 129 | else: 130 | # Define the string which the function returns 131 | return("Dog doesn't want to play") 132 | 133 | # Create an instance of the Dog class and assign values to the attributes 134 | huskyDog = Dog("Snowball",5,False,True,"Husky","Stick") 135 | 136 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 137 | Play = huskyDog.wantsToPlay() 138 | 139 | # Print the value of the Play variable 140 | # This will print "Dog wants to play with Stick" 141 | print(Play) 142 | 143 | # Assign the value False to the playful attribute of the huskyDog instance 144 | huskyDog.playful = False 145 | 146 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 147 | Play = huskyDog.wantsToPlay() 148 | 149 | # Print the value of the Play variable 150 | # This will print "Dog doesn't want to play" 151 | print(Play) 152 | -------------------------------------------------------------------------------- /classes/Pets-Part-C.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Pets, Part C Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | # Define a class 9 | class Pet: 10 | 11 | # Define a function which refers to the class in order to initiliaze the attributes of the class 12 | def __init__(self,name,a,h,p): 13 | # Define an attribute and assign the value of the name argument 14 | self.name = name 15 | # Define an attribute and assign the value of the a argument 16 | self.age = a 17 | # Define an attribute and assign the value of the h argument 18 | self.hunger = h 19 | # Define an attribute and assign the value of the p argument 20 | self.playful = p 21 | 22 | # getters 23 | # Define a function to return an attribute of the class 24 | def getName(self): 25 | # The function will return the name attribute 26 | return self.name 27 | 28 | # Define a function to return an attribute of the class 29 | def getAge(self): 30 | # The function will return the age attribute 31 | return self.age 32 | 33 | # Define a function to return an attribute of the class 34 | def getHunger(self): 35 | # The function will return the hunger attribute 36 | return self.hunger 37 | 38 | # Define a function to return an attribute of the class 39 | def getPlayful(self): 40 | # The function will return the playful attribute 41 | return self.playful 42 | 43 | # setters 44 | # Define a function which assigns a value to an attribute of the class 45 | def setName(self,xname): 46 | self.name = xname 47 | 48 | # Define a function which assigns a value to an attribute of the class 49 | def setAge(self,Age): 50 | self.age = Age 51 | 52 | # Define a function which assigns a value to an attribute of the class 53 | def setHunger(self,hunger): 54 | self.hunger = hunger 55 | 56 | # Define a function which assigns a value to an attribute of the class 57 | def setPlayful(self,play): 58 | self.playful = play 59 | 60 | # Define a function which refers to the class and returns a string 61 | def __str__(self): 62 | # Define the string which the function returns 63 | return (self.name + " is " +str(self.age) + " years old") 64 | 65 | 66 | # The class is commented becuse two errors exist. One is in line 65 where the self argument is missing 67 | # and the second error is in line 81 where the code should be self.FavoriteToy 68 | # Define a class which inherits the Pet class 69 | #class Dog(Pet): 70 | # 71 | # # Define a function which refers to the class in order to initiliaze the attributes of the class 72 | # def __init__(self,name,age,hunger,playful,breed,FavoriteToy): 73 | # # Call the initializer of the parent class with the proper parameters 74 | # # Error - the self argument is missing 75 | # Pet.__init__(name,age,hunger,playful) 76 | # 77 | # # The following line will return an error if uncommented 78 | # #self.__init__(name,age,hunger,playful) 79 | # 80 | # # Define an attribute and assign the value "None" 81 | # self.breed = breed 82 | # self.FavoriteToy = FavoriteToy 83 | # 84 | # # Define unction which refers to the class 85 | # def wantsToPlay(self): 86 | # 87 | # # IF condition is True 88 | # if self.playful == True: 89 | # # Define the string which the function returns 90 | # # Error - It should be self.FavoriteToy 91 | # return("Dog wants to play with " + FavoriteToy) 92 | # 93 | # # ELSE condition 94 | # else: 95 | # # Define the string which the function returns 96 | # return("Dog doesn't want to play") 97 | # 98 | # Create an instance of the Dog class and assign values to the attributes 99 | #huskyDog = Dog("Snowball",5,False,True,"Husky","Stick") 100 | # 101 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 102 | #Play = huskyDog.wantsToPlay() 103 | # 104 | # Print the value of the Play variable 105 | # This will print "Dog wants to play with Stick" 106 | #print(Play) 107 | 108 | 109 | 110 | # Define a class which inherits the Pet class 111 | class Dog(Pet): 112 | 113 | # Define a function which refers to the class in order to initiliaze the attributes of the class 114 | def __init__(self,name,age,hunger,playful,breed,FavoriteToy): 115 | # Call the initializer of the parent class with the proper parameters 116 | Pet.__init__(self,name,age,hunger,playful) 117 | 118 | # The following line will return an error if uncommented 119 | #self.__init__(name,age,hunger,playful) 120 | 121 | # Define an attribute and assign the value of the breed argument 122 | self.breed = breed 123 | # Define an attribute and assign the value of the FavoriteToy argument 124 | self.FavoriteToy = FavoriteToy 125 | 126 | # Define unction which refers to the class 127 | def wantsToPlay(self): 128 | # IF condition is True 129 | if self.playful == True: 130 | # Define the string which the function returns 131 | return("Dog wants to play with " + self.FavoriteToy) 132 | # ELSE condition 133 | else: 134 | # Define the string which the function returns 135 | return("Dog doesn't want to play") 136 | 137 | 138 | # Define a class which inherits the Pet class 139 | class Cat(Pet): 140 | 141 | # Define a function which refers to the class in order to initiliaze the attributes of the class 142 | def __init__(self,name,age,hunger,playful,place): 143 | 144 | # Call the initializer of the parent class with the proper parameters 145 | Pet.__init__(self,name,age,hunger,playful) 146 | 147 | # Define an attribute and assign the value of the place argument 148 | self.FavoritePlaceToSit = place 149 | 150 | # Define unction which refers to the class 151 | def wantsToSit(self): 152 | # IF condition is True 153 | if self.playful == False: 154 | # Define the string which the function returns 155 | # The following line will produce an error if uncommented due to the self.place part of the code 156 | #print("The cat wants to sit in" ,self.place) 157 | print("The cat wants to sit in" ,self.FavoritePlaceToSit) 158 | # ELSE condition 159 | else: 160 | # Define the string which the function returns 161 | print("The cat wants to play") 162 | 163 | # Define a function which refers to the class and returns a string 164 | def __str__(self): 165 | # Define the string which the function returns 166 | return (self.name + " likes to sit in " + self.FavoritePlaceToSit) 167 | 168 | 169 | # Create an instance of the Dog class and assign values to the attributes 170 | huskyDog = Dog("Snowball",5,False,True,"Husky","Stick") 171 | 172 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 173 | Play = huskyDog.wantsToPlay() 174 | 175 | # Print the value of the Play variable 176 | # This will print "Dog wants to play with Stick" 177 | print(Play) 178 | 179 | # Assign the value False to the playful attribute of the huskyDog instance 180 | huskyDog.playful = False 181 | 182 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 183 | Play = huskyDog.wantsToPlay() 184 | 185 | # Print the value of the Play variable 186 | # This will print "Dog doesn't want to play" 187 | print(Play) 188 | 189 | # Create an instance of the Cat class and assign values to the attributes 190 | typicalCat = Cat("Fluffy",3,False,False,"the sun ray") 191 | 192 | # Call the wantsToSit() function of the typicalCat instance 193 | # This will print "The cat wants to sit in the sun ray" 194 | typicalCat.wantsToSit() 195 | 196 | # This will print the returned string from the __str__ function of the typicalCat instance 197 | # This will print "Fluffy likes to sit in the sun ray" 198 | print(typicalCat) 199 | # The __str__ function is not defined in the Dog function so it will return general inforamtion on the class 200 | # This will print 201 | print(Dog) 202 | -------------------------------------------------------------------------------- /classes/Pets-Part-D.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Pets, Part D Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | # Define a class 9 | class Pet: 10 | 11 | # Define a function which refers to the class in order to initiliaze the attributes of the class 12 | def __init__(self,name,a,h,p): 13 | # Define an attribute and assign the value of the name argument 14 | self.name = name 15 | # Define an attribute and assign the value of the a argument 16 | self.age = a 17 | # Define an attribute and assign the value of the h argument 18 | self.hunger = h 19 | # Define an attribute and assign the value of the p argument 20 | self.playful = p 21 | 22 | # getters 23 | # Define a function to return an attribute of the class 24 | def getName(self): 25 | # The function will return the name attribute 26 | return self.name 27 | 28 | # Define a function to return an attribute of the class 29 | def getAge(self): 30 | # The function will return the age attribute 31 | return self.age 32 | 33 | # Define a function to return an attribute of the class 34 | def getHunger(self): 35 | # The function will return the hunger attribute 36 | return self.hunger 37 | 38 | # Define a function to return an attribute of the class 39 | def getPlayful(self): 40 | # The function will return the playful attribute 41 | return self.playful 42 | 43 | # setters 44 | # Define a function which assigns a value to an attribute of the class 45 | def setName(self,xname): 46 | self.name = xname 47 | 48 | # Define a function which assigns a value to an attribute of the class 49 | def setAge(self,Age): 50 | self.age = Age 51 | 52 | # Define a function which assigns a value to an attribute of the class 53 | def setHunger(self,hunger): 54 | self.hunger = hunger 55 | 56 | # Define a function which assigns a value to an attribute of the class 57 | def setPlayful(self,play): 58 | self.playful = play 59 | 60 | # Define a function which refers to the class and returns a string 61 | def __str__(self): 62 | # Define the string which the function returns 63 | return (self.name + " is " +str(self.age) + " years old") 64 | 65 | 66 | # The class is commented becuse two errors exist. One is in line 65 where the self argument is missing 67 | # and the second error is in line 81 where the code should be self.FavoriteToy 68 | # Define a class which inherits the Pet class 69 | #class Dog(Pet): 70 | # 71 | # # Define a function which refers to the class in order to initiliaze the attributes of the class 72 | # def __init__(self,name,age,hunger,playful,breed,FavoriteToy): 73 | # # Call the initializer of the parent class with the proper parameters 74 | # # Error - the self argument is missing 75 | # Pet.__init__(name,age,hunger,playful) 76 | # 77 | # # The following line will return an error if uncommented 78 | # #self.__init__(name,age,hunger,playful) 79 | # 80 | # # Define an attribute and assign the value "None" 81 | # self.breed = breed 82 | # self.FavoriteToy = FavoriteToy 83 | # 84 | # # Define unction which refers to the class 85 | # def wantsToPlay(self): 86 | # 87 | # # IF condition is True 88 | # if self.playful == True: 89 | # # Define the string which the function returns 90 | # # Error - It should be self.FavoriteToy 91 | # return("Dog wants to play with " + FavoriteToy) 92 | # 93 | # # ELSE condition 94 | # else: 95 | # # Define the string which the function returns 96 | # return("Dog doesn't want to play") 97 | # 98 | # Create an instance of the Dog class and assign values to the attributes 99 | #huskyDog = Dog("Snowball",5,False,True,"Husky","Stick") 100 | # 101 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 102 | #Play = huskyDog.wantsToPlay() 103 | # 104 | # Print the value of the Play variable 105 | # This will print "Dog wants to play with Stick" 106 | #print(Play) 107 | 108 | 109 | 110 | # Define a class which inherits the Pet class 111 | class Dog(Pet): 112 | 113 | # Define a function which refers to the class in order to initiliaze the attributes of the class 114 | def __init__(self,name,age,hunger,playful,breed,FavoriteToy): 115 | # Call the initializer of the parent class with the proper parameters 116 | Pet.__init__(self,name,age,hunger,playful) 117 | 118 | # The following line will return an error if uncommented 119 | #self.__init__(name,age,hunger,playful) 120 | 121 | # Define an attribute and assign the value of the breed argument 122 | self.breed = breed 123 | # Define an attribute and assign the value of the FavoriteToy argument 124 | self.FavoriteToy = FavoriteToy 125 | 126 | # Define unction which refers to the class 127 | def wantsToPlay(self): 128 | # IF condition is True 129 | if self.playful == True: 130 | # Define the string which the function returns 131 | return("Dog wants to play with " + self.FavoriteToy) 132 | # ELSE condition 133 | else: 134 | # Define the string which the function returns 135 | return("Dog doesn't want to play") 136 | 137 | 138 | # Define a class which inherits the Pet class 139 | class Cat(Pet): 140 | 141 | # Define a function which refers to the class in order to initiliaze the attributes of the class 142 | def __init__(self,name,age,hunger,playful,place): 143 | 144 | # Call the initializer of the parent class with the proper parameters 145 | Pet.__init__(self,name,age,hunger,playful) 146 | 147 | # Define an attribute and assign the value of the place argument 148 | self.FavoritePlaceToSit = place 149 | 150 | # Define unction which refers to the class 151 | def wantsToSit(self): 152 | # IF condition is True 153 | if self.playful == False: 154 | # Define the string which the function prints 155 | # The following line will produce an error if uncommented due to the self.place part of the code 156 | #print("The cat wants to sit in" ,self.place) 157 | print("The cat wants to sit in" ,self.FavoritePlaceToSit) 158 | # ELSE condition 159 | else: 160 | # Define the string which the function prints 161 | print("The cat wants to play") 162 | 163 | # Define a function which refers to the class and returns a string 164 | def __str__(self): 165 | # Define the string which the function returns 166 | return (self.name + " likes to sit in " + self.FavoritePlaceToSit) 167 | 168 | # Define a class 169 | class Human: 170 | # Define a function which refers to the class in order to initiliaze the attributes of the class 171 | def __init__(self,name,Pets): 172 | # Define an attribute and assign the value of the name argument 173 | self.name = name 174 | # Define an attribute and assign the value of the Pets argument 175 | self.Pets = Pets 176 | 177 | def hasPets(self): 178 | # IF condition is True 179 | # If the Human has Pets 180 | if len(self.Pets) != 0: 181 | # Define the string which the function returns 182 | return "yes" 183 | # ELSE condition 184 | else: 185 | # Define the string which the function returns 186 | return "no" 187 | 188 | 189 | 190 | 191 | 192 | # Create an instance of the Dog class and assign values to the attributes 193 | huskyDog = Dog("Snowball",5,False,True,"Husky","Stick") 194 | 195 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 196 | Play = huskyDog.wantsToPlay() 197 | 198 | # Print the value of the Play variable 199 | # This will print "Dog wants to play with Stick" 200 | print(Play) 201 | 202 | # Assign the value False to the playful attribute of the huskyDog instance 203 | huskyDog.playful = False 204 | 205 | # Assign to a variable the result returned by the wantsToPlay() function of the huskyDog instance 206 | Play = huskyDog.wantsToPlay() 207 | 208 | # Print the value of the Play variable 209 | # This will print "Dog doesn't want to play" 210 | print(Play) 211 | 212 | # Create an instance of the Cat class and assign values to the attributes 213 | typicalCat = Cat("Fluffy",3,False,False,"the sun ray") 214 | 215 | # Call the wantsToSit() function of the typicalCat instance 216 | # This will print "The cat wants to sit in the sun ray" 217 | typicalCat.wantsToSit() 218 | 219 | # This will print the returned string from the __str__ function of the typicalCat instance 220 | # This will print "Fluffy likes to sit in the sun ray" 221 | print(typicalCat) 222 | # The __str__ function is not defined in the Dog function so it will return general inforamtion on the class 223 | # This will print 224 | print(Dog) 225 | # This will print the returned string from the __str__ function of the huskyDog instance which is inherited by the Pet class 226 | # This will print "Snowball is 5 years old" 227 | print(huskyDog) 228 | 229 | # Create an instance of the Human class and assign values to the attributes 230 | yourAverageHuman = Human("Alice",[huskyDog,typicalCat]) 231 | 232 | # Assign to a variable the result returned by the hasPets() function of the yourAverageHuman instance 233 | hasPet = yourAverageHuman.hasPets() 234 | 235 | # Print the value of the hasPet variable 236 | # This will print "yes" 237 | print(hasPet) 238 | 239 | # Print the first element in the Pets list attribute of the yourAverageHuman instance 240 | # The huskyDog instance is the first element in the Pets list attribute of the yourAverageHuman instance 241 | # This will print the returned string from the __str__ function of the huskyDog instance which is inherited by the Pet class 242 | # This will print "Snowball is 5 years old" 243 | print(yourAverageHuman.Pets[0]) 244 | 245 | # Print the second element in the Pets list attribute of the yourAverageHuman instance 246 | # The typicalCat instance is the second element in the Pets list attribute of the yourAverageHuman instance 247 | # This will print the returned string from the __str__ function of the typicalCat instance 248 | # This will print "Fluffy likes to sit in the sun ray" 249 | print(yourAverageHuman.Pets[1]) 250 | 251 | # Print the name attribute of the second element in the Pets list attribute of the yourAverageHuman instance 252 | # The typicalCat instance is the second element in the Pets list attribute of the yourAverageHuman instance 253 | # This will print "Fluffy" 254 | print(yourAverageHuman.Pets[1].name) 255 | 256 | # Print the name attribute of the first element in the Pets list attribute of the yourAverageHuman instance 257 | # The huskyDog instance is the first element in the Pets list attribute of the yourAverageHuman instance 258 | # This will print "Snowball" 259 | print(yourAverageHuman.Pets[0].name) 260 | -------------------------------------------------------------------------------- /dictionaries and sets/Dictionaries-and-Sets.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Dictionaries and Sets Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | """ 9 | A set is a data structure in python like a list to store a variety of hetrogenous unique elements. 10 | Hetrogenous means a set can contain primitive types integer , string , float in it. 11 | Unique means that each element can occur only once in a set 12 | """ 13 | 14 | # Declaring a set 'Sets' with different string values in it 15 | Sets={"Element1","Element2","Element1","Element4"} 16 | # Printing variable 'Sets' using the 'print' function 17 | print(Sets) 18 | # Output 19 | """ 20 | {'Element1', 'Element4', 'Element2'} 21 | """ 22 | # Notice how the output is different from the input in two ways 23 | # 1) Only unique elements are printed 24 | # 2) Elements are not printed in the same order as they were stored because in sets order doesnt matter 25 | 26 | 27 | # Here 'if' condition is used along with 'in' keyword to check whether the value "Element1" is present in set 'Sets' 28 | if "Element1" in Sets: 29 | # If the value "Element1" is found print "Yes" to console 30 | print("Yes") 31 | # Output 32 | """ 33 | Yes 34 | """ 35 | 36 | 37 | # Declaring a list variable 'CountryList' and assigning empty list to it by using '[]' 38 | CountryList = [] 39 | 40 | # For loop is used with 'range(5)' indicating the loop will run 5 times from 0-4 41 | for i in range(5): 42 | # Taking input from user and assigning it to variable named 'Country' using 'input(range_value)' function 43 | Country = input("Please Enter Your Country: ") 44 | # 'append(variable_name)' function is used here which adds a new element into the list 'CountryList' 45 | CountryList.append(Country) 46 | 47 | # 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 48 | CountrySet = set(CountryList) 49 | 50 | # Printing list 'CountryList' 51 | print(CountryList) 52 | # Printing set 'CountrySet' 53 | print(CountrySet) 54 | # Output 55 | """ 56 | Please Enter Your Country: US 57 | Please Enter Your Country: France 58 | Please Enter Your Country: India 59 | Please Enter Your Country: Brazil 60 | Please Enter Your Country: France 61 | ['US', 'France', 'India', 'Brazil', 'France'] 62 | {'France', 'India', 'Brazil', 'US'} 63 | """ 64 | # First the program asks to entry country names 5 times and then the list and set is printed 65 | # Notice how the set has changed order and only prints unique elements which is the property of set 66 | 67 | # Here 'if' condition is used along with 'in' keyword to check whether the value "Brazil" is present in set 'CountrySet' 68 | if "Brazil" in CountrySet: 69 | # If the value "Brazil" is found print "attended" to console 70 | print("attended") 71 | # Output 72 | """ 73 | attended 74 | """ 75 | 76 | """ 77 | A dictionary is another data structure in python that also supports hetrogenous data to be stored inside it. 78 | 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 79 | A dictionary should also contain unique keys and can contain even lists inside of it. 80 | """ 81 | 82 | # Declaring a dictonary variable named 'Dictonary' and assigning keys and values to it 83 | # "Key" , "Key1", "Key2" are the keys 84 | # "Value" , "Value1" , "Value2" are the corresponding values 85 | Dictionary={"Key":"Value","Key1":"Value1","Key2":"Value2"} 86 | # Printing the dictonary variable 'Dictionary' 87 | print(Dictionary) 88 | # Output 89 | """ 90 | {'Key': 'Value', 'Key1': 'Value1', 'Key2': 'Value2'} 91 | """ 92 | 93 | 94 | # Declaring a list variable 'CountryList' and assigning empty list to it by using '[]' 95 | CountryList = [] 96 | 97 | # For loop is used with 'range(5)' indicating the loop will run 5 times from 0-4 98 | for i in range(5): 99 | # Taking input from user and assigning it to variable named 'Country' using 'input(range_value)' function 100 | Country = input("Please Enter Your Country: ") 101 | # 'append(variable_name)' function is used here which adds a new element into the list 'CountryList' 102 | CountryList.append(Country) 103 | 104 | 105 | # Declaring a dictionary variable 'CountryDictionary' and assigning empty dictionary to it by using '{}' 106 | CountryDictionary={} 107 | 108 | # A for loop is used using 'for in syntax' to access the elements of list 'CountryList' and stored it in local variable named 'Country' 109 | for Country in CountryList: 110 | # If statement is used in order to check if the country name is present as a key in dictionary 'CountryDictionary' 111 | if Country in CountryDictionary: 112 | # upon finding the key the value is accessed using 'DictionaryName[key_name]' synatx and incremented one to it 113 | CountryDictionary[Country] +=1 114 | else: 115 | # if the key is not found then creating a new key with country name and assigning one to it 116 | # Notice how no error will be produced which was occuring in list when tried to access an element whcih didnt existed 117 | CountryDictionary[Country] = 1 118 | 119 | # Printing the dictionary variable 'CountryDictionary' 120 | print(CountryDictionary) 121 | # Output 122 | """ 123 | Please Enter Your Country: US 124 | Please Enter Your Country: France 125 | Please Enter Your Country: India 126 | Please Enter Your Country: Brazil 127 | Please Enter Your Country: France 128 | {'France': 2, 'India': 1, 'Brazil': 1,'US': 1} 129 | """ 130 | # No order is mainatined in dictionary as well 131 | -------------------------------------------------------------------------------- /dictionaries and sets/Examples-of-Dictionaries-and-Sets.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Examples of Dictionaries and Sets - Lecture 3 | ## 4 | 5 | 6 | # Declaring a dictonary variable named 'BlackShoes' and assigning keys and values to it 7 | # 42 , 41, 40 , 39 , 38 are the keys 8 | # 2 , 3 , 4 , 1 , 0 are the corresponding values 9 | BlackShoes={42:2,41:3,40:4,39:1,38:0} 10 | 11 | # Printing the dictionary variable 'BlackShoes' 12 | print(BlackShoes) 13 | 14 | # Using a while loop which will run endlesly until a given condition is met 15 | while (True): # True==True 16 | # Taking input from user and assigning it to variable named 'purchaseSize' using 'input()' function 17 | # notice \n in the code which is used to bring new line 18 | # int(variable_name) converts the the variable to type integer 19 | purchaseSize = int(input("Which shoe size would you like to buy?\n")) 20 | # Accessing the value of key 'purchaseSize' and decreasing it by 1 21 | BlackShoes[purchaseSize] -= 1 # BlackShoes[purchaseSize]=BlackShoes[purchaseSize]-1 both are same 22 | # Printing the dictionary variable 'BlackShoes' 23 | print(BlackShoes) 24 | # Output 25 | """ 26 | {42: 2, 41: 3, 40: 4, 39: 1, 38: 0} 27 | Which shoe size would you like to buy? 28 | 42 29 | {42: 1, 41: 3, 40: 4, 39: 1, 38: 0} 30 | Which shoe size would you like to buy? 31 | 39 32 | {42: 1, 41: 3, 40: 4, 39: 0, 38: 0} 33 | Which shoe size would you like to buy? 34 | 38 35 | {42: 1, 41: 3, 40: 4, 39: 0, 38: -1} 36 | """ 37 | # Notice the issue in the code where the value of shoe size goes to negative and this needs to be fixed 38 | 39 | 40 | 41 | # Declaring a dictonary variable named 'BlackShoes' and assigning keys and values to it 42 | # 42 , 41, 40 , 39 , 38 are the keys 43 | # 2 , 3 , 4 , 1 , 0 are the corresponding values 44 | BlackShoes={42:2,41:3,40:4,39:1,38:0} 45 | 46 | # Printing the dictionary variable 'BlackShoes' 47 | print(BlackShoes) 48 | 49 | # Using a while loop which will run endlesly until a given condition is met 50 | while (True): # True==True 51 | # Taking input from user and assigning it to variable named 'purchaseSize' using 'input()' function 52 | # notice \n in the code which is used to bring new line 53 | # int(variable_name) converts the the variable to type integer 54 | purchaseSize = int(input("Which shoe size would you like to buy?\n")) 55 | # If statement is used in order to check if the value of shoe size is greater than zero 56 | if BlackShoes[purchaseSize] > 0: 57 | # Accessing the value of key 'purchaseSize' and decreasing it by 1 58 | BlackShoes[purchaseSize] -= 1 # BlackShoes[purchaseSize]=BlackShoes[purchaseSize]-1 both are same 59 | # If size is not greater than zero then we print message using 'print()' function to user 60 | else: 61 | # Printing message 62 | print("Shoes are no longer in stock") 63 | # Printing the dictionary variable 'BlackShoes' 64 | print(BlackShoes) 65 | # Output 66 | """ 67 | {42: 2, 41: 3, 40: 4, 39: 1, 38: 0} 68 | Which shoe size would you like to buy? 69 | 42 70 | {42: 1, 41: 3, 40: 4, 39: 1, 38: 0} 71 | Which shoe size would you like to buy? 72 | 38 73 | Shoes are no longer in stock 74 | {42: 1, 41: 3, 40: 4, 39: 1, 38: 0} 75 | Which shoe size would you like to buy? 76 | 77 | """ 78 | # Notice that the negative number problem is fixed but the loop is never ending and this needs to be fixed as well 79 | 80 | 81 | 82 | 83 | # Declaring a dictonary variable named 'BlackShoes' and assigning keys and values to it 84 | # 42 , 41, 40 , 39 , 38 are the keys 85 | # 2 , 3 , 4 , 1 , 0 are the corresponding values 86 | BlackShoes={42:2,41:3,40:4,39:1,38:0} 87 | 88 | # Printing the dictionary variable 'BlackShoes' 89 | print(BlackShoes) 90 | 91 | # Using a while loop which will run endlesly until a given condition is met 92 | while (True): # True==True 93 | # Taking input from user and assigning it to variable named 'purchaseSize' using 'input()' function 94 | # notice \n in the code which is used to bring new line 95 | # int(variable_name) converts the the variable to type integer 96 | purchaseSize = int(input("Which shoe size would you like to buy?\n")) 97 | # If statement is used to check if the entered amount is less than 0 98 | if purchaseSize < 0: 99 | # if it is then 'break' keyword is used to terminate the loop 100 | break 101 | # If statement is used in order to check if the value of shoe size is greater than zero 102 | if BlackShoes[purchaseSize] > 0: 103 | # Accessing the value of key 'purchaseSize' and decreasing it by 1 104 | BlackShoes[purchaseSize] -= 1 # BlackShoes[purchaseSize]=BlackShoes[purchaseSize]-1 both are same 105 | # If size is not greater than zero then we print message using 'print()' function to user 106 | else: 107 | # Printing message 108 | print("Shoes are no longer in stock") 109 | # Printing the dictionary variable 'BlackShoes' 110 | print(BlackShoes) 111 | # Output 112 | """ 113 | {42: 2, 41: 3, 40: 4, 39: 1, 38: 0} 114 | Which shoe size would you like to buy? 115 | 38 116 | Shoes are no longer in stock 117 | {42: 2, 41: 3, 40: 4, 39: 1, 38: 0} 118 | Which shoe size would you like to buy? 119 | 40 120 | {42: 2, 41: 3, 40: 3, 39: 1, 38: 0} 121 | Which shoe size would you like to buy? 122 | -1 123 | """ 124 | -------------------------------------------------------------------------------- /error handling/main.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Error Handling Lecture 3 | ## 4 | 5 | 6 | # float("123.4") - > 123.4 7 | # float("N/A") - > error 8 | 9 | """ 10 | 'try' 'except' is a way of handling errors in phyton 11 | 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 12 | """ 13 | 14 | 15 | try: 16 | # Printing 'Hello' using the 'print()' function 17 | print("Hello") 18 | except: 19 | # Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function 20 | print("Entered exception") 21 | 22 | # Output 23 | """ 24 | Hello 25 | """ 26 | # Hello is printed since no error occured in the try block 27 | 28 | 29 | try: 30 | # Printing 'Hello' using the 'print()' function 31 | print(int("Hello")) 32 | except: 33 | # Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function 34 | print("Entered exception") 35 | 36 | # Output 37 | """ 38 | Entered exception 39 | """ 40 | # Entered exception is printed since error occured in the try block 41 | 42 | 43 | 44 | try: 45 | # Printing 'Hello' using the 'print()' function 46 | print(int("Hello")) 47 | except: 48 | # Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function 49 | print("Entered exception") 50 | 51 | # Printing 'Past exception' using the 'print()' function 52 | print("Past exception") 53 | # Output 54 | """ 55 | Entered exception 56 | Past exception 57 | """ 58 | # Both the Entered exception and passed exception has been printed , this shows that the program doesnt stops if an error has occured 59 | 60 | # Declared a variable 'keyword' with a value of "123" 61 | keyword="123" 62 | try: 63 | # Printing variable 'keyword' using the 'print()' function 64 | print(int(keyword)) 65 | except: 66 | # Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function 67 | print("Entered exception") 68 | 69 | # Printing 'Past exception' using the 'print()' function 70 | print("Past exception") 71 | # Output 72 | """ 73 | 123 74 | Past exception 75 | """ 76 | 77 | 78 | 79 | # Declared a variable 'keyword' with a value of "Hello" 80 | keyword="Hello" 81 | try: 82 | # Printing variable 'keyword' using the 'print()' function 83 | print(int(keyword)) 84 | except: 85 | # Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function 86 | print("Entered exception") 87 | 88 | # Printing 'Past exception' using the 'print()' function 89 | print("Past exception") 90 | # Output 91 | """ 92 | Entered exception 93 | Past exception 94 | """ 95 | 96 | 97 | # Declared a variable 'keyword' with a value of "Hello" 98 | keyword="Hello" 99 | try: 100 | # Printing variable 'keyword' using the 'print()' function 101 | print(int(keyword)) 102 | except: 103 | # 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 104 | pass 105 | 106 | # Printing 'Past exception' using the 'print()' function 107 | print("Past exception") 108 | # Output 109 | """ 110 | Past exception 111 | """ 112 | 113 | 114 | # Declared a variable 'keyword' with a value of "Hello" 115 | keyword="Hello" 116 | try: 117 | # Printing variable 'keyword' using the 'print()' function 118 | print(int(keyword)) 119 | except: 120 | # 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 121 | pass 122 | # Printing 'Enterted Exception' only if any errors occur in the try block using the 'print()' function 123 | print("Entered exception") 124 | 125 | # Printing 'Past exception' using the 'print()' function 126 | print("Past exception") 127 | # Output 128 | """ 129 | Entered exception 130 | Past exception 131 | """ 132 | # Both the Entered exception and Past exception has been printed , because 'pass' keyword is doesnt work like 'break' 133 | 134 | 135 | 136 | 137 | # Declared a variable 'keyword' with a value of "Hello" 138 | keyword="Hello" 139 | try: 140 | # Printing variable 'keyword' using the 'print()' function 141 | print(int(keyword)) 142 | except Exception as e: 143 | # Printing the string version of the catched exception , The exception that has occured can be caught and stored in a variable 144 | print(str(e)) 145 | 146 | # Printing 'Past exception' using the 'print()' function 147 | print("Past exception") 148 | # Output 149 | """ 150 | invalid literal for int() with base 10: 'Hello' 151 | Past exception 152 | """ 153 | 154 | 155 | # Declared a variable 'keyword' with a value of "Hello" 156 | keyword="Hello" 157 | try: 158 | # Printing variable 'keyword' using the 'print()' function 159 | print(int(keyword)) 160 | # If known a specific error can be caught using the 'except' keyword 161 | except ValueError: 162 | # Pinting "got a ValueError" using 'print()' function 163 | print("got a ValueError") 164 | 165 | # Printing 'Past exception' using the 'print()' function 166 | print("Past exception") 167 | # Output 168 | """ 169 | got a ValueError 170 | Past exception 171 | """ 172 | 173 | 174 | # Declared a variable 'keyword' with a value of "Hello" 175 | keyword="Hello" 176 | try: 177 | # Printing variable 'keyword' using the 'print()' function 178 | print(int(keyword)) 179 | # If known a specific error can be caught using the 'except' keyword 180 | except ValueError: 181 | # Printing "got a ValueError" using 'print()' function 182 | print("got a ValueError") 183 | # except can be chained together like if elif statements 184 | except: 185 | # Printing "Other types of exception" using 'print()' function 186 | print("Other tpyes of exception") 187 | 188 | # Printing 'Past exception' using the 'print()' function 189 | print("Past exception") 190 | # Output 191 | """ 192 | got a ValueError 193 | Past exception 194 | """ 195 | # Since ValueError has occured only the 'except' block with 'ValueError' has been executed 196 | 197 | 198 | # Declared a variable 'keyword' with a value of "Hello" 199 | keyword="Hello" 200 | try: 201 | # Printing variable 'keyword' using the 'print()' function 202 | print(int(keyword)) 203 | # If known a specific error can be caught using the 'except' keyword 204 | except ValueError: 205 | # Printing "got a ValueError" using 'print()' function 206 | print("got a ValueError") 207 | # except can be chained together like if elif statements 208 | except: 209 | # Printing "Other types of exception" using 'print()' function 210 | print("Other tpyes of exception") 211 | # The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block 212 | finally: 213 | # Printing "finally" using 'print()' function 214 | print("finally") 215 | 216 | # Printing 'Past exception' using the 'print()' function 217 | print("Past exception") 218 | # Output 219 | """ 220 | got a ValueError 221 | finally 222 | Past exception 223 | """ 224 | # finally has also printed because it always executed 225 | 226 | 227 | 228 | try: 229 | # We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program 230 | raise ValueError 231 | # If known a specific error can be caught using the 'except' keyword 232 | except ValueError: 233 | # Printing "got a ValueError" using 'print()' function 234 | print("got a ValueError") 235 | # except can be chained together like if elif statements 236 | except: 237 | # Printing "Other types of exception" using 'print()' function 238 | print("Other tpyes of exception") 239 | # The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block 240 | finally: 241 | # Printing "finally" using 'print()' function 242 | print("finally") 243 | 244 | # Printing 'Past exception' using the 'print()' function 245 | print("Past exception") 246 | # Output 247 | """ 248 | got a ValueError 249 | finally 250 | Past exception 251 | """ 252 | # got a ValueError is printed because we rasied that error ourselves 253 | 254 | 255 | 256 | try: 257 | # We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program 258 | raise NameError 259 | # If known a specific error can be caught using the 'except' keyword 260 | except ValueError: 261 | # Printing "got a ValueError" using 'print()' function 262 | print("got a ValueError") 263 | # except can be chained together like if elif statements 264 | except: 265 | # Printing "Other types of exception" using 'print()' function 266 | print("Other tpyes of exception") 267 | # The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block 268 | finally: 269 | # Printing "finally" using 'print()' function 270 | print("finally") 271 | 272 | # Printing 'Past exception' using the 'print()' function 273 | print("Past exception") 274 | # Output 275 | """ 276 | Other types of exception 277 | finally 278 | Past exception 279 | """ 280 | # Notice how "Other types of exception" is printed because we have not caught the 'NameError' in any 'except' block 281 | 282 | 283 | 284 | 285 | 286 | try: 287 | # We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program 288 | raise NameError 289 | # If known a specific error can be caught using the 'except' keyword 290 | except ValueError: 291 | # Printing "got a ValueError" using 'print()' function 292 | print("got a ValueError") 293 | # except can be chained together like if elif statements 294 | except: 295 | # Printing "Other types of exception" using 'print()' function 296 | print("Other tpyes of exception") 297 | # We can raise the same error again to manually crash the program 298 | raise 299 | # The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block 300 | finally: 301 | # Printing "finally" using 'print()' function 302 | print("finally") 303 | 304 | # Printing 'Past exception' using the 'print()' function 305 | print("Past exception") 306 | # Output 307 | """ 308 | raise NameError 309 | NameError 310 | """ 311 | 312 | 313 | 314 | try: 315 | # We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program 316 | # A message of "Error" has been passed when we 'raise' the error 317 | raise NameError("Error") 318 | # If known a specific error can be caught using the 'except' keyword 319 | except ValueError: 320 | # Printing "got a ValueError" using 'print()' function 321 | print("got a ValueError") 322 | # except can be chained together like if elif statements 323 | # The error has been catched here and renamed it to 'e' 324 | except Exception as e: 325 | # Printing "Other types of exception" using 'print()' function 326 | print("Other tpyes of exception") 327 | # Printing the String version of error 'e' using 'print()' function 328 | print(str(e)) 329 | # The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block 330 | finally: 331 | # Printing "finally" using 'print()' function 332 | print("finally") 333 | 334 | # Printing 'Past exception' using the 'print()' function 335 | print("Past exception") 336 | # Output 337 | """ 338 | Other tpyes of exception 339 | Error 340 | finally 341 | Past exception 342 | """ 343 | # Notice the message "Error" has also been printed 344 | 345 | 346 | # Declared a variable 'keyword' with a value of "Hello" 347 | keyword="Hello" 348 | try: 349 | # Printing variable 'keyword' using the 'print()' function 350 | print(int(keyword)) 351 | # We can 'raise' call an error using the raise keyword even though the error doesnt occur in the program 352 | # A message of "Error" has been passed when we 'raise' the error 353 | raise NameError("Error") 354 | # The error has been catched here and renamed it to 'e' 355 | except Exception as e: 356 | # Printing "Other types of exception" using 'print()' function 357 | print("Other tpyes of exception") 358 | # Printing the String version of error 'e' using 'print()' function 359 | print(str(e)) 360 | # The 'finally' block is a block always executed , no matter what happens in the 'try' 'except' block 361 | finally: 362 | # Printing "finally" using 'print()' function 363 | print("finally") 364 | 365 | # Printing 'Past exception' using the 'print()' function 366 | print("Past exception") 367 | # Output 368 | """ 369 | Other tpyes of exception 370 | invalid literal for int() with base 10: 'Hello' 371 | finally 372 | Past exception 373 | """ 374 | # Notice the message "Error" has also been printed 375 | -------------------------------------------------------------------------------- /final project/Blackjack-Part-A.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Blackjack, Part A Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | #Import shuffle function from random library 8 | from random import shuffle 9 | 10 | # Create a functions 11 | def createDeck(): 12 | Deck = [] 13 | #Set a variable for faceValues 14 | faceValues = ['A', 'J', 'Q', 'K'] 15 | for i in range(4): #There are 4 different suites 16 | for card in range(2,11): #Adding numbers 2-10 17 | Deck.append(str(card)) 18 | 19 | for card in faceValues: 20 | Deck.append(card) 21 | return Deck #Return products 22 | 23 | #Set a variable to createDock function, and then print it 24 | cardDeck = createDeck() 25 | 26 | shuffle(cardDeck) #Mixing results with shuffle 27 | 28 | print(cardDeck) 29 | -------------------------------------------------------------------------------- /final project/Blackjack-Part-B.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Blackjack, Part B Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | #Import shuffle function from random library 8 | from random import shuffle 9 | 10 | # Create a functions 11 | def createDeck(): 12 | Deck = [] 13 | #Set a variable for faceValues 14 | faceValues = ['A', 'J', 'Q', 'K'] 15 | for i in range(4): #There are 4 different suites 16 | for card in range(2,11): #Adding numbers 2-10 17 | Deck.append(str(card)) 18 | 19 | for card in faceValues: 20 | Deck.append(card) 21 | shuffle(Deck) #Mixing results with shuffle 22 | return Deck #Return products 23 | 24 | #Set a variable to createDock function, and then print it 25 | cardDeck = createDeck() 26 | print(cardDeck) 27 | 28 | # Set a player class 29 | class Player: 30 | def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class 31 | self.hand = hand 32 | self.score = self.setScore() 33 | print(self.score) 34 | self.money = money 35 | 36 | def __str__(self): #__str__ will return a human readable string 37 | currentHand = " " #slef.hand = ["A","10"] 38 | for card in self.hand: 39 | currentHand += str(card) + " " 40 | 41 | #Set a variable for finalStatus, and then return it 42 | finalStatus = currentHand + "score " + str(self.score) 43 | return finalStatus 44 | 45 | #Set a setScore function, and then return it 46 | def setScore(self) : 47 | self.score = 0 48 | print(self.score) 49 | #Set a Dictionary for faceCards 50 | faceCardsDict = {"A":11,"J":10,"Q":10,"K":10, 51 | "2":2,"3":3,"4":4,"5":5,"6":6, 52 | "7":7,"8":8,"9":9,"10":10} 53 | #Set a variable for aceCounter 54 | aceCounter = 0 55 | #Convert card into score 56 | for card in self.hand: 57 | self.score += faceCardsDict[card] 58 | if card == "A": 59 | aceCounter +=1 60 | if self.score > 21 and aceCounter !=0: 61 | self.score -= 10 62 | aceCounter -= 1 63 | return self.score 64 | 65 | #Set a variable for player1, and then print it 66 | player1 = Player(["3","7","5"]) 67 | print(player1) 68 | -------------------------------------------------------------------------------- /final project/Blackjack-Part-C.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Blackjack, Part C Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | #Import shuffle function from random library 9 | from random import shuffle 10 | 11 | # Create a functions 12 | def createDeck(): 13 | Deck = [] 14 | #Set a variable for faceValues 15 | faceValues = ['A', 'J', 'Q', 'K'] 16 | for i in range(4): #There are 4 different suites 17 | for card in range(2,11): #Adding numbers 2-10 18 | Deck.append(str(card)) 19 | 20 | for card in faceValues: 21 | Deck.append(card) 22 | shuffle(Deck) #Mixing results with shuffle 23 | return Deck #Return products 24 | 25 | #Set a variable to createDock function, and then print it 26 | cardDeck = createDeck() 27 | print(cardDeck) 28 | 29 | # Set a player class 30 | class Player: 31 | def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class 32 | self.hand = hand 33 | self.score = self.setScore() 34 | self.money = money 35 | 36 | def __str__(self): #__str__ will return a human readable string 37 | currentHand = " " #slef.hand = ["A","10"] 38 | 39 | for card in self.hand: 40 | currentHand += str(card) + " " 41 | 42 | #Set a variable for finalStatus, and then return it 43 | finalStatus = currentHand + "score " + str(self.score) 44 | return finalStatus 45 | 46 | #Set a setScore function to count score, and then return it 47 | def setScore(self) : 48 | self.score = 0 49 | #Set a Dictionary for faceCards 50 | faceCardsDict = {"A":11,"J":10,"Q":10,"K":10, 51 | "2":2,"3":3,"4":4,"5":5,"6":6, 52 | "7":7,"8":8,"9":9,"10":10} 53 | #Set a variable for aceCounter 54 | aceCounter = 0 55 | #Convert card into score 56 | for card in self.hand: 57 | self.score += faceCardsDict[card] 58 | if card == "A": 59 | aceCounter +=1 60 | if self.score > 21 and aceCounter != 0: 61 | self.score -= 10 62 | aceCounter -= 1 63 | 64 | return self.score 65 | 66 | #Set a hit function to select a card, and then return it 67 | def hit(self,card): 68 | self.hand.append(card) 69 | self.score = self.setScore() 70 | 71 | #Set a function to add new player 72 | def play(self,newHnad): 73 | self.hand = newHnad 74 | self.score = self.setScore() 75 | 76 | #Set a function to put out money 77 | def pay(self,amount): 78 | self.money -= amount #decrease money from balance 79 | 80 | #Set a function for winner 81 | def win(self,amount): 82 | self.money += amount # double amount for winner 83 | 84 | 85 | #Set a variable for player1, and then print it 86 | Player1 = Player(["3","7","5"]) 87 | print(Player1) 88 | Player1.hit("A") 89 | Player1.hit("A") 90 | print(Player1) #Score after selecting a card 91 | Player1.pay(20) 92 | print(Player1.money) #Balance after puting money 93 | Player1.win(40) 94 | print(Player1.money) #Balance after winning 95 | Player1.play(["A","K"]) 96 | print(Player1) #Score for new player 97 | print(Player1.money) #After restarting the game 98 | -------------------------------------------------------------------------------- /final project/Blackjack-Part-D.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Blackjack, Part D Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | #Import shuffle function from random library 9 | from random import shuffle 10 | 11 | # Create a functions 12 | def createDeck(): 13 | Deck = [] 14 | #Set a variable for faceValues 15 | faceValues = ['A', 'J', 'Q', 'K'] 16 | for i in range(4): #There are 4 different suites 17 | for card in range(2,11): #Adding numbers 2-10 18 | Deck.append(str(card)) 19 | 20 | for card in faceValues: 21 | Deck.append(card) 22 | shuffle(Deck) #Mixing results with shuffle 23 | return Deck #Return products 24 | 25 | #Set a variable to createDock function, and then print it 26 | cardDeck = createDeck() 27 | print(cardDeck) 28 | 29 | # Set a player class 30 | class Player: 31 | def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class 32 | self.hand = hand 33 | self.score = self.setScore() 34 | self.money = money 35 | self.bet = 0 36 | 37 | def __str__(self): #__str__ will return a human readable string 38 | currentHand = " " #slef.hand = ["A","10"] 39 | 40 | for card in self.hand: 41 | currentHand += str(card) + " " 42 | 43 | #Set a variable for finalStatus, and then return it 44 | finalStatus = currentHand + "score " + str(self.score) 45 | return finalStatus 46 | 47 | #Set a setScore function to count score, and then return it 48 | def setScore(self) : 49 | self.score = 0 50 | #Set a Dictionary for faceCards 51 | faceCardsDict = {"A":11,"J":10,"Q":10,"K":10, 52 | "2":2,"3":3,"4":4,"5":5,"6":6, 53 | "7":7,"8":8,"9":9,"10":10} 54 | #Set a variable for aceCounter 55 | aceCounter = 0 56 | #Convert card into score 57 | for card in self.hand: 58 | self.score += faceCardsDict[card] 59 | if card == "A": 60 | aceCounter +=1 61 | if self.score > 21 and aceCounter != 0: 62 | self.score -= 10 63 | aceCounter -= 1 64 | 65 | return self.score 66 | 67 | #Set a hit function to select a card, and then return it 68 | def hit(self,card): 69 | self.hand.append(card) 70 | self.score = self.setScore() 71 | 72 | #Set a function to add new player 73 | def play(self,newHnad): 74 | self.hand = newHnad 75 | self.score = self.setScore() 76 | 77 | #Set a function to put out money 78 | def betMoney(self,amount): 79 | self.money -= amount #decrease money from balance 80 | self.bet += amount # 81 | 82 | #Set a function for winner 83 | def win(self,result): 84 | if result == True: 85 | if self.score == 21 and len(self.hand) == 2: # Set required score for winning blackjack 86 | self.money += 2.5*self.bet # if player win with a blackjack 87 | else: 88 | self.money += 2*self.bet # if player win without a blackjack 89 | 90 | self.bet = 0 # Reset the bet 91 | else: 92 | self.bet = 0 # If player loose a bet 93 | 94 | #Set a variable for player1, and then print it 95 | Player1 = Player(["3","7","5"]) 96 | print(Player1) 97 | Player1.hit("A") 98 | Player1.hit("A") 99 | print(Player1) #Score after selecting a card 100 | Player1.betMoney(20) 101 | print(Player1.money,Player1.bet) #Balance after puting money and bet amount 102 | Player1.win(True) 103 | print(Player1.money,Player1.bet) #Balance after winning without a blackjack 104 | Player1.play(["A","K"]) 105 | print(Player1) #Score for new player 106 | Player1.betMoney(20) 107 | Player1.win(True) 108 | print(Player1.money,Player1.bet) #Balance after winning with a blackjack 109 | -------------------------------------------------------------------------------- /final project/Blackjack-Part-E.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Blackjack, Part E Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | #! /usr/bin/env python3 8 | # -*- coding: utf-8 -*- 9 | 10 | from random import shuffle #import shuffle function from random module 11 | 12 | def createDeck(): #define a function to Create the Deck 13 | Deck = [] #create Deck as a List 14 | 15 | faceValues = ["A", "J", "Q", "K" ] #define faceValues with a list 16 | for i in range(4): #add values 4 times via a for loop so there are 4 different suits 17 | 18 | for card in range(2,11): #loop through values between 2 to 10 not including 11. tese numbers represent cards 19 | Deck.append(str(card)) #add cards to Deck. converting Integers to Strins for more convinience 20 | for card in faceValues: #loop through faceValues list 21 | Deck.append(card) #add faceValues to Deck 22 | 23 | shuffle(Deck) #suffle the Deck 24 | return Deck #return the Deck 25 | 26 | class Player: #here we will be creating Player class 27 | 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 28 | self.hand = hand #define hand attribute for the class player 29 | 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 30 | self.money = money #define money attribute for the class player 31 | self.bet = 0 #add a new attribute to Player called bet. 32 | 33 | def __str__(self): #overriding the __str__ function. it is used to print hand and score of the player 34 | CurrentHand = "" #define a temporary variable to hold the current cards of the player 35 | for card in self.hand: #loop through the player 'hand' and add each card to CurrentHand 36 | CurrentHand += str(card) + " " #it is more convinient to add cards as strings to CurrentHand. so use str(card) 37 | 38 | finalStaus = CurrentHand + "score: " + str(self.score) #finalStaus will be in the format "A 10 score:21" "A 10 2 score:23" 39 | return finalStaus #return finalStatus. which is printed by this function. 40 | 41 | def setScore(self): #define setScore method for player class 42 | self.score = 0 #it is good practice to initialize the variable. 43 | faceCardsDict = {"A":11, "J":10, "Q":10, "K":10, #create a Dictionary and map each card a value 44 | "2":2, "3":3, "4":4, "5":5, "6":6, 45 | "7":7, "8":8, "9":9, "10":10} 46 | aceCounter = 0 #You need to count the number of Aces. here counter is initialized. 47 | for card in self.hand: #loop throught the hand of the player and add value of each card to players score 48 | self.score += faceCardsDict[card] 49 | if card == "A": #if the card is a Ace, 50 | aceCounter +=1 #then increment the aceCounter 51 | if self.score > 21 and aceCounter != 0: #if the acore is above 21 and player has a Ace 52 | self.score -= 10 #new Ace value will be 1. hence score will be reduced by 10 53 | aceCounter -= 1 #as one Ace is consumed, reduce 1 from aceCounter 54 | 55 | return self.score #return the score of the player 56 | 57 | def hit(self, card): #hit function is used to ada a card to hand 58 | self.hand.append(card) #new card will be append to the Player's hand 59 | self.score = self.setScore() #player score will be recalculated 60 | 61 | 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 62 | self.hand = newHand #new hand will be assigned to Player's hand 63 | self.score = self.setScore() #recalculate the Player's score 64 | 65 | def betMoney(self,amount): #change pay function to betMoney 66 | self.money -= amount #reduce bet amount from player's money 67 | self.bet += amount #add bet amount to Player's bet amount 68 | 69 | def win(self, result): #change win function. now it takes boolean argument. 70 | if result == True: #if win funtion recieve true 71 | if self.score == 21 and len(self.hand) == 2: #if Blackjack is earned 72 | self.money += 2.5 * self.bet #2.5 times of bet amount will be added to Player's money. 73 | else: #if win but not a Blackjack 74 | self.money += 2 * self.bet #two times of bet amount will be added to Players money 75 | self.bet = 0 #we should erase bet amount after that 76 | else: 77 | self.bet = 0 #if player is lost we only have to do erase bet amount. so it won't effect future play 78 | 79 | def printHouse(House): #this method will print all cards of House except first card 80 | for card in range(len(House.hand)): #loop through the hand of House 81 | if card == 0: #if it is the first card 82 | print("X", end=" ") #just print 'X'. continue printing in same line with space gap 83 | elif card == len(House.hand) - 1: #if the card is the last one in the hand 84 | print(House.hand[card]) #just print it. no need of space 85 | else: #else 86 | print(House.hand[card], end=" ") #just print the card and keep a gap of space 87 | 88 | cardDeck = createDeck() #what is returned from the createDeck() function will be assigned to 'cardDeck' 89 | print(cardDeck) #print the cardDeck 90 | firstHand = [cardDeck.pop(),cardDeck.pop()] #add last two cards to firstHand, 91 | secondHand = [cardDeck.pop(),cardDeck.pop()] #add next last two cards to secondHand 92 | Player1 = Player(firstHand) #Player1 recieve firstHand 93 | House = Player(secondHand) #House recieve secondHand 94 | print(Player1) #Print hand and score of Player1 95 | printHouse(House) #Print hand and score of House 96 | 97 | while(Player1.score < 21): #this loop will continue as long as Player1 score is less than 21 98 | action = input("Do you want another card?(y/n)") #ask from user whether he needs another card. recieve user input 99 | if action == "y": #if he press 'y' 100 | Player1.hit(cardDeck.pop()) #Player1 recieve a new card 101 | print(Player1) #Print hand and score of Player1 102 | printHouse(House) #Print hand and score of House 103 | else: 104 | break #if user press 'n', exit the loop 105 | -------------------------------------------------------------------------------- /final project/Blackjack-Part-F.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Blackjack, Part F Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | from __future__ import print_function 9 | #Import shuffle function from random library 10 | from random import shuffle 11 | 12 | # Set a createDeck function 13 | def createDeck(): 14 | Deck = [] 15 | 16 | #Set a variable for faceValues 17 | faceValues = ['A', 'J', 'Q', 'K'] 18 | for i in range(4): # There are 4 different suites 19 | for card in range(2,11): # Adding numbers 2-10 20 | Deck.append(str(card)) 21 | 22 | for card in faceValues: 23 | Deck.append(card) 24 | 25 | shuffle(Deck) # Mixing results with shuffle 26 | return Deck # Return products 27 | 28 | # Set a player class 29 | class Player: 30 | def __init__(self,hand = [],money = 100): #__init__ is the constructor for a class 31 | self.hand = hand 32 | self.score = self.setScore() 33 | self.money = money 34 | self.bet = 0 35 | 36 | def __str__(self): #__str__ will return a human readable string 37 | currentHand = " " 38 | 39 | for card in self.hand: 40 | currentHand += str(card) + " " 41 | 42 | #Set a variable for finalStatus, and then return it 43 | finalStatus = currentHand + "score " + str(self.score) 44 | return finalStatus 45 | 46 | #Set a setScore function to count score, and then return it 47 | def setScore(self) : 48 | self.score = 0 49 | #Set a Dictionary for faceCards 50 | faceCardsDict = {"A":11,"J":10,"Q":10,"K":10, 51 | "2":2,"3":3,"4":4,"5":5,"6":6, 52 | "7":7,"8":8,"9":9,"10":10} 53 | #Set a variable for aceCounter 54 | aceCounter = 0 55 | #Convert card into score 56 | for card in self.hand: 57 | self.score += faceCardsDict[card] 58 | if card == "A": 59 | aceCounter +=1 60 | if self.score > 21 and aceCounter != 0: 61 | self.score -= 10 62 | aceCounter -= 1 63 | 64 | return self.score 65 | 66 | #Set a hit function to select a card, and then return it 67 | def hit(self,card): 68 | self.hand.append(card) 69 | self.score = self.setScore() 70 | 71 | #Set a function to add new player 72 | def play(self,newHand): 73 | self.hand = newHand 74 | self.score = self.setScore() 75 | 76 | #Set a function to put out money 77 | def betMoney(self,amount): 78 | self.money -= amount # Decrease money from balance 79 | self.bet += amount 80 | 81 | #Set a function for winner 82 | def win(self,result): 83 | if result == True: 84 | if self.score == 21 and len(self.hand) == 2: # Set required score for winning blackjack 85 | self.money += 2.5*self.bet # if player win with a blackjack 86 | else: 87 | self.money += 2*self.bet # if player win without a blackjack 88 | 89 | self.bet = 0 # Reset the bet 90 | else: 91 | self.bet = 0 # If player loose a bet 92 | 93 | #Set a function to check the result win or draw 94 | def draw(self): 95 | self.money += self.bet 96 | self.bet = 0 97 | 98 | #Set a function to check blackjack 99 | def hasBlackjack(self): 100 | if self.score == 21 and len(self.hand) == 2: 101 | return True 102 | else: 103 | return False 104 | 105 | 106 | # Set a printHouse function to print the house and score 107 | def printHouse(House): 108 | for card in range(len(House.hand)): 109 | if card == 0: 110 | print("X",end = " ") 111 | elif card == len(House.hand) -1: 112 | print(House.hand[card]) 113 | else: 114 | print(House.hand[card], end = " ") 115 | 116 | #Set a variable to createDock function, and then print it 117 | cardDeck = createDeck() 118 | 119 | # Pop function select the last shuffle number 120 | 121 | # Set a variable for First players last shuffle number 122 | firstHand =[cardDeck.pop(),cardDeck.pop()] 123 | 124 | # Set a variable for Second players last shuffle number 125 | secondHand = [cardDeck.pop(),cardDeck.pop()] 126 | 127 | # Set a variable to First player score, and then print it 128 | Player1 = Player(firstHand) 129 | 130 | # Set a variable to Second player score, and then print it 131 | House = Player(secondHand) 132 | 133 | cardDeck = createDeck() 134 | 135 | while(True): 136 | if len(cardDeck) <20: 137 | cardDeck = createDeck() 138 | firstHand = [cardDeck.pop(),cardDeck.pop()] 139 | secondHand = [cardDeck.pop(),cardDeck.pop()] 140 | Player1.play(firstHand) 141 | House.play(secondHand) 142 | 143 | # Set a variable to ask player for bet amount 144 | Bet = int(input("Please enter your bet: ")) 145 | 146 | print(cardDeck) 147 | Player1.betMoney(Bet) 148 | printHouse(House) 149 | print(Player1) 150 | 151 | #Define results on Blackjack win 152 | if Player1.hasBlackjack(): 153 | if House.hasBlackjack(): 154 | Player1.draw() 155 | else: 156 | Player1.win(True) 157 | else: 158 | # if players score is below 21, ask him to add more card 159 | while(Player1.score < 21):# While (true==true) 160 | action = input("Do you want another card?(y/n): ") 161 | if action == "y": 162 | Player1.hit(cardDeck.pop()) 163 | print(Player1) 164 | printHouse(House) 165 | else: 166 | break 167 | # Define how long player can add card 168 | while(House.score < 16): 169 | print(House) 170 | House.hit(cardDeck.pop()) 171 | 172 | if Player1.score > 21: 173 | if House.score > 21: 174 | Player1.draw() 175 | else: 176 | Player1.win(False) 177 | 178 | elif Player1.score > House.score: 179 | Player1.win(True) 180 | 181 | elif Player1.score == House.score: 182 | Player1.draw() 183 | 184 | else: 185 | if House.score > 21: 186 | Player1.win(True) 187 | else: 188 | Player1.win(False) 189 | 190 | print(Player1.money) 191 | print(House) 192 | -------------------------------------------------------------------------------- /functions/main.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Functions Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | # Assignment on Functions 8 | ''' 9 | Syntax for a function: 10 | 11 | def FunctionName(Input): 12 | Action 13 | return Output 14 | ''' 15 | # define a function using a keyword def 16 | ''' 17 | function name: addOne 18 | input: Number 19 | output: Output 20 | ''' 21 | #The function addOne takes a Number as input and then adds 1 and then returns it 22 | def addOne(Number): 23 | Output = Number + 1 #add 1 to a Number 24 | return Output #return output 25 | 26 | Var = 0 #intialize to 0 27 | print(Var) #print value 28 | ''' 29 | an argument is passed through a function. 30 | ''' 31 | Var2 = addOne(Var) #calling a function addOne and is assigned to a variable 32 | Var3 = addOne(Var2) #calling a function addOne and is assigned to a variable 33 | Var4 = addOne(2) #a value is directly passed through a function and the output is 34 | #assigned to a variable 35 | #print Var2, Var3 and Var4 36 | print(Var2) 37 | print(Var3) 38 | print(Var4) 39 | 40 | Var4 = addOne(2.1) #float value is passed into a function 41 | print(Var4) #print the value 42 | Var4 = addOne(2.1+3.4) #two float numbers are added and passed into a function 43 | print(Var4) #print the value 44 | 45 | ''' 46 | function addOneAddTwo takes two variable as an input and then returns a variable. 47 | ''' 48 | def addOneAddTwo(NumberOne, NumberTwo): 49 | Output = NumberOne + 1 #add 1 to a variable NumberOne 50 | # Output = Output + NumberTwo + 2 51 | Output += NumberTwo + 2 #add 2, NumberTwo variable and Output 52 | return Output #return Output variable 53 | 54 | Sum = addOneAddTwo(1, 2) #call the function addOneTwo and pass two arguments directly 55 | print(Sum) #print output 56 | Sum = addOneAddTwo(Var2, Var3) #call the function addOneTwo and pass two variable arguments 57 | print(Sum) #print output 58 | -------------------------------------------------------------------------------- /importing/Alternative-Import-Methods.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Alternative Import Methods Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | # Importing the library 'random' as 'r' where 'r' is its nickname 8 | ## from random import * 9 | import random as r 10 | 11 | # import the function from the library 12 | ## from random import randInt 13 | 14 | # Assign a random integer value to the variable 'randInt' 15 | ## random.seed(1) 16 | randInt = r.randint(0,10) #start<=N<=end 17 | print(randInt) 18 | 19 | # Assign a random float value to the variable 'randFloat' between 0 and 1 only 20 | randFloat = r.random() #0.0<=N<1.0 21 | print(randFloat) 22 | 23 | # Assign a random float value to the variable 'randFloat' between any specified range 24 | randUniform = r.uniform(1,1100) #start<=N<=end 25 | print(randUniform) 26 | 27 | # Create a list 'simpleList' and print a random integer from that list 28 | simpleList = [1,3,5,7,11] 29 | pickElement = r.choice(simpleList) 30 | print(pickElement) 31 | print(simpleList) 32 | 33 | # shuffle the list using 'shuffle' function of 'random' library 34 | r.shuffle(simpleList) 35 | print(simpleList) 36 | -------------------------------------------------------------------------------- /importing/Guessing-Game-Part-A.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Guessing Game, Part A Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | # import the fuction 'randint' from library random 8 | from random import randint 9 | 10 | ## randint(a,b) -> a<=N<=b 11 | 12 | # set the variable 'randVal' with a random value between 0 to 100 13 | randVal = randint(0,100) 14 | 15 | 16 | while(True): 17 | guess = int(input('Please enter your guess:')) 18 | # check if 'guess' and 'randVal' are equal 19 | if guess == randVal: 20 | # get out of the loop if they are equal 21 | break 22 | # check if 'guess' is less than 'randVal' 23 | elif guess < randVal: 24 | print('Your guess was too low') 25 | # check if 'guess' is more than 'randVal' 26 | else: 27 | print('Too high') 28 | 29 | # print the correct answer 30 | print('You guessed correctly with:',guess) 31 | -------------------------------------------------------------------------------- /importing/Guessing-Game-Part-B.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Guessing Game, Part B Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | # import 'random' fuction of 'random' library 8 | from random import random 9 | 10 | # import 'clock' function of 'time' library 11 | from time import clock 12 | 13 | # Set the value of variable 'randVal' as a random number 14 | randVal = random() # 0.0 <=N <1.0 15 | ## print(randVal) 16 | ## time.clock() -> timevalue 17 | ## time.clock() -> timevalue2 18 | 19 | # Set the values of upper and lower as 1.0 and 0.0 respectively 20 | upper = 1.0 21 | lower = 0.0 22 | ## guess = 0.5 -> Too Low -> lower = 0.5 23 | ## guess = 0.9 -> Too High -> upper = 0.9 24 | ## guess = 0.5 25 | 26 | # Set the variable 'startTime' as the currect processor time 27 | startTime = clock() 28 | while(True): 29 | # set the variable 'guess' as the avarage of 'upper' and 'lower' 30 | guess = (upper+lower)/2 31 | # check if 'guess' and 'randVal' are equal 32 | if guess == randVal: 33 | # get out of the loop if they are equal 34 | break 35 | # check if 'guess' is less than 'randVal' 36 | elif guess "21" 36 | # Age = 21 37 | 38 | # Another method is to convert the Age later 39 | Age = input("Please enter your age: ") # Age here will be an integer 40 | # The following instruction becames valid for now 41 | print(int(Age)+1) # This will temporary convert Age string to integer 42 | 43 | 44 | # Create an empty list 45 | Scores = [] 46 | # Ask the user for 5 different scores using a loop 47 | 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[) 48 | # currentScore = int(input("Please enter the score: ")) 49 | # Or we can also print which score to put: but accept only integers 50 | # currentScore = int(input("Please enter the score " + str(i+1) + ": ")) # Add 1 because i will start by 0 51 | # We can also convert it to float so also decimals could be taken into account 52 | currentScore = float(input("Please enter the score " + str(i+1) + ": ")) 53 | # Append the score to our list (at the end) using the predefined function : append 54 | Scores.append(currentScore) 55 | # Print the score entered by the user, we use comma to format our variable to string automatically 56 | # print("The score you entered was: ",currentScore) 57 | # We can put something else afterwards 58 | # print("The score you entered was: ",currentScore, "nice") 59 | # We can use "\n" to put our score in a new line: "\" is used to mention a special caracter 60 | # print("The score you entered was:\n",currentScore) 61 | # To convert our score to an integer 62 | print("The score you entered was: \n"+str(currentScore)) 63 | 64 | # print is actually a function that takes those inputs separated by "," and prints them 65 | # def FunctionName(input1,input2): 66 | # Action 67 | 68 | 69 | # What happens inside our loop ? (Below an example for integers) 70 | # Scores = [] 71 | # Scores = [70] # First loop i = 0 72 | # Scores = [70, 12] # First loop i = 1 73 | # Scores = [70, 12, 45] # First loop i = 2 74 | # Scores = [70, 12, 45, 56] # First loop i = 3 75 | # Scores = [70, 12, 45, 56, 99] # First loop i = 4 76 | 77 | # Print the list Scores 78 | print(Scores) 79 | -------------------------------------------------------------------------------- /input and output/Participant-Data-Part-A.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Participant Data, Part A Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | # Create the number of participants that are allowed to register 9 | ParticipantNumber = 2 10 | ParticipantData = [] # For now an empty list to store Participant Data 11 | 12 | # Create a counter for the registered participants 13 | registeredParticipants = 0 14 | 15 | # This is the file where we are going to write our data 16 | outputFile = open("PaticipantData.txt","w") 17 | 18 | # Loop over the participants 19 | while(registeredParticipants < ParticipantNumber): 20 | # Add a temporary data holder as a list 21 | tempPartData = [] # name, country of origin, age 22 | # Ask for user input to add his name 23 | name = input("Please enter your name: ") 24 | # Append the name to the temporary data 25 | tempPartData.append(name) 26 | country = input("Please enter your country of origin: ") 27 | # Append the country to the temporary data 28 | tempPartData.append(country) 29 | # Ask for user input to add his age 30 | age = int(input("Please enter your age: ")) # Convert the input to integer 31 | # Append the age to the temporary data 32 | tempPartData.append(age) 33 | # Print the tempData 34 | print (tempPartData) 35 | # Save our temporary data to the ParticipantData 36 | ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]] 37 | print(ParticipantData) 38 | # Increase the registeredParticipants number 39 | registeredParticipants +=1 # = registeredParticipants + 1 40 | 41 | # Write everything to a file 42 | # Each participant is represented by a list 43 | for participant in ParticipantData: 44 | # loop over particpant data 45 | for data in participant: 46 | outputFile.write(str(data)) # Convert data to string and write it to the file 47 | # We need to add extra formatting otherwise we will have it similar to MaxU.s.21 48 | outputFile.write(" ") # MaxU.s.21 49 | # Add each participant data in a new line 50 | outputFile.write("\n") 51 | 52 | 53 | outputFile.close() 54 | -------------------------------------------------------------------------------- /input and output/Participant-Data-Part-B.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Participant Data, Part B Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | # Create the number of participants that are allowed to register 9 | ParticipantNumber = 5 10 | ParticipantData = [] # For now an empty list to store Participant Data 11 | 12 | # Create a counter for the registered participants 13 | registeredParticipants = 0 14 | 15 | # This is the file where we are going to write our data 16 | outputFile = open("PaticipantData.txt","w") 17 | 18 | # Loop over the participants 19 | while(registeredParticipants < ParticipantNumber): 20 | # Add a temporary data holder as a list 21 | tempPartData = [] # name, country of origin, age 22 | # Ask for user input to add his name 23 | name = input("Please enter your name: ") 24 | # Append the name to the temporary data 25 | tempPartData.append(name) 26 | country = input("Please enter your country of origin: ") 27 | # Append the country to the temporary data 28 | tempPartData.append(country) 29 | # Ask for user input to add his age 30 | age = int(input("Please enter your age: ")) # Convert the input to integer 31 | # Append the age to the temporary data 32 | tempPartData.append(age) 33 | # Print the tempData 34 | print (tempPartData) 35 | # Save our temporary data to the ParticipantData 36 | ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]] 37 | print(ParticipantData) 38 | # Increase the registeredParticipants number 39 | registeredParticipants +=1 # = registeredParticipants + 1 40 | 41 | # Write everything to a file 42 | # Each participant is represented by a list 43 | for participant in ParticipantData: 44 | # loop over particpant data 45 | for data in participant: 46 | outputFile.write(str(data)) # Convert data to string and write it to the file 47 | # We need to add extra formatting otherwise we will have it similar to MaxU.s.21 48 | outputFile.write(" ") # MaxU.s.21 49 | # Add each participant data in a new line 50 | outputFile.write("\n") 51 | 52 | # Always remember to close your file 53 | outputFile.close() 54 | 55 | # Reading all this data from the file 56 | inputFile = open("PaticipantData.txt","r") 57 | # Store all the file data into an inputList 58 | inputList = [] 59 | # Read through the file line by line using a for loop 60 | for line in inputFile: 61 | # We need to read back from the file all participant data 62 | tempParticipant = line.strip("\n").split() 63 | # This is equivalent to the following 64 | # "Max U.S. 21 \n".strip("\n") -> "Max U.S. 21 " // Takes out the \n 65 | # "Max U.S. 21 ".split() -> ["Max","U.S.","21"] // Split the string and puts it's part into a list 66 | print(tempParticipant) 67 | # Let's append the data to the inputList 68 | inputList.append(tempParticipant) 69 | print(inputList) 70 | 71 | # let's save the data into a dictionnary 72 | Age = {} 73 | # loop over the list to get each participant's age 74 | for part in inputList: 75 | # Use a temporary variable 76 | tempAge = int(part[-1]) # ie: int('21') -> 21 77 | # We can access the last element using this method 78 | # Only add the Age to the dictionnary if it doesn't exist already 79 | if tempAge in Age: 80 | Age[tempAge] += 1 # means there is one more person with the same age 81 | else: 82 | Age[tempAge] = 1 # Otherwise, put it inside the dictionnary and give it value 1 83 | 84 | print(Age) # ie: {25: 2, 22: 1, 21: 1, 26: 1} 85 | 86 | # Always remember to close your file 87 | outputFile.close() 88 | -------------------------------------------------------------------------------- /input and output/Participant-Data-Part-C.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Participant Data, Part C Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | # Create the number of participants that are allowed to register 9 | ParticipantNumber = 5 10 | ParticipantData = [] # For now an empty list to store Participant Data 11 | 12 | # Create a counter for the registered participants 13 | registeredParticipants = 0 14 | 15 | # This is the file where we are going to write our data 16 | outputFile = open("PaticipantData.txt","w") 17 | 18 | # Loop over the participants 19 | while(registeredParticipants < ParticipantNumber): 20 | # Add a temporary data holder as a list 21 | tempPartData = [] # name, country of origin, age 22 | # Ask for user input to add his name 23 | name = input("Please enter your name: ") 24 | # Append the name to the temporary data 25 | tempPartData.append(name) 26 | country = input("Please enter your country of origin: ") 27 | # Append the country to the temporary data 28 | tempPartData.append(country) 29 | # Ask for user input to add his age 30 | age = int(input("Please enter your age: ")) # Convert the input to integer 31 | # Append the age to the temporary data 32 | tempPartData.append(age) 33 | # Print the tempData 34 | print (tempPartData) 35 | # Save our temporary data to the ParticipantData 36 | ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]] 37 | print(ParticipantData) 38 | # Increase the registeredParticipants number 39 | registeredParticipants +=1 # = registeredParticipants + 1 40 | 41 | # Write everything to a file 42 | # Each participant is represented by a list 43 | for participant in ParticipantData: 44 | # loop over particpant data 45 | for data in participant: 46 | outputFile.write(str(data)) # Convert data to string and write it to the file 47 | # We need to add extra formatting otherwise we will have it similar to MaxU.s.21 48 | outputFile.write(" ") # MaxU.s.21 49 | # Add each participant data in a new line 50 | outputFile.write("\n") 51 | 52 | # Always remember to close your file 53 | outputFile.close() 54 | 55 | # Reading all this data from the file 56 | inputFile = open("PaticipantData.txt","r") 57 | # Store all the file data into an inputList 58 | inputList = [] 59 | # Read through the file line by line using a for loop 60 | for line in inputFile: 61 | # We need to read back from the file all participant data 62 | tempParticipant = line.strip("\n").split() 63 | # This is equivalent to the following 64 | # "Max U.S. 21 \n".strip("\n") -> "Max U.S. 21 " // Takes out the \n 65 | # "Max U.S. 21 ".split() -> ["Max","U.S.","21"] // Split the string and puts it's part into a list 66 | print(tempParticipant) 67 | # Let's append the data to the inputList 68 | inputList.append(tempParticipant) 69 | print(inputList) 70 | 71 | # let's save the data into a dictionnary 72 | Age = {} 73 | # loop over the list to get each participant's age 74 | for part in inputList: 75 | # Use a temporary variable 76 | tempAge = int(part[-1]) # ie: int('21') -> 21 77 | # We can access the last element using this method 78 | # Only add the Age to the dictionnary if it doesn't exist already 79 | if tempAge in Age: 80 | Age[tempAge] += 1 # means there is one more person with the same age 81 | else: 82 | Age[tempAge] = 1 # Otherwise, put it inside the dictionnary and give it value 1 83 | 84 | print(Age) # ie: {25: 2, 22: 1, 21: 1, 26: 1} 85 | 86 | 87 | # We can also get other participant's data like country int(part[1]) or name int(part[0]) 88 | Countries = {} 89 | # loop over the list to get each participant's country 90 | for part in inputList: 91 | # Use a temporary variable 92 | tempCountry = part[1] # No need to convert : it's already a string 93 | # We can access the last element using this method 94 | # Only add the Age to the dictionnary if it doesn't exist already 95 | if tempCountry in Countries: 96 | Countries[tempCountry] += 1 # means there is one more person with the same age 97 | else: 98 | Countries[tempCountry] = 1 # Otherwise, put it inside the dictionnary and give it value 1 99 | 100 | print("Countries that attended:",Countries) 101 | 102 | # Find the oldest age 103 | Oldest = 0 # Let's assume this is the minimum value our age can have 104 | Youngest = 100 # Let's assume this is the maximum value our age can have 105 | mostOccuringAge = 0 # To save the most occurant age 106 | counter = 0 107 | 108 | # Loop over the Age dictionnary 109 | for tempAge in Age: 110 | # In the first time Oldest = first tempAge since the previous value was 0 111 | # In each loop: if we have found a new bigger value, we will assign it to variable Oldest 112 | if tempAge > Oldest: 113 | Oldest = tempAge 114 | # Otherwise, Oldest will not change and we'll assign it to the Youngest 115 | if tempAge < Youngest: 116 | Youngest = tempAge 117 | # Access the value of each key in dictionary, counter will get the value for most occuring age 118 | if Age[tempAge] >= counter: 119 | counter = Age[tempAge] 120 | # Get the dictionnary key equivalent to mostOccurongAge 121 | mostOccuringAge = tempAge 122 | 123 | # Print the Oldest Age 124 | print(Oldest) 125 | print(Youngest) 126 | print("Most occuring age is:",mostOccuringAge,"with",counter,"participants") 127 | 128 | # Always remember to close your file 129 | inputFile.close() 130 | -------------------------------------------------------------------------------- /input and output/Participant-Data-Part-D.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Participant Data, Part D Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | # Create the number of participants that are allowed to register 9 | ParticipantNumber = 5 10 | ParticipantData = [] # For now an empty list to store Participant Data 11 | 12 | # Create a counter for the registered participants 13 | registeredParticipants = 0 14 | 15 | """ 16 | # This is the file where we are going to write our data 17 | outputFile = open("PaticipantData.txt","w") 18 | 19 | # Loop over the participants 20 | while(registeredParticipants < ParticipantNumber): 21 | # Add a temporary data holder as a list 22 | tempPartData = [] # name, country of origin, age 23 | # Ask for user input to add his name 24 | name = input("Please enter your name: ") 25 | # Append the name to the temporary data 26 | tempPartData.append(name) 27 | country = input("Please enter your country of origin: ") 28 | # Append the country to the temporary data 29 | tempPartData.append(country) 30 | # Ask for user input to add his age 31 | age = int(input("Please enter your age: ")) # Convert the input to integer 32 | # Append the age to the temporary data 33 | tempPartData.append(age) 34 | # Print the tempData 35 | print (tempPartData) 36 | # Save our temporary data to the ParticipantData 37 | ParticipantData.append(tempPartData) # [tempPartData] = [[name,country,age]] 38 | print(ParticipantData) 39 | # Increase the registeredParticipants number 40 | registeredParticipants +=1 # = registeredParticipants + 1 41 | 42 | # Write everything to a file 43 | # Each participant is represented by a list 44 | for participant in ParticipantData: 45 | # loop over particpant data 46 | for data in participant: 47 | outputFile.write(str(data)) # Convert data to string and write it to the file 48 | # We need to add extra formatting otherwise we will have it similar to MaxU.s.21 49 | outputFile.write(" ") # MaxU.s.21 50 | # Add each participant data in a new line 51 | outputFile.write("\n") 52 | 53 | # Always remember to close your file 54 | outputFile.close() 55 | """ 56 | 57 | 58 | # Reading all this data from the file 59 | inputFile = open("PaticipantData.txt","r") 60 | # Store all the file data into an inputList 61 | inputList = [] 62 | # Read through the file line by line using a for loop 63 | for line in inputFile: 64 | # We need to read back from the file all participant data 65 | tempParticipant = line.strip("\n").split() 66 | # This is equivalent to the following 67 | # "Max U.S. 21 \n".strip("\n") -> "Max U.S. 21 " // Takes out the \n 68 | # "Max U.S. 21 ".split() -> ["Max","U.S.","21"] // Split the string and puts it's part into a list 69 | print(tempParticipant) 70 | # Let's append the data to the inputList 71 | inputList.append(tempParticipant) 72 | print(inputList) 73 | 74 | # let's save the data into a dictionnary 75 | Age = {} 76 | # loop over the list to get each participant's age 77 | for part in inputList: 78 | # Use a temporary variable 79 | tempAge = int(part[-1]) # ie: int('21') -> 21 80 | # We can access the last element using this method 81 | # Only add the Age to the dictionnary if it doesn't exist already 82 | if tempAge in Age: 83 | Age[tempAge] += 1 # means there is one more person with the same age 84 | else: 85 | Age[tempAge] = 1 # Otherwise, put it inside the dictionnary and give it value 1 86 | 87 | print(Age) # ie: {25: 2, 22: 1, 21: 1, 26: 1} 88 | # Find the oldest age 89 | Oldest = 0 # Let's assume this is the minimum value our age can have 90 | # Loop over the Age dictionnary 91 | for tempAge in Age: 92 | # In the first time Oldest = first tempAge since the previous value was 0 93 | # In each loop: if we have found a new bigger value, we will assign it to variable Oldest 94 | if tempAge > Oldest: 95 | Oldest = tempAge 96 | # Otherwise, Oldest will not change 97 | 98 | # Print the Oldest Age 99 | 100 | # Always remember to close your file 101 | inputFile.close() 102 | -------------------------------------------------------------------------------- /input and output/Tic-Tac-Toe-Part-A.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Tic Tac Toe, Part A Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | """ 8 | # The game should be similar to 9 | # | | 0 10 | #----- 1 11 | # | | 2 12 | #----- 3 13 | # | | 4 14 | """ 15 | 16 | #!python3 17 | 18 | # Define a function 19 | def drawField(): 20 | for row in range(5): #0,1,2,3,4 21 | # if row is even row write " | | " 22 | if row%2 == 0: 23 | # print writing lines 24 | for column in range(5): # will take values 0,1,2,3,4 25 | # if column is even, we will print a space 26 | if column%2 == 0: 27 | if column != 4: 28 | print(" ",end="") # Continue in the same line 29 | else: 30 | print(" ") # Jump to the next line 31 | else: 32 | print("|",end="") 33 | else: 34 | print("-----") 35 | 36 | """ 37 | # We need to do the following 38 | 1. Apply and Save the move 39 | 2. Check which player turn is "X" or "O" 40 | """ 41 | 42 | # Create a variable for the Players 43 | Player = 1 44 | # Create a list with each element corresponds to a column 45 | # currentField = [element1, element2, element3] 46 | # Let's simulate our playing field 47 | # In the first time, each list that correpond to a column will contains 3 empty spaces for the rows 48 | currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # A list that contains 3 lists 49 | 50 | 51 | # Create an infinite loop for the gamez 52 | while(True): # True == True / is always true (We can also use while(1)) 53 | # Display the player's turn 54 | print("Players turn: ",Player) 55 | # Ask user for input: to specify the desired row and column 56 | MoveRow = int(input("Please enter the row\n")) # Convert the row to integer 57 | MoveColumn = int(input("Please enter the column\n")) # Convert the column to integer 58 | if Player == 1: 59 | # Make move for player 1 60 | # Access our current field 61 | currentField[MoveColumn][MoveRow] = "X" 62 | # Once Player 1 make his move we change the Player to 2 63 | Player = 2 64 | else: 65 | # Make move for player 2 66 | currentField[MoveColumn][MoveRow] = "O" 67 | Player = 1 68 | # At the end, print the current field 69 | print(currentField) 70 | -------------------------------------------------------------------------------- /input and output/Tic-Tac-Toe-Part-B.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Tic Tac Toe, Part B Lecture 3 | ## 4 | 5 | # _*_ coding: utf-8 _*_ 6 | 7 | 8 | """ 9 | # The game should be similar to 10 | # | | 0 11 | #----- 1 12 | # | | 2 13 | #----- 3 14 | # | | 4 15 | """ 16 | 17 | #!python3 18 | 19 | # Define the function drawField that will print the game field 20 | # We will try to put our current field into the draw field 21 | 22 | def drawField(field): 23 | for row in range(5): #0,1,2,3,4 24 | #0,.,1,.,2 25 | # if row is even row write " | | " 26 | if row%2 == 0: 27 | practicalRow = int(row/2) 28 | # print writing lines 29 | # In this case , we have to adapt our field (3*3) to the actual drawing (5*5) 30 | # We can divde by 2 to get the correct maping 31 | for column in range(5): # will take values 0 (in drawing) -> 0 (in actual field), 1->., 2->1, 3->., 4->2 32 | # if column is even, we will print a space 33 | # The even columns gives us the move of each player 34 | if column%2 == 0: # Values 0,2,4 35 | # The actual column that should be used in our field 36 | # Make sure our values are integers 37 | practicalColumn = int(column/2) # Values 0,1,2 38 | if column != 4: 39 | # Print the specific field 40 | print(field[practicalColumn][practicalRow],end="") # Continue in the same line 41 | else: 42 | print(field[practicalColumn][practicalRow]) # Jump to the next line 43 | else: 44 | # The odd value just give us vertical lines 45 | print("|",end="") 46 | else: 47 | print("-----") 48 | 49 | """ 50 | # We need to do the following 51 | 1. Apply and Save the move 52 | 2. Check which player turn is "X" or "O" 53 | """ 54 | 55 | # Create a variable for the Players 56 | Player = 1 57 | # Create a list with each element corresponds to a column 58 | # currentField = [element1, element2, element3] 59 | # Let's simulate our playing field 60 | # In the first time, each list that correpond to a column will contains 3 empty spaces for the rows 61 | currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # A list that contains 3 lists 62 | 63 | # We will draw the current field 64 | drawField(currentField) 65 | 66 | # Create an infinite loop for the gamez 67 | while(True): # True == True / is always true (We can also use while(1)) 68 | # Display the player's turn 69 | print("Players turn: ",Player) 70 | # Ask user for input: to specify the desired row and column 71 | MoveRow = int(input("Please enter the row\n")) # Convert the row to integer 72 | MoveColumn = int(input("Please enter the column\n")) # Convert the column to integer 73 | if Player == 1: 74 | # Make move for player 1 75 | # Access our current field 76 | # We only want to make one move when that specific field is empty 77 | if currentField[MoveColumn][MoveRow] == " ": 78 | currentField[MoveColumn][MoveRow] = "X" 79 | # Once Player 1 make his move we change the Player to 2 80 | Player = 2 81 | else: 82 | # Make move for player 2 83 | if currentField[MoveColumn][MoveRow] == " ": 84 | currentField[MoveColumn][MoveRow] = "O" 85 | Player = 1 86 | 87 | # At the end, draw the current field representation 88 | drawField(currentField) 89 | -------------------------------------------------------------------------------- /lists/main.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Lists Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | TestList = ["element1", "element2", "element3"] #TestList is a list with three elements 9 | #Scores is a list with different data types 10 | Scores = [70, 85, 67.5, 90, 80] 11 | print(Scores) #print Scores list 12 | ''' 13 | elements of a list can be accessed with a index inside a square bracket 14 | Accessing list elements. The first element of a list starts from 0 15 | ''' 16 | print(Scores[0]) #prints 1st element of a list 17 | print(Scores[1]) #prints 2nd element of a list 18 | print(Scores[2]) #prints 3rd element of a list 19 | print(Scores[3]) #prints 4th element of a list 20 | print(Scores[4]) #prints 5th element of a list 21 | ''' 22 | Accessing list in a reverse order 23 | ''' 24 | print(Scores[-1]) #prints last element of a list 25 | print(Scores[-2]) #prints 2nd last element of a list 26 | print(Scores[-3]) #prints 3rd last element of a list 27 | print(Scores[-4]) #prints 4th last element of a list 28 | print(Scores[-5]) #prints 5th last element of a list 29 | ''' 30 | Accessing multiple elements from a list. 31 | It can be done using List[first : last] 32 | ''' 33 | print(Scores[0:2]) #access elements from index 0 to index 1 34 | print(Scores[0:3]) #access elements from index 0 to index 2 35 | print(Scores[1:3]) #access elements from index 1 to index 2 36 | print(Scores[2:]) #access all elements from index 2 to end 37 | print(Scores[1:]) #access all elements from index 1 to end 38 | 39 | ''' 40 | Values of a list can be changed 41 | ''' 42 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 43 | print(Scores) #print a list named Scores 44 | Scores[0] = 75 #assign a value of 75 to the first element of a list Scores 45 | print(Scores) #print the Scores 46 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 47 | Scores[0] = 6.0 #assign a float value 6.0 to the first element of a list 48 | print(Scores) #print Scores 49 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 50 | print(Scores) #print Scores 51 | Scores[0] = "Hello" #assign a string 'Hello' to the first element of a list 52 | print(Scores) #print Scores 53 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 54 | print(Scores) #print Scores 55 | Scores[1:3] = [] #remove elements 2nd to 3rd from the list 56 | print(Scores) #print Scores 57 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 58 | print(Scores) #print Scores 59 | Scores[2:3] = [] #remove 3rd element from the list. 60 | print(Scores) #print Scores list 61 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 62 | print(Scores) #print Scores list 63 | Scores[2] = [] #assign an empty list to element 3rd (index 2nd) 64 | print(Scores) #print Scores 65 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 66 | print(Scores) #print Scores 67 | Scores[2] = ["Hello", "World"] #assign a list to 3rd element (index 2nd) 68 | print(Scores) #print Scores 69 | print(Scores[2]) #accessing the 3rd element 70 | ''' 71 | Accessing list within a list 72 | ''' 73 | print(Scores[2][0]) #access the list within a list 74 | print(Scores[2][1]) 75 | Scores = [70, 85, 67.5, 90, 80] #initialize list with values 76 | print(Scores) #print Scores 77 | Scores.append(82) #appending value at the end of list 78 | print(Scores) #print Scores 79 | -------------------------------------------------------------------------------- /loops/Breaking-and-Continuing-in-Loops.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Breaking and Continuing in Loops Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | Participants = ["Jen", "Alex", "Tina", "Joe", "Ben"] #create a list of 5 elements. 9 | 10 | position = 0 #set position is equal to 0 11 | for name in Participants: #loop over each element of list 12 | if name == "Tina": #check if the element of list matches to "Tina" 13 | break #come outside of loop if the condition is met 14 | position = position + 1 #increment variable position by 1 15 | 16 | print(position) #print the value of position 17 | 18 | position = 0 #set position is equal to 0 19 | for name in Participants: #loop over each element of list 20 | if name == "Tina": #check if the element of list matches to "Tina" 21 | print("About to break") #print message 22 | break #come outside of loop if the condition is met 23 | print("About to increment") #print message 24 | position = position + 1 #increment variable position by 1 25 | 26 | print(position) #print the value of position 27 | 28 | ''' 29 | finds the index of matched string from the list 30 | ''' 31 | Index = 0 #set Index to 0 32 | for currentIndex in range(len(Participants)): #loop over all elements in list 33 | print(currentIndex) #print value of currentIndex 34 | if Participants[currentIndex] == "Joe": #check if list element is equal to Joe 35 | print("Have Breaked") #print message 36 | break #come out of the loop 37 | print("Not Breaked") #print message 38 | print(currentIndex+1) #print currentIndex of matched element 39 | 40 | for number in range(10): #loop from range of 0 to 10 41 | if number%3 == 0: #check remainder is 0 if divided by 3 42 | print(number) #print value of a number 43 | print("Divisible by 3") #print message 44 | continue #continue 45 | print(number) #print value of number 46 | print("Not Divisible by 3") #print message 47 | -------------------------------------------------------------------------------- /loops/Introduction-to-Loops.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Introduction to Loops Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | 9 | Word = "Hello" #initialize a variable Word with string "Hello" 10 | Letters = [] #create an empty list 11 | ''' 12 | loop through each character of a string, print each character. Check if the character 13 | in a string matches e, print a string and then append it into List 14 | ''' 15 | for w in Word: #loop over each character 16 | print(w) #print a character 17 | if w == "e": #check if a character matches 'e' 18 | print("What a funny letter") 19 | Letters.append(w) #Append each character into List. 20 | print(Letters) #print the list 21 | ''' 22 | Loop through each character stored in list Letters and then print each character 23 | ''' 24 | for l in Letters: #Print each character in the list named Letters 25 | print(l) 26 | 27 | ''' 28 | Create a list of 5 elements. Loop through each element in the list and print it. 29 | ''' 30 | Numbers = [1, 2, 3, 4, 5] #creating a list named Numbers with 5 integer elements 31 | for l in Numbers: #loop over each element in list using for loop 32 | print(l) #print each element 33 | 34 | ''' 35 | print all the numbers which has a remainder of zero when divisible by 2. 36 | ''' 37 | for l in Numbers: #loop over all elements in the list 38 | if l%2 == 0: #check if remainder is 0 when divided by 2 39 | print(l) #print the number 40 | ''' 41 | print all the numbers which has a remainder of one when divisible by 2. 42 | ''' 43 | for l in Numbers: #loop over all elements in the list 44 | if l%2 == 1: #check if remainder is 1 when divided by 2 45 | print(l) #print the number 46 | 47 | Numbers = [] #create an empty list 48 | for num in range(10): #loop over elements from 0 to 9 49 | Numbers.append(num) #append each number to List 50 | print(num) #print each number 51 | print(Numbers) #print the list. 52 | 53 | ''' 54 | Above process is repeated with value changed to 100. It prints all numbers from 0 to 99 and are appended 55 | in list Numbers. 56 | ''' 57 | Numbers = [] #create an empty list 58 | for num in range(100): #loop over elements from 0 to 9 59 | Numbers.append(num) #append each number to List 60 | print(num) #print each number 61 | print(Numbers) #print the list 62 | 63 | ''' 64 | range is a function which takes an integer as an input. 65 | range(1, 10, 2): 1 is the start, 10 is end and 2 is the step size 66 | ''' 67 | Numbers = [] #create an empty list 68 | for num in range(1, 10, 2): #loop over an elements from 1 to 10 with difference of 2 69 | Numbers.append(num) #append each number to List 70 | print(num) #print each number 71 | print(Numbers) #print the list 72 | 73 | Numbers = [] #create an empty list 74 | for num in range(-1, -12, -2): #loop over an elements from -1 to -12 with difference of -2 75 | Numbers.append(num) #append each number to List 76 | print(num) #print each number 77 | print(Numbers) #print list 78 | 79 | ''' 80 | Above example is repeated with a range now changed from -1 to -13 at a difference of 3. 81 | ''' 82 | Numbers = [] 83 | for num in range(-1, -13, 3): 84 | Numbers.append(num) 85 | print(num) 86 | print(Numbers) 87 | -------------------------------------------------------------------------------- /loops/Making-Shapes-With-Loops.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Making Shapes With Loops Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | Length = 10 #set a variable name Length = 10 8 | ''' 9 | On each loop character c is printed n number of times which is defined by pos. 10 | "c"*2 means character c is repeated twice 11 | ''' 12 | for pos in range(1, 10): #loop from 1 to 9 13 | print("c"*pos) #print character c 14 | 15 | Length = 10 #set a variable name Length = 10 16 | ToPrint = "a" #a variable name ToPrint is assigned a character "a" 17 | for pos in range(1, Length + 1): #loop from 1 to value of Length + 1 18 | print(ToPrint*pos) #print character n number of times 19 | 20 | ''' 21 | Loop in a decreasing order from 10 to 0 and print a character n times on each decreasing loop 22 | ''' 23 | for pos in range(Length, 0, -1): 24 | print(ToPrint*pos) 25 | ''' 26 | Loop in a increasing order from 1 to 12 and print a character n times on each increasing loop 27 | ''' 28 | Length = 12 29 | ToPrint = "1" #a variable name ToPrint is assigned a character "1" 30 | for pos in range(1, Length + 1): 31 | print(ToPrint*pos) 32 | ''' 33 | Loop in a decreasing order from 12 to 0 and print a character "1" n times on each decreasing loop 34 | ''' 35 | for pos in range(Length, 0, -1): 36 | print(ToPrint*pos) 37 | -------------------------------------------------------------------------------- /loops/Nested-Loops.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Nested Loops Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | # | | 9 | #----- 10 | # | | 11 | #----- 12 | # | | 13 | ''' 14 | for loop 15 | ''' 16 | for row in range(5): #loop 5 times 17 | if row%2 == 0: #if remainder is equal to zero when divided by 2 18 | print(" | | ") #print message 19 | else: #if above condition is false 20 | print("-----") #print message 21 | 22 | ''' 23 | | | 24 | ----- 25 | | | 26 | ----- 27 | | | 28 | printing the above shapes 29 | ''' 30 | for row in range(5): #loop 5 times 31 | if row%2 == 0: #if remainder is equal to zero when divided by 2 32 | for column in range(1, 6): #created a nested loop of range from 1 to 6 33 | if column%2 == 1: #check if remainder is 1 when divided by 2 34 | if column != 5: #if variable column not equal to 5 35 | print(" ", end = "") #print space and in the same line 36 | else: 37 | print(" ") #print in next line 38 | else: 39 | print("|", end = "") #print a pipe in same line 40 | 41 | else: 42 | print("-----") #print dash 43 | -------------------------------------------------------------------------------- /loops/While-Loops.py: -------------------------------------------------------------------------------- 1 | ## 2 | # While Loops Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | ''' 8 | While Loops 9 | Syntax: 10 | while condition: 11 | Action1 12 | Action2 13 | ACtion3 14 | ''' 15 | counter = 1 #set counter variable equal to 1 16 | ''' 17 | The while loop runs until the condition is True, updates the counter, prints the counter. 18 | It comes out of the loop if the condition fails. 19 | ''' 20 | while (counter <= 10): #checks condition 21 | print(counter) #print value of counter 22 | counter = counter + 1 #increments counter by 1 23 | 24 | counter = 1 #sets counter variable equal to 1 25 | Sum = 0 #initialize sum to 0 26 | while (counter <= 10): #checks condition 27 | print(counter) #print value of counter 28 | Sum = Sum + counter #add sum and counter value 29 | counter = counter + 1 #increments counter by 1 30 | print(Sum) #print the value of sum 31 | 32 | ''' 33 | print the sum of values from 1 to 100 34 | ''' 35 | counter = 1 #set counter equal to 1 36 | Sum = 0 #intialize sum to 0 37 | while (counter <= 100): #check the value of counter until it is less than or equal to 100 38 | print(counter) #print the value of counter 39 | Sum = Sum + counter #add the sum and counter 40 | counter = counter + 1 #increment counter by 1 41 | print(Sum) #print Sum 42 | 43 | KeepTrack = 1 44 | Sum = 0 45 | while (KeepTrack <= 100): 46 | print(KeepTrack) 47 | Sum = Sum + KeepTrack 48 | KeepTrack = KeepTrack + 1 49 | print(Sum) 50 | 51 | Letters = ["a", "b", "c", "d", "e"] #initialize a list with 5 character elements 52 | Index = 0 #set index equal to 0 53 | while (Index < len(Letters)): #Compare variable Index with length of list 54 | print(Index) #print value of Index 55 | print(Letters[Index]) #print each element in a List 56 | Index = Index + 1 #Increment value of Index by 1. 57 | 58 | ''' 59 | Starts from Index 4. Since the length of list is equal to 5. the loop runs only once 60 | and prints the last element only. 61 | ''' 62 | Index = 4 #set index equal to 4 63 | while (Index < len(Letters)): #Compare variable Index with length of list 64 | print(Index) #print value of Index 65 | print(Letters[Index]) #print each element in a List 66 | Index = Index + 1 #Increment value of Index by 1. 67 | 68 | 69 | ''' 70 | The code below does not print anything since the loop starts from 5 and condition does not meet. 71 | ''' 72 | Index = 5 73 | while (Index < len(Letters)): 74 | print(Index) 75 | print(Letters[Index]) 76 | Index = Index + 1 77 | 78 | height = 5000 #set variable height equal to 5000. 79 | velocity = 50 #set variable velocity equal to 50 80 | time = 0 #set variable time equal to 0 81 | while (height > 0): #check if variable height > 0 82 | height = height - velocity #decrement height with velocity and assign the value to height. 83 | time = time + 1 #increment time by value 1 84 | 85 | print(height) #print value of height 86 | print(time) #print value of time 87 | -------------------------------------------------------------------------------- /variables/main.py: -------------------------------------------------------------------------------- 1 | ## 2 | # Variables Lecture 3 | ## 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | 8 | # 'one' is the name of the variable 9 | # '=' is called the assignment operator we use to store values in a variable 10 | # '1' is the actual value stored inside the variable 'one' 11 | one = 1 12 | 13 | # 'two' is the name of the variable 14 | # '=' is called the assignment operator we use to store values in a variable 15 | # '2' is the actual value stored inside the variable 'two' 16 | two = 2 17 | 18 | # 'three' is the name of the variable 19 | # '=' is called the assignment operator we use to store values in a variable 20 | # '3' is the actual value stored inside the variable 'three' 21 | three = 3 22 | 23 | # 'print()' is a function we use in python to print some value or content on the screen 24 | # name of the variable can be passed inside the print function to display its value on screen 25 | print(one) 26 | print(two) 27 | print(three) 28 | print(two) 29 | print(one) 30 | # The above code will print the following 31 | # Notice how the same variable is being used again for printing 32 | """ 33 | 1 34 | 2 35 | 3 36 | 2 37 | 1 38 | """ 39 | 40 | 41 | 42 | print(one) 43 | print(two) 44 | print(three) 45 | # the value of a variable can be overwritten again by using the assignment operator '=' to store a new unique value 46 | two = 4 47 | print(two) 48 | print(one) 49 | # The above code will print the following 50 | # Notice the value of variable 'two' is reassigned to '4' in the output 51 | """ 52 | 1 53 | 2 54 | 3 55 | 4 56 | 1 57 | """ 58 | 59 | # apart from storing integer values , decimal values can also be stored inside a variable 60 | # notice how the decimal value '1.1' is stored inside a variable called 'decimal' 61 | decimal = 1.1 62 | # The above code will print the following 63 | """ 64 | 1.1 65 | """ 66 | 67 | 68 | # text values also called strings can be stored inside a variable 69 | # notice how the value 'Hello' is stored inside a variable 'StringVar' 70 | StringVar = "Hello" 71 | # The above code will print the following 72 | """ 73 | Hello 74 | """ 75 | 76 | # will produce and error with the following message 77 | """ 78 | StringVar = "Hello" + 1 79 | TypeError: must be str, not int 80 | """ 81 | # uncomment this code execute the script to see error 82 | #StringVar = "Hello" + 1 83 | # this happens because variables cant be of two types of 'int' denotes to integer and 'str' denotes to string 84 | 85 | 86 | StringVar = "Hello" + "1" 87 | # The above code will print the following 88 | # The above code works beause now both 1 and hello are strings 89 | """ 90 | Hello1 91 | """ 92 | 93 | # The def keyword is used to begin fuction declaration and then the name of function is wriiten 94 | def FunctionName(): 95 | # Declaring local variable 96 | newVar="World" 97 | # Printing local variable 98 | print(newVar) 99 | # Used to indicate global variable is used 100 | global one 101 | # Printing global one variable 102 | print(one) 103 | # Returing a value , also used for ending a function 104 | return 105 | 106 | # The function being called by using its name along with () 107 | FunctionName() 108 | # Printing a local variable 109 | print(newVar) 110 | # The following error is produced with due to the fact that 'newVar is a local variable' 111 | """ 112 | NameError: name 'newVar' is not defined 113 | """ 114 | 115 | # Shorthand way of declaration variables 116 | one , two , three = 1,2,3 117 | print(one) 118 | print(two) 119 | print(three) 120 | # The above code will print the following 121 | """ 122 | 1 123 | 2 124 | 3 125 | """ 126 | 127 | # Declaraing a variable and storing the value 5 into it 128 | Five = 3+2 129 | print(Five) 130 | # The above code will print the following 131 | """ 132 | 5 133 | """ 134 | 135 | # Will produce error because we cant add two variables with one value on the right of assignment operator 136 | Five + Six = 3+2 137 | 138 | # This will produce an error as well 139 | # left = what you're giving the value to 140 | # right = what the value is 141 | 5 = Five 142 | # Trying to print the value of variable 'Five' 143 | print(Five) 144 | 145 | # Declared a variable 'count' and stored the value 0 to it 146 | count = 0 147 | # Printing count value 148 | print(count) 149 | # Output 150 | """ 151 | 0 152 | """ 153 | 154 | # Reassign the value of count to 1 155 | count = 1 156 | # Printing count value 157 | print(count) 158 | # Output 159 | """ 160 | 1 161 | """ 162 | 163 | 164 | # This will also increase the count value by adding 1 to the previous value of count 165 | count = count + 1 166 | # Printing count value 167 | print(count) 168 | # Output 169 | """ 170 | 2 171 | """ 172 | # This will also increase the count value by adding 1 to the previous value of count 173 | count = count + 1 174 | # Printing count value 175 | print(count) 176 | # Output 177 | """ 178 | 3 179 | """ 180 | 181 | # This will also increase the count value by adding 1 to the previous value of count 182 | # Short hand notation of the same line as 'count=count+1' 183 | count+=1 184 | # Printing count value 185 | print(count) 186 | # Output 187 | """ 188 | 4 189 | """ 190 | 191 | # Assign 0 value to variable count 192 | count = 0 193 | # Print the value 194 | print(count) 195 | # Incrementing count value 196 | count = count + 1 197 | # Print the value 198 | print(count) 199 | # Multiply the value of count by 3 200 | count*=3 201 | # Print the value 202 | print(count) 203 | # Output 204 | """ 205 | 0 206 | 1 207 | 3 208 | """ 209 | 210 | # Assign 0 value to variable count 211 | count = 0 212 | # Print the value 213 | print(count) 214 | # Incrementing count value 215 | count = count + 1 216 | # Print the value 217 | print(count) 218 | # Multiply the value of count by 3 219 | count/=3 220 | # Print the value 221 | print(count) 222 | # Output 223 | """ 224 | 0 225 | 1 226 | 0.333333333333 227 | """ 228 | --------------------------------------------------------------------------------