Wang Haihua
🚅 🚋😜 🚑 🚔
print "Hello World!"
File "<ipython-input-1-8afc9091282f>", line 1 print "Hello World!" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello World!")?
Bugs are usually caused by human mistakes. They don't necessarily have to end up in an error.
#bug example.
num1 = input("Enter the first integer: ")
num2 = input("Enter the second integer: ")
print(num1, "+", num2, "=", num1 + num2)
Enter the first integer: 8 Enter the second integer: 7 8 + 7 = 87
#bug example.
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
print(num1, "+", num2, "=", num1 + num2)
Enter the first integer: hey
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-19915655c439> in <module> 1 #bug example. 2 ----> 3 num1 = int(input("Enter the first integer: ")) 4 num2 = int(input("Enter the second integer: ")) 5 ValueError: invalid literal for int() with base 10: 'hey'
#exception example, ValueError.
num3 = int(input("First integer: "))
num4 = int(input("Second integer: "))
print(num3, "/",num4, "=", num3/num4)
First integer: 6 Second integer: 7.4
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-6-2ca720ac0e5e> in <module> 2 3 num3 = int(input("First integer: ")) ----> 4 num4 = int(input("Second integer: ")) 5 6 print(num3, "/",num4, "=", num3/num4) ValueError: invalid literal for int() with base 10: '7.4'
int(3.8)
3
# ZeroDivisionError.
num3 = int(input("First integer: "))
num4 = int(input("Second integer: "))
print(num3, "/",num4, "=", num3/num4)
First integer: 7 Second integer: 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-11-c273cdf866df> in <module> 5 num4 = int(input("Second integer: ")) 6 ----> 7 print(num3, "/",num4, "=", num3/num4) ZeroDivisionError: division by zero
try:
the situations where we can get exceptions
except "Exception Name":
the operations in case of exceptions
x = "Alan Turing"
int(x)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-417db27f4b47> in <module> 1 x = "Alan Turing" 2 ----> 3 int(x) ValueError: invalid literal for int() with base 10: 'Alan Turing'
try:
int(x)
except ValueError:
print("Please enter an integer value!!!")
Please enter an integer value!!!
num3 = input("First integer: ")
num4 = input("Second integer: ")
try:
num3_int = int(num3)
num4_int = int(num4)
print(num3_int, "/",num4_int, "=", num3_int/num4_int)
except ValueError:
print("Please enter an integer value!!!")
First integer: 6 Second integer: 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-8-194a4a382dd0> in <module> 6 num4_int = int(num4) 7 ----> 8 print(num3_int, "/",num4_int, "=", num3_int/num4_int) 9 10 except ValueError: ZeroDivisionError: division by zero
num3 = input("First integer: ")
num4 = input("Second integer: ")
try:
num3_int = int(num3)
num4_int = int(num4)
print(num3_int, "/",num4_int, "=", num3_int/num4_int)
except ZeroDivisionError:
print("Please enter the second input different than 0 value!!!")
First integer: 6 Second integer: 2 6 / 2 = 3.0
num3 = input("First integer: ")
num4 = input("Second integer: ")
try:
num3_int = int(num3)
num4_int = int(num4)
print(num3_int, "/",num4_int, "=", num3_int/num4_int)
except ValueError:
print("Please enter an integer value!!!")
except ZeroDivisionError:
print("Please enter the second input different than 0 value!!!")
except:
print("Unknown error...")
First integer: 5 Second integer: 0 Please enter the second input different than 0 value!!!
3.4/0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-10-71f13771214b> in <module> ----> 1 3.4/0 ZeroDivisionError: float division by zero
num3 = input("First integer: ")
num4 = input("Second integer: ")
try:
num3_int = int(num3)
num4_int = int(num4)
print(num3_int, "/",num4_int, "=", num3_int/num4_int)
except (ValueError, ZeroDivisionError):
print("Error!!!")
First integer: 2.5 Second integer: 3 Error!!!
int("3.5")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-f6c874437bf0> in <module> ----> 1 int("3.5") ValueError: invalid literal for int() with base 10: '3.5'
#try/except/as
num3 = input("First integer: ")
num4 = input("Second integer: ")
try:
num3_int = int(num3)
num4_int = int(num4)
print(num3_int, "/",num4_int, "=", num3_int/num4_int)
except ValueError as error:
print("Error!!!")
print("Error message: ", error)
First integer: 5 Second integer: 5.2 Error!!! Error message: invalid literal for int() with base 10: '5.2'
#exception handling in loop structure
while True:
num1 = input("First number: (Press q for quit the program): ")
if num1 == "q":
break
num2 = input("Second number: ")
try:
num1_int = int(num1)
num2_int = int(num2)
print(num1_int, "/", num2_int, "=", num1_int / num2_int)
except (ValueError, ZeroDivisionError):
print("Error!")
print("Please try again!")
First number: (Press q for quit the program): 9 Second number: 9 9 / 9 = 1.0 First number: (Press q for quit the program): q
#try/except/as
num3 = input("First integer: ")
num4 = input("Second integer: ")
try:
num3_int = int(num3)
num4_int = int(num4)
print(num3_int, "/",num4_int, "=", num3_int/num4_int)
except (ValueError, ZeroDivisionError) as error:
print("Error!!!")
print("Error message: ", error)
First integer: 9 Second integer: 0 Error!!! Error message: division by zero
"""
exception handling in functions
using raise command
"""
def reverse(s):
if (type(s) != str):
raise ValueError("Please enter a String type.")
else:
return s[::-1]
reverse("python")
'nohtyp'
reverse(12)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-25-9be0aeb641b6> in <module> ----> 1 reverse(12) <ipython-input-21-fbb7f7fb3af7> in reverse(s) 7 def reverse(s): 8 if (type(s) != str): ----> 9 raise ValueError("Please enter a String type.") 10 else: 11 return s[::-1] ValueError: Please enter a String type.
Python is an object oriented programming language. And almost everything in Python is an object.
An object has properties an methods.
A Class is how we construct an object (like its blueprint)
class Car():
pass
def hello():
pass
class Car():
colour = "yellow"
brand = "xyz"
door = 4
model = 1987
car1 = Car()
print(car1)
<__main__.Car object at 0x00000239E2897A00>
print(car1.model)
print(car1.brand)
print(car1.door)
print(car1.colour)
1987 xyz 4 yellow
car2 = Car()
car2.colour = "blue"
print(car2.colour)
print(car1.colour)
blue yellow
#We can also call attributes over the class without creating an object.
Car.model
1987
Car.brand
'xyz'
dir(car1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'brand', 'colour', 'door', 'model']
All classes have a function called init ()
We use this function to assign values to object properties. For this, we use a special method: init ()
The init () method called automatically every time the class is used to create a new object.
By defining this method, we can create our objects with different values.
class Car2():
def __init__(self):
print("init function calling...")
self is a reference to the current instance to the class and is used to any variable or method that belongs to the class.
car = Car2()
init function calling...
class Car3():
def __init__(self, colour, brand, door):
self.colour = colour
self.brand = brand
self.door = door
red_car = Car3("red", "abc",2)
yellow_car = Car3("yellow", "xyz", 4)
print(red_car.colour)
print(yellow_car.brand)
red xyz
blue_car = Car3()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-36-2993678ac391> in <module> ----> 1 blue_car = Car3() TypeError: __init__() missing 3 required positional arguments: 'colour', 'brand', and 'door'
blue_car = Car3("blue","xyz")
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-37-6b3d9a135cf0> in <module> ----> 1 blue_car = Car3("blue","xyz") TypeError: __init__() missing 1 required positional argument: 'door'
blue_car = Car3("blue", "BMW", 4)
print(blue_car.brand)
print(blue_car.colour)
print(blue_car.door)
BMW blue 4
class Person():
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def welcomePerson(self):
print("Hello " + self.name)
def showAge(self):
print(self.age)
person1 = Person ("Asli", 28)
person1.welcomePerson()
Hello Asli
person1.showAge()
28
Inheritence is a way that allows us to define a class that inherits all the methods and properties from another class.
One will be the Parent Class
Another will be the Child Class
class Person:
def __init__(self, name, lname, nationality):
self.first_name = name
self.last_name = lname
self.nationality = nationality
def print_name(self):
print(self.first_name + " " + self.last_name)
def print_nationality():
print(self.name + " is " + self.natioanlity)
class Student(Person):
pass
student = Student("Rob", "Bain", "Dutch")
student.print_name()
Rob Bain
class Student(Person):
def __init__(self, school, year):
self.school = school
self.year = year
student = Student("Bogazici", 3)
student.first_name = "Ali"
student.last_name = "Cengiz"
student.print_name()
Ali Cengiz
class Student(Person):
def __init__(self, name, lname, nationality, school, year):
super().__init__(name, lname, nationality)
self.school = school
self.year = year
def print_student_status(self):
print(self.first_name + " is year " + str(self.year) + " at " + self.school)
new_student = Student("Mary", "Jenkins", "French", "Sorbonne", 2)
dir(new_student)
new_student.print_student_status()
Mary is year 2 at Sorbonne
Create a new Person class that takes a name and age in the contructor.
Define 3 functions:
class Person3():
def __init__(self, name, age):
self.name = name
self.age = age
self.language = []
def welcomePerson(self):
print("Hello",self.name)
def showAge(self):
print(self.age)
def addLanguage(self,new_lang):
print("Adding new language")
self.language.append(new_lang)
def showInfo(self):
print("{} is {} years old".format(self.name,self.age))
print("He can speak:")
for i in self.language:
print(i)
Ferhat = Person3("Ferhat",21)
Ferhat
<__main__.Person3 at 0x27972501548>
Ferhat.addLanguage("Spanish")
Adding new language
Ferhat.showAge()
21
Ferhat.showInfo()
Ferhat is 21 years old He can speak: Spanish
Ferhat.welcomePerson()
Hello Ferhat
Ferhat.addLanguage("Spanish")
Adding new language
Ferhat.showInfo()
Ferhat is 21 years old He can speak: Spanish Spanish
Ferhat.addLanguage("English")
Adding new language
Ferhat.showInfo()
Ferhat is 21 years old He can speak: Spanish Spanish English