Course Introduction to Python Programming Language
The python crash course is great for both beginners and experienced programmers who want to understand the Python programming language. As a note to experienced developers, we know that the problem with a new programming language is not about understanding the concept of computer programming, but rather understanding how to implement the common programming concepts, design patterns, common business logic as well as implementing common algorithmic problems that you are familiar with in your previous programming language using Python.
With that in mind, I will try as much as possible to adapt this course not to be too detailed about how you would do one thing versus the other. Rather, I will show you the pythonic way of software development and outline some of the common pitfalls and traps a new developer might fall in.
Absolute beginners can benefit from this course because it examines python from the ground up. To beginners, especially folks who self-studies, I have tried to make this course as easy as I can, so you can understand some of the key concepts in software development.
I also know that sometimes when you are studying software development on your own, you have no idea what materials to trust or how to connect the dots from vast information that you need to absorb. I fell prey to that kind of stuff. I spent a good amount of my time unlearning things from material where information was not accurate. With that said, I hope you enjoy this course much as I enjoy it while preparing.
General Python Syntax Consideration for Programmers Transitioning to Python
- Python uses indentation instead of curly brackets {} as in C-family languages
1
2
3
4
5
name = 'Lagu'
def sayMyName():
print(f"Hi {name}.")
sayMyName()
- Python does not have key words for declaring variable, you simple type the name of the variable, assign it to a value and that's it.
What is Python?
This question is already answered on this section of the website. Installation
To install Python, check out this section of the website Python Path
The default installation location of Python interpreter is usually on the path /usr/local/bin/python3.9
on unix system and on the windows system, it is'C:\\Python3.9\\python.exe'
Typing
In your terminal or cmd prompt prints out the respective path of python installation
How to run Python script
Using nodemon
To many people, this might seemed unorthodox method but trust me this stuff rocks! If want to see the results of the script on file save, this is the way to go. Unlike watchdog, this is install-and-play.
First you need to install a node package called nodemon
1
yarn global add nodemon
Then to run a python script using nodemon, run...
1
nodemon --exec python3 ./path/to/my-script.py
Using Python Package watchdog
Setting up this package is involved and beyond the scope of this course. There are a lots of resources on how to use watchdog to watch changes to the file system. For this reason, nodemon rocks, it is simply install-and-play.
Using the Python Interpreter
To invoke the Python interpreter, type in your terminal or cmd prompt python3
and you should see this output.
1
2
3
4
Python 3.8.5 (default, Jul 21 2020, 10:48:26)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> I
With this Python interpreter invoked, we can now start writing our python programs in the REPL...
1
2
3
4
5
6
7
>>> print("hello world")
hello world
>>> name = "lagu"
>>> age = 25
>>> print("My name is "+name+ " and I am "+str(age)+" years old")
My name is lagu and I am 25 years old
>>>
At any time to exit out of the Python interpreter, simply enter exit()
1
2
3
>>> print("My name is "+name+ " and I am "+str(age)+" years old")
My name is lagu and I am 25 years old
>>> exit()
Integrated Development Environment, IDEs and Text Editors for Python
We could use the python build-in REPL in the console and continue to write our programs all day long and there's nothing wrong with it except that it will eat up a lot of our time writing code this way.
You see, as developers, we solve complex real-world engineering problems which can take days, months, or even years, and therefore, writing our codes in the terminal will not only be inefficient but keeping track of the Python files we write would be a nightmare.
So now, what is the best way to write Python code? The answer, is we use special programs called Integrated Development Environment, IDEs, IDEs or some Special Text Editors.
These IDEs or Text editors have built-in special features to help make our lives easy as developers.
- They debug our codes, by showing us where the error happens and where we can correct them.
- Code syntax highlighting and therefore makes it easy to read our codes
Best IDEs and Text editors for Python Programmers
There are tens of these Code (Text) editors and IDEs out there for python. Here are a few of the most popular ones.
Microsoft Visual Studio Code
VS Codeis a light weight text code editor used by millions of developer every day, it is free and open sourced by Microsoft. To install vs code, follow this section of the website to get it setup. PyCharm
PyCharm is loved by python community of developers and comes in two edition, the enterprise, which is commercial and the community edition which is free to use. To install PyCharm, follow this section of the website. Jupyter Book or Jupyter Lab
This is a browser based text editor for Python, for sure this one rocks, it is one of my most favorite when prototyping Python application. To use Jupyter Notebook or Lab, you either use the online version, or simply download the anaconda package, install it and you should be good to go. To install Jupyter lab, follow this section of the website to get anaconda distribution package. Hello World! Writing your first Python program
This is what your first Python program would look like.
1
2
>>> print("hello world")
hello world
A single line comment in Python starts with the hash tag symbol (#), look at how it is used in this code snippet below.
1
2
# This is a single line java comment
print("Hello World!");
Unlike other programming languages like Java, Javascript, C or C++, there are no true multi-line comment in Python. Most developers would use the doc-strings to represent multi-line comment which starts with either single tripple quote,'''
and ends with '''
or the double tripple quotes"""
and ends with """
. Look at the code snippet below to see doc string in usage.
1
2
3
4
5
6
7
8
9
'''
A docstring is a string literal that can be as the
first statement to document a python module, function,
class, or method definition. The docstring becomes the
__doc__ special
attribute of that object created...
'''
print("Hello World!");
Python Reserved Keywords
Let's see how many reserved keywords are there in Python3. You should know these reserved keywords as you cannot use them to name any of the identifiers in Python for example, they cannot be used to name variables, function or classes hence the reserved keywords.
As of Python 3.9.5 (default, May 4 2021, 03:36:27)
, there are 36 keywords in Python, these list includes.
Printing out the list of Keywords in Python3
1
2
3
4
5
6
import keyword
python_keyword = keyword.kwlist
print(f"There {len(python_keyword)} in python
These include
{python_keyword}")
Python Variables
Variables are containers for storing data type values. In Python, these values can be of data types such as, strings - series of characters really or a character, numerical values such as float and integers or boolean values such as true or false
Declaring single variables in Python
Python has no key word command for declaring variables. As a dynamically typed language, a variable is created the minute it is assigned value(s) to it.
1
2
3
4
5
age = 5
name = "Lagu"
# Using the + operator, we can do a string concatenation
print("My name is "+ name + " and I am "+age +" year of age")
Declaring multiple variables in one line
You can also declare many variables in one line provided you separate them with a comma (,) like this.
1
2
age, name, country = 34, "lagu", "South Sudan"
print(f"My name is {name} and I am {age} years old, originally from {country}")
Global variable in Python
Any variable declared outside of function automatically becomes a global variable that can be used anywhere by any object calling it. The variable country
is a global variable in the code snippet below whereas age
is a local variable because it is declared inside themy_country
function.
1
2
3
4
5
6
7
country = "South Sudan" # global variable
def my_country():
age = 28 # local variable
print("I am from ", country, "I am ", age, "years old")
my_country()
The variable age
is scoped to the function my_country
and can't be called outside of it.
1
2
3
4
5
6
7
8
9
country = "South Sudan" # global variable
def my_country():
age = 25
print("I am from ", country, "I am ", age, "years old")
my_country()
print(age)
Using the global
keyword for variable
Consider the use of global variable, which runs as expected.
1
2
3
4
5
6
user_1 = "Lagu"
def get_user_name():
print("user is: " + user_1) # Ok
get_user_name()
Reassigning the global variable before it's usage errors out with UnboundLocalError
1
2
3
4
5
6
7
8
9
user_1 = "Lagu"
def get_user_name():
print("user is: " + user_1) # UnboundLocalError
user_1 = "John"
print("user is: " + user_1)
get_user_name()
Reassigning the global
variable before its usage errors out with UnboundLocalError.
1
2
3
4
5
6
7
8
9
10
11
user_1 = "Lagu"
def get_user_name():
global user_1
print("user is: " + user_1) # Ok
user_1 = "John"
print("user is: " + user_1)
get_user_name()
You can also use the global
keyword if you want to make local variable available in the global scope
1
2
3
4
5
6
7
8
9
10
def get_user_name():
global user_1
user_1 = "X-man"
print("user is inside: " + user_1) # Ok
get_user_name()
# still run even do user_1 is declared inside of get_user_name() function
print("user is outside: " + user_1) # Ok
Use the global
keyword to override the value of global variable inside a function. The preceding lines of code usinguser_1
assumes the new value of the variable.
1
2
3
4
5
6
7
8
9
10
11
12
user_1 = "Lagu"
print("user_1 before get_user_name(): " + user_1) # Ok
def get_user_name():
global user_1
user_1 = "X-man"
print("user_1 inside get_user_name(): " + user_1) # Ok
get_user_name()
print("user_1 after get_user_name(): " + user_1) # Ok
Rules for declaring variables in Python
- It must begin with a letter, you can't start a variable name with a numerical values
- Variable names can contain letters, digits, special characters such as underscores, and dollar signs
- You cannot use words thatPython Reserved Keywordssuch as
def
or boolean,True
true to name your variable - Convention dictates that variable name should start with a lowercase letter and it cannot contain whitespace
Concept of constant variable in Python
In python, there are no constant variable. A constant variable is that variable whose values cannot change. Unlike other programming languages such as JavaScript which uses the constto declare a constant, in python there are no such things.
Shallow, Deep Copy and Assignment Operator
Data Types in Python
Python data types fall into two main categories
Primitive data types
Data types that comes built-in to Python programming language and they include.
- Textual types str
- Boolean types bool
- Numerical types
- Integers int
- Floating point float
- Complex numbers complex
Non-primitive data types
These data types are programmer defined types, they are constructed from the primitive data types. Examples include
- Sequencing Types
- range
- list an orderd, changeable collection which allows duplicate members.
- tupleAn ordered unchangeable collection which also allows duplicate members.
- Mapping type (Hash map like data structure)
- dictA ordered collection which is changeable. No duplicate members. In Python version 3.7 an above dictionaries members are ordered while in Python 3.6 and below have dictionaries whose member are unordered.
- The Sets and Frozen sets
- setis a unique unordered, unchangeable, and unindexed collection. That is, sets do not allow duplicate members.
- frozensetis an immutable set, so its contents cannot be modified after it’s created.
- Binary Types
- memoryview
- bytesarray
- bytes
Using the type()
Constructor to get Data Type in Python
1
2
3
4
5
name = "lagu"
array1 = ["lagu", 3, 4.5]
print(type(name)) # <class 'str'>
print(type(array1)) # <class 'list'>
Type Casting in Python
Type casting is the conversion of one data type into another. In Python, type casting is done using the following constructors
1
2
age = 24.3
print(f"I am about {int(age)} years old.")
Methods and Properties associated Python Data Structure
To study all the methods and properties associated with a given data structure is beyond the scope of the course. If you would like to take an in depth look at individual methods and properties of a given data structure, I recommend the following approach. Checkout thissection of the websiteto get more on this particular topic.
Using type() to evaluate the types of given Python data types
Using dir() to evaluate the methods and properties of given Python data types
Using help() to get help associated methods and properties of given Python data types
Python Operators
Operators in Python are used to manipulate variables and can be divided into the following categories.
Python Operator falls into 7 categories
- Python Arithmetic Operator
- Python Relational Operator
- Python Assignment Operator
- Python Logical Operator
- Python Membership Operator
- Python Identity Operator
- Python Bitwise Operator
Python arithmetic operators
Python relational operators
>=
Greater than or equal to
a >= b
<=
Less than or equal to
a <= b
Python logical operators
&& (logical and)
|| (logical or)
! (logical not)
Python assignment operators
= (asign left side to right side value)
+= e.g y += x is equivalent to y = y + x etc...
Python ternary operator
This is a conditional operator. It can be handy as opposed to writing if statements.
Syntax: [expression_is_true] if [expression] else [expression_is_false]
1
2
3
4
5
6
7
8
9
10
11
12
a, b = 2, 5
# using if else
if a<b:
print("This is true")
else:
print("this is not true")
# Using Ternary operator
value = "this is true" if a<b else "this is not true"
print(value)
1
2
3
name = "lagus"
print("my name is", name) if name =="lagu" else print("you are not lagu")
# Output: you are not lagu
Python bitwise operator
In daily practice, unless otherwise you are working with image compression, encryption algorithms etc, you are most likely not to use the bitwise operators, for this reason, we will skit this in this crash course. However, if you need to learn more about it, check out the more on this website.
To get user input from the console application, we use the input()
method;
1
2
3
4
name = input("enter your name: ")
users = ["lagu", "alomija", "lebu", "leku", "konyio"]
print(f"Welcome {name.title()}!") if name.lower() in users else print(f"Hi {name.title()}, you are not authorised!")
Conditional Statements in Python
In order for the software we write to make decisions, there are few conditional statements used in Python to establish a bit of intelligence to programs we write. Python usesif statements almost exclusively or the however, it does not have built-inswitch statementsand ternary operators, ternary operator still uses if clause to fake it.
If Statements
if else
1
2
3
4
5
6
name = 'Maguma'
if name =="lagu":
print("Welcome ", name)
else:
print("You are not authorized", name)
if elif else
1
2
3
4
5
6
7
8
name = 'Manga'
if name =="lagu":
print("Welcome ", name, "as admin")
elif name =="Manga":
print(f"Hello {name}, what would you like to drink?")
else:
print("You are not authorized", name)
Python Switch Statements
There is no built-in switch statement in python as of the time of writing this course, but you can always create your own.
Iterations or Loops in Python
The fundamental primitive loops in python arewhile loop
andfor loop.
As note, python does not havedo while loop
While Loops
The while loop first checks the test condition before running the code block. If the test condition is true, the code block runs but it evaluates to falsy, then code block does not run.
1
2
3
4
5
6
# initialize a variable
i = 0;
while i < 7:
print(f"i is at: {i}")
# increment i, if code enters infinite loop
i+=1
It is also possible to represent while loop in one line
1
2
n = 7
while n>0: n -=1; print(n)
Looping Through Array using while loop in Python
1
2
3
4
5
6
7
8
9
ages = [1,2,3,4,5,6,7,8]
# initialize a variable
i = 0;
print("Listing all ages")
while i < len(ages):
print(f"age: {ages[i]}")
# increment i, if code enters infinite loop
i+=1
Using while True statement
The while True, creates an infinite loops, study the example below for it's usage.
1
2
3
4
5
6
7
i = 3
while True:
print(i)
i= i-1
if i==0:
break # terminate the loop using break statement
1
2
3
4
5
6
7
8
9
from time import sleep
count_endless = 0
while True:
print(f"The count now is: {count_endless}")
count_endless=count_endless+1
sleep(3) # wait for three seconds
if count_endless ==10:
break
The else clause in while Loop
1
2
3
4
5
# Syntax A
while 'expression':
"statement(s)"
else:
'else clause expression'
You might asking is this necessary? Why not just put the expressionelse clause expression after the loops?
1
2
3
4
# Syntax B
while 'expression':
"statement(s)"
'else clause expression'
In syntax A, the else clause expressionexpression executes only if the iteration completes successfully while in Syntax B, the else clause expression will always execute no matter what.
1
2
3
4
5
6
7
8
9
10
11
tribes = ["Kuku", "Madi", "Kakua", "Pojulu", "Mundari", "Zande"]
find_tribe = 'Lopit'
i = 0
while i<len(tribes):
if tribes[i]==find_tribe:
print(f"{find_tribe} found!")
break
i += 1
else:
print(f"{find_tribe} not found!")
1
2
3
4
5
6
7
8
9
10
11
tribes = ["Kuku", "Madi", "Kakua", "Pojulu", "Mundari", "Zande"]
find_tribe = 'Madi'
i = 0
while i<len(tribes):
if tribes[i]==find_tribe:
print(f"{find_tribe} found!")
break
i += 1
else:
print(f"{find_tribe} not found!")
For Loops
For loop is mostly used to loop through a given list. It is much simpler than while loop in this case
1
2
3
4
5
tribes = ["Kuku", "Madi", "Kakua", "Pojulu", "Mundari", "Zande"]
for tribe in tribes:
print(f" - {tribe}")
print("etc...")
For loop can also be used to loop through characters of a given word
1
2
3
4
tribe = "Madi"
# list the letter found in Madi tribe of South Sudan and Uganda
for letter in tribe:
print(letter)
Getting Index of List Element while using For Loop
The standard for loop does not give you index of the list you are looping through, to solve this problem, we can take couple approaches:
Enumerate function with For Loop
Use the enumerate(args)
function to get the index of the list being looped.
1
2
3
4
5
6
7
8
9
10
tribes = ["Kuku", "Madi", "Kakua", "Pojulu", "Mundari", "Zande"]
# Normal for loops
for tribe in tribes:
print(tribe)
# If you want to get index in for loops, use the enumerate function
for index, tribe in enumerate(tribes):
print(index, tribe)
1
2
3
4
string = "This is a string"
for i, letter in enumerate(string):
print(i, letter)
1
2
3
4
5
6
string = "This is a string"
# Get position of a given value in a collections
for i, letter in enumerate(string):
if letter =='s': print(f"letter s found in index(s) {i}, {letter}")
Iterator counter like those in while loop for For Loop
1
2
3
4
5
6
7
8
tribes = ["Kuku", "Madi", "Kakua", "Pojulu", "Mundari", "Zande"]
# getting index of list elements in python using for
i = 0
for tribe in tribes:
print(f"{i+1} - {tribe}")
i=i+1
Using break, continue and else control in for, while loops
You can introduce a counter variable just like you would in while loop to count. But if you find yourself this does, it should probably use the while loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
strings = "This is a string"
# continue
for s in strings:
if s=="s": continue
print(s, end='')
# break
for s in strings:
if s=="s": break
print(s, end='')
# else
for s in strings:
print(s, end='')
else:
print("
Hello else part")
Functions in Python
Declaring and calling function in Python
Functions in Python is declared using the def key word. To call the function you simply type the name of the function following parenthesis, see in code below call_my_name()
1
2
3
4
5
6
# declare a function
def call_my_name():
print("Hey Lagu...")
# call the function
call_my_name()
Function with Parameters and Arguments
Most often people confuse parameter and argument, but to set this straight, when you are declaring or defining a function, you pass parameter in the parenthesise.g name in the function below is a parameter , but when you are calling a function you pass argument in the parenthesise.g "Lagu" in the function call below is an argument.
1
2
3
4
5
6
# declare a function takes the name parameter
def call_my_name(name):
print("Hey ", name)
# call the function passing "Lagu" as an argument
call_my_name("Lagu")
You can define the function in one line
1
2
3
4
# function in oneline
def get_name(name): print(f"your name is {name}")
get_name("lagu")
Number of Arguments to function parameter
Normally, you can pass as many arguments as there parameters in the function definition
1
2
3
4
def getUserInfo(name, age, tribe):
print(f"{name} is {age} years old and here a {tribe} by tribe.")
getUserInfo("Lagu", 12, "Kuku")
If you call function getUserInfo("Lagu", 12)
it will throw a typeError for positional argument
TypeError: getUserInfo() missing 1 required positional argument: 'tribe'
Python Positional and Keyword Arguments
To a beginner the distinction between this two words: positional argument (args) and keyword argument (kwargs) can be difficult to grasp but I like to simplify them here.
Positional Argument (args)
Positional argument are those argument you pass to function call and defined by the position and order in which they are passed.
1
2
3
4
5
def positional_function(x, y, z, *args):
res = x + y + z
return res
positional_function(3, 5, 8)
x, y, z are required positional arguments, which means they must be passed during function call, calling
If you want to make them optional arguments, then add *args to it, note, it doesn't have to be called args, it can be called anything as long as it has the preceeding astericks(*)
Passed optional positional arguments results into a python tuple datatypes
Keyword Argument (kwargs)
If you instead give names to optional positional arguments, they are called key word arguments, it yields a python dictionary object.
1
2
3
4
5
def positional_function(x, y, z, **kwargs):
res = x + y + z
return res
positional_function(3, 5, 8)
Most of the times people create functions and pass both args and kwargs in so that users have the choice to any passed named keword arguments or positonal argments.
1
2
3
4
5
def positional_function(*args, **kwargs):
print(args)
print(kwargs)
positional_function(3, 5, 8, 7, name="Lagu", age=27)
Python Function Keyword Arguments, *args, and **kwargs
If you don't know the number of argument the function should expect at the time of function definition, pass in function *args or **kwargs
The *args results into a python tuple object.
1
2
3
4
def getUserInfo(*data):
print(data) # ('Lagu', 12, 'Kuku', 'south Sudan')
getUserInfo("Lagu", 12,"Kuku", "south Sudan")
1
2
3
4
5
6
7
8
def add(*args):
x = 0
print(args) # default *arg type is tuple
print(list(args)) # convert the type to list
for arg in args:
x += arg
return x
print(add(4, 5, 6, 7, 9))
The **kwargs results into python dictionary object
1
2
3
4
def getUserInfo(**data):
print(data) # {'name': 'Lagu', 'age': 12, 'tribe': 'Kuku'}
print(f'{data["name"]} is {data["age"]} years old and here a {data["tribe"]} by tribe.')
getUserInfo(name="Lagu", age=12, tribe="Kuku")
Python Lambda Function
Python lambda function is small, nameless (anonymous) function bound a single expression.Consider the function below.
1
2
3
4
def introduceUser(name, age, tribe):
print(f"{name} is {age} years old and here a {tribe} by tribe.")
introduceUser("Lagu", 12,"Kuku")
Using lambda, the function becomes...
1
2
introduceUser = lambda name, age :print(f"{name} is {age} years old")
introduceUser("lagu", 23)
Using lambda function for sorting
1
2
3
4
5
6
7
8
people = [
{'name':"lagu", "home":"st. paul"},
{"name":"Jobas", "home":"moyo town"},
{"name":"Richard", "home":"palo alto"}
]
# sort this people
people.sort()
Using regular function to sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
people = [
{'name':"lagu", "home":"st. paul"},
{"name":"Jobas", "home":"moyo town"},
{"name":"Richard", "home":"palo alto"}
]
# sort this people
def f(p):
return p["name"]
people.sort(key=f)
print(people)
Using lambda function to sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
people = [
{'name':"lagu", "home":"st. paul"},
{"name":"Jobas", "home":"moyo town"},
{"name":"Richard", "home":"palo alto"}
]
# sort this people
# def f(p):
# return p["name"]
# people.sort(key=f)
#or using lambda function we
people.sort(key= lambda p:p["name"])
print(people)
Python Virtual Environment
At this point, we you should now be able to write python application using just the knowledge you have acquired. To so, you will need to write a compact applications and to do that you need to know about python virtual environment. This topic is not intended to be part of this crash course so checkout the Python Virtual Environment section of the website to learn more...
Functional Programming in Python
Function Decorator
A function decorator is a function takes in a another function and return a funtion, normally a wrappper function.
Create a decorator function
1
2
3
4
5
6
7
8
9
10
11
def check_user_login(f):
user_login=False # get from API
def wrapper():
if user_login:
print("Login")
f()
print("now read message")
else:
print("not authorized")
return
return wrapper
To use the decorator function
1
2
3
4
5
@check_user_login
def private_message():
print("Hello John")
private_message()
Python Classes
We python classes to define custom data types of our choice to deal with real world objects. We seen that python has built-in data types: numbers, strings, boolean, dictionaries, tuples, sets and so forth. These data types are great but they don't alway to the model of data we may want to use in our application. To deal with this problem, we use python classes to create the object of desired types.
Creating a classes in python
To create a class, we use the class keyword to declare the class. We user PascalNamingConvention that is capitalize the first letter of every word used in creating a class.
1
2
3
class UserData:
def get_name(self):
print("Lagu")
After creating a class we instantiate it, we create a new object
1
2
3
4
5
user1 = UserData()
user1.get_name()
user2 = UserData()
user2.get_name()
Instance objects are different from each other i.e, user1 is different from user2
Python Class Constructor
In the class UserData above, we see that each time we call method get_name(), we get the same result. Ideally we would instantiate our class with some prior information that then gets called when the instance object is created, to do this we use a class constructor
1
2
3
4
5
6
7
8
9
10
class UserData:
def __init__(self, name, age):
self.name = name
self.age = age
def get_user_info(self):
print(f"My name is {self.name} and I am {self.age} years old")
user1 = UserData("Lagu", 22)
print(user1.get_user_info())
Class Inheritance in Python
Let's the class Animal, we know that all animals can work but different animal make different sounds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Dog:
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} is walking...")
def bark():
print("wof wof...")
class Cat:
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} is walking...")
def mew():
print("Mew, mew...")
The class Cat, Dog all have the constructor and walk methods repeated, this clearly violates the DRY principles i.e Don't Repeat Yourself, so to solve this issue we can use class inheritance where we can move all the shared methods in to the parent class Animal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Animals:
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} is walking...")
class Dog(Animals):
def bark():
print("wof wof...")
class Cat(Animals):
def mew():
print("Mew, mew...")
cat = Cat("Rose")
cat.walk()
dog = Dog("Hipin")
dog.walk()
Exceptions in Python
No how clever and brilliant programmer you are, you code will at one point fail, but when it does, you need to provide a so ground for the code fail gracefully. If you don't handle exceptions, the real problem will be program crashes.
Conside the pieces of code below.
1
2
3
4
5
6
x = int(input("x: "))
y = int(input("y: "))
res = x/y
print(res)
If you enter 5 for x and 2 for y, you peacefully get 2.5 but try to enter 3 for x and 0 for y, the program will crash with DivisionByZero exceptions.
1
2
3
4
5
6
x = int(input("x: "))
y = int(input("y: "))
res = x/y
print(res)
What really happened, well, we tried to divide a number by zero and we know from simple arithmetics that is not possible so that operation has crashed our program. The problem here is now assuming our code has some task to do after completing the division task, well now the program has crashed so, it won't continue down. If we want to make sure that our code should crash and stop, we can improve that code by handling the exception.
1
2
3
4
5
6
7
8
9
10
11
import sys
x = int(input("x: "))
y = int(input("y: "))
try:
res = x/y
except ZeroDivisionError:
print(f"Error: Oh no! you can't divide {x} by zero")
sys.exit(1)
print(f"{x} / {y} = {res} ")
Again, try to enter 4 for x and "hello" for y, and see what you will you, this time you will get a value error, we also need to handle that error
1
2
3
4
5
6
7
8
9
10
11
import sys
x = int(input("x: "))
y = int(input("y: "))
try:
res = x/y
except ZeroDivisionError:
print(f"Error: Oh no! you can't divide {x} by zero")
sys.exit(1)
print(f"{x} / {y} = {res} ")
To improve the code to handle invalid inputs we will write this,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import sys
try:
x = int(input("x: "))
y = int(input("y: "))
except ValueError:
print("Invalid inputs, please enter numbers only!")
sys.exit(1)
try:
res = x/y
except ZeroDivisionError:
print(f"Error: Oh no! you can't divide {x} by zero")
sys.exit(1)
print(f"{x} / {y} = {res} ")
Destructuring in Python