Python Tutorial Episode 1

This tutorial is following book "Smarter Way to learn Python"
chapters 1 until 19

Sheet Written by Ahsan Farooqui, www.blog.ahsanfarooqui.xyz

Download editable notebook from Here

In [206]:
# Chapter 0 - You can define comments within the program and python will ignore them while executing.
# to add a comment, simply put a # in start and remaining text in that line will be commented.

Chapter - 1 - Print

  • Print command is used to display whatever is passed inside the parenthesis.
  • You can display a string, a number or any value stored in a variable or any calculation.
  • For strings, across the python, you need to enclose your string in " " or ' '
In [207]:
#Printing a string
print("Hello World")
Hello World
In [208]:
#Printing Multiple Strings
# Notice output and how it adds a space between strings
print("Hello","World")
Hello World
In [209]:
#Displaying numbers and calculations
#Notice no quotation marks are required. 
print(1)
print(2)
print(1/2) 
print(2**3) #equivalent to 2 raised to power 3
1
2
0.5
8
In [210]:
# Printing number with string
print("Hello, My Age is",13)
Hello, My Age is 13
In [211]:
#If you have noticed, every print statement is printing in a separate line. to change that, we use end keyword and pass space or tab or whatever you wish to append at the end of print
print("hello",end="")
print("world",end="\n")

#If you have noticed, every print statement is printing in a separate line. to change that, we use end keyword and pass space or tab or whatever you wish to append at the end of print
print("a tab",end="\t")
print("away",end="")
helloworld
a tab	away

Chapter - 2 - Variables

  • A variable is essentially a place in memory in which we store some value
  • Any value can be stored in a variable like numeric values, strings, characters etc.
  • Unlike other languages, we dont need to mention variable's data type in python.

Types of Variables:

  • integer i.e. variable value is real numbers like 1,2,3,4555,444666 etc.
  • float i.e. the variable value is a floating point like 3.4455, 3.14, 24.56, 2555.667 etc.
  • String i.e. the variable value is a string i.e. "Ahsan", "Ali", "Pakistan" etc. Even if the string has one character, it is still termed as a string and not a character.
  • There are other types of variables as well but we'll keep it limited to these three for now.
In [212]:
# Let's create some variables
name = "Ahsan"  #Here we store value Ahsan in a variable called "name". Remember to put your strings between the quotation marks
age = 23        # We can store an integer value in the same way
weight = 60.5   # Here we are storing a floating point number in similar fashion
In [213]:
# Printing these varaibles 
print(name)
print(age)
print(weight)
Ahsan
23
60.5
In [214]:
# I can modify variable at any time
name = "Ali"
#Printing name after modifying
print(name)
Ali
In [215]:
# Similarly I can print all of these variables using single print command
print("My name is",name,", and my age is",age," and I weigh",weight,"kgs")
My name is Ali , and my age is 23  and I weigh 60.5 kgs
In [216]:
#another way to print is using format. Note that this works in python 3.5
#notice there is a small f representing special format just before the string.
print(f"My name is {name}, and my age is {age} and I weigh {weight} KGs")
My name is Ali, and my age is 23 and I weigh 60.5 KGs

Example: Take input from user and greet them

In [217]:
# you can also take quick input from user using input()
name = input("Hello, Please enter your name : ") #input function is used to take input. String passed is presented to user as a prompt
print(f"Hello {name}!") #print whatever name is given by user with a greeting! 
Hello, Please enter your name : Ahsan
Hello Ahsan!

Finding Types of Variable

  • Since we are not declaring a variable type explicitly, we may need to know what a type of variable is
  • for that we use type(variable_name) function to print the type of variable
  • Python automatically selects the python variable type based on the data that is present inside it.
In [218]:
# Lets find type for name, age and weight 
In [219]:
print(type(name))
print(type(age))
print(type(weight))
<class 'str'>
<class 'int'>
<class 'float'>
In [220]:
#now lets say if I change the data in one of the variables. the type will change accordingly. 
#Lets change weight to be a category, rather than numeric weight
weight = "Overweight"

#Now lets find out the type of same variable
print(type(weight))
<class 'str'>

using variables in calculations

We saw already how the variables can be printed with other strings. Now we'll see how they can be used in calculations.
Example 1:
In [221]:
centigrade = 37 #Declaring a variable and assigning value to it. 
fahrenhiet = (centigrade * 9/5) + 32  #Notice how we easily used the centigrade variable directly in formula.
print(f"The temperature {centigrade} degrees centigrade is equivalent to {fahrenhiet} degrees Fahrenheit ")
The temperature 37 degrees centigrade is equivalent to 98.6 degrees Fahrenheit 
The above print statement and fahrenheit statements can be merged as follows...
We replaced the formula within the print statement directly instead of assigning it to any variable.
In [222]:
centigrade = 37 #Declaring a variable and assigning value to it. 
print(f"The temperature {centigrade} degrees centigrade is equivalent to {(centigrade * 9/5) + 32} degrees Fahrenheit ")
The temperature 37 degrees centigrade is equivalent to 98.6 degrees Fahrenheit 

using variables in calculations

Example 2:
Say we want to make a currency converter from USD to PKR. Using rate as of today, i.e. 160 Rupees, we can easily do it like following:
In [223]:
usd = 135.6
pkr = usd * 160
print(f"The ${usd} is equivalent to Rs. {pkr}" )
The $135.6 is equivalent to Rs. 21696.0

using variables in calculations

Example 3:
Updating an existing variable with its own value.
We have a bank balance for a person. Now the person deposits a $100 into the variable
In [224]:
bank_balance = 400
deposit = 100
bank_balance = bank_balance + deposit
print(f"The bank balance after depositing ${deposit} is ${bank_balance}")
The bank balance after depositing $100 is $500

Another method to add a variable to itself is through following syntax:

  • variable_name += 3 --> Adds 3 to the variable_name's value
  • variable_name -= 3 --> Subtracts 3 to the variable_name's value
  • variable_name *= 3 --> Multiplies variable_name's value by 3
    Example of sum is below, practice subtract and multiplication yourself.
In [225]:
bank_balance = 400
deposit = 100
bank_balance +=deposit
print(f"The bank balance after depositing ${deposit} is ${bank_balance}")
The bank balance after depositing $100 is $500
Explanation of line 3:
  • The variable written on the right side of equality takes data from pre-assigned value of variable. It will give error if the variable is not defined previously.
  • the variable on left side of equality updates the value after calculating.

using variables in calculations

Example 4:
Updating an existing variable with its own value.
We wish to calculate the sales tax on a product that costs $100. The tax rate is 5%.
In [226]:
productCost = 100
taxRate = 0.05
productCost = productCost + (productCost*taxRate)
print(f"The product cost after adding tax of {taxRate}% is {productCost}")
The product cost after adding tax of 0.05% is 105.0

One Important point

Anything written between " " or ' ' is considered as a string. Even if they are numbers. Please find below one example and their difference

In [227]:
number1 = "21"
number2 = 21
print(type(number1)) #We cannot use that directly in our calculations. we can cast it,however, to integer but more on that later.
print(type(number2)) #We can use this directly in our calculations
<class 'str'>
<class 'int'>

Chapter-4-Math Expressions

  • Python has inbuilt math characters that can be used directly
  • Addition, subtraction, multiplication, division, remainder etc. can be calculated easily
  • Below are the examples of each of them.
In [228]:
#Addition
print("adding 2+4=",2+4)

#Subtraction
print("subtracting 2-4=",2-4)

#Division
print("Dividing 4/3=",4/3)

#Division and get integer value at answer

print("Dividing 4/3 and getting integer answer=",4//3)

#Multiplication
print("multiplying 2*4=",2*4)

#remainder (remainder is whats left once you divide 2 numbers for example 4 divided by 3 gives 1 as remainder)
print("Finding remainder of 4/3=",4%3)

#Power
print("2 raised to the power 3 equals=",2**3) #This is equivalent to 2 raised to power 2
adding 2+4= 6
subtracting 2-4= -2
Dividing 4/3= 1.3333333333333333
Dividing 4/3 and getting integer answer= 1
multiplying 2*4= 8
Finding remainder of 4/3= 1
2 raised to the power 3 equals= 8

Chapter-5-Variable Names Legal and Illegal

  • Python uses some words as its inbuild function or features. Hence using those words as a variable is not allowed.
  • Examples include and, in, True, False, except, try,is,import,if,global etc.
  • Python gives error if you try to assign any value to any of these. Take following for example:
In [229]:
raise = 3
  File "<ipython-input-229-9e1b1c54f670>", line 1
    raise = 3
          ^
SyntaxError: invalid syntax
In [230]:
import = 4
  File "<ipython-input-230-9f6db7ac69c5>", line 1
    import = 4
           ^
SyntaxError: invalid syntax

Variable Names are Case Sensitive!

This means I can use same word with different cases and code will still run.

Example is below:

In [231]:
Rose = 3
rOse = 2
roSe = 1
rosE = 0
ROSE = -1
rose = -2
In [232]:
print(Rose)
print(rOse)
print(roSe)
print(rosE)
print(ROSE)
print(rose)
3
2
1
0
-1
-2

Standard Notation of Variables

Python Programmers use camelNotation to assign variables, which means if your variable has more than one word, the first letter of first word is written in lower case while the first character of second variable is written in upper case.

Example is below:

  • userBalance
  • myAge
  • name
  • cityName
  • phoneNumber
  • ageOfCustomer

Chapter 7 - Eliminating Ambiguity

You may heard of a BDMAS rule in math. The python follows same rules and if you want to specify or order a calculation first, you must use parenthesis brackets to specify.

Example:

  • Imagine a calculation 1+2-4/5*9. using dmas rule we should get -4.2 as answer
  • But if we contain the 5*9 in brackets, the answer will change.
In [233]:
print("without parenthesis",1+2-4/5*9)
print("with parenthesis",1+2-4/(5*9))
without parenthesis -4.2
with parenthesis 2.911111111111111

Another Example:

  • Imagine a calculation 1+2*5+9. using dmas rule we should get 20 as answer
  • But if we contain the 1+2 and 5+9 in brackets, the answer will change.
In [234]:
print("without brakcets: ",1+2*5+9)
print("with brakcets: ",(1+2)*(5+9))
without brakcets:  20
with brakcets:  42

Chapter 8 - Concatenating Strings

This has been discussed earlier but we should learn a few things here that may help

We can concatenate strings by using + sign between two strings. Please have a look at following examples

In [235]:
#Example 1
string1 = "Hello"
string2 = "World"
string = string1 + string2
print(string)
HelloWorld
In [236]:
#Example 1
greeting = "Hello! "
name = "John"
punctuation = "!"
message = " Welcome to Python 101"

print(greeting+name+punctuation+message)
Hello! John! Welcome to Python 101

Important:

  • String can have any ASCII character as input. You can have a look at complete ASCII chart and read more about it on following link : http://www.asciitable.com/
  • The plus sign concatenates the strings without spaces. So if you wish to add space, you can define an empty string and concatenate it between the two texts. Example below:
In [237]:
greeting = "Hello!"
name = "John"
punctuation = "!"
message = "Welcome to Python 101"
space = " "
print(greeting+space+name+punctuation+space+message)
Hello! John! Welcome to Python 101

Chapter 9 - If-else Statements

So far we checked basic functions regarding variables, calculations etc. Now we move to learn about how to make decisions based on a condition.

The condition is any formula that gives a boolean (True/False) output. We can decide what to show to user or what action to perform based on this condition.

If keyword is used to start such a decision.

Syntax is following:

if(condition):
    perform these actions
    and these as well
    and these too if the condition is true
else:
    perform these actions if condition is false

other lines of code

Notice the colon at the end of if condition and all actions below it are indented by one tab. last line is not indented. else statement is run only when the condition is False and if block is not executed.

Example below:

In [238]:
#Insert random numbers in numberone and two and see the if-else in action:
numberOne = 3
numberTwo = 2
if(numberOne>numberTwo):
    print("Yes")
else:
    print("No")
Yes
In [239]:
# Similarly another example. We can take decisions based on strings as well. 
user = "Female"
if(user=="Male"):
    print("He is a nice guy")
else:
    print("She is a nice girl")
She is a nice girl
In [240]:
#Another Example. Using input to get amount and conversion direction to convert either from PKR to USD or USD to PKR
In [242]:
amount = int(input("Enter amount in PKR or USD: ")) #int() in start helps converting string input to integer value. We'll learn about it in type castings
conversionMode = int(input("Enter conversion direction \n 1 for USD to PKR \n any other digit for PKR to USD: "))
if(conversionMode==1):
    print(f"Total amount for $ {amount} is Rs.{amount*160}")
else:
    print(f"Total amount for PKR {amount} is ${amount/160}")
          
    
Enter amount in PKR or USD: 500
Enter conversion direction 
 1 for USD to PKR 
 any other digit for PKR to USD: 1
Total amount for $ 500 is Rs.80000

You might be wondering what if there are more than two options to select from. For that we use elif.

If keyword is used to start such a decision.

Syntax is following:

if(condition):
    perform these actions
    and these as well
    and these too if the condition is true
    and dont elif or else below.
elif(check this second condition):
    perform these actions if second condition is true
    and dont execute elif or else below
elif(check this third condition)
    perform these actions if third condition is true
    and dont execute elif or else below.
else:
    perform these actions if no option is true

other lines of code

you can add as many elif blocks as you have conditions

Example below:

In [243]:
# We can now modify the above example and add an elif block to it.
user = input("Enter Gender Male/Female")
if(user=="Male"):
    print("He is a nice guy")
elif(user=="Female"):
    print("She is a nice girl")
else:
    print("invalid option")
Enter Gender Male/FemaleMale
He is a nice guy

Chapter 10 - Comparison Operators:

comparison operators are the ones that are used to build a condition.

A list of these operators and their denotions are given as follows:

  • Equality operator denoted by ==,
  • not equal !=
  • less than <
  • greater than >
  • greater than and equal to >=
  • less than and equal to <=

It is worth noting that we can also use the equality and non-equality operators for strings as well. while other operators can only be used for numeric comparisons only.

In equality comparison, note that there are two == signs. It is different from assignment operator that uses one = to assign a value. Python usually gives error if one = is used but if it doesnt give error, the program may not work properly.

In [244]:
#we can quickly see the results as following: 
print(2==3)
print(2!=3)
print(2<3)
print(2>3)
print(2<=3)
print(2>=3)
print("Head"=="Head")
print("Tails"!="Head")
print("Apples"=="Oranges")
False
True
True
False
True
False
True
True
False

How to check Multiple conditions in same If?

We can use keywords like and, or to create our logic.

  • and keyword checks if all conditions are true, only then it returns true.
  • or keyword checks if any one of the condition is true, it returns true.
  • you can compare only two conditions using one and/or. for multiple values, you have to use and again.
  • In a condition where you have both and & or statements written, and will be given precedence if precedence not set through parenthesis. More on precedence : https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
In [245]:
#### Example:
a = True
b = False
c = True
print(a and b)
print(a or b and c)
print(a and b or c)
print(a and (b and c))
False
True
True
False
In [246]:
#Example

a = 30
# so it is less than 20 and less than 5 as well. 

if(a<20 and a>5): #This condition will not be true as it will check for all conditions and it will mark it true only if all conditions are true
    print("The and keyword is run")
elif(a<20 or a>5): #or keyword checks if any one of the conditions are true, it will work. 
    print("The or keyword is run")
else:
    print("none")
The or keyword is run

Nested If-statements.

  • You can put one if statement inside the other to check conditions one after another
  • The complete if-else will be indented inside the other if.
  • the else statement of parent if will come after the nested conditions are over.

Example:

  • let's get a username and password from user. Username is "ahsan" and password is "1234"
  • and then if the username/password is correct, get his age and print like below:
    • if the age is under 21, write "you cannot get a driving license"
    • if the age is between 21 and 40, write "you may proceed to get a driving license"
    • if the age is above 40, write "Please arrange a health certificate before applying"
In [248]:
# First, lets get username and password as input
username = input("Enter Username: ") 
password = input("Enter Password: ") 

# for now we use same input to get password. later we will import a library to take hidden password
# Next step is to check whether the username and password are correct. 

if(username=="ahsan" and password=="1234"):
    # Here all statements will be 
    age = int(input("enter your age")) #converting age to integer.
    if(age<21):
        print("You cannot get a driving license")
    elif(age>=21 and age<=40):
        print("You may proceed to get a driving license")
    else:
        print("Please arrange a health certificate before applying")
else:
    print("invalid username/password")
Enter Username: ahsan
Enter Password: 1234
enter your age40
You may proceed to get a driving license

Pro-tip: you can take input directly into the if conditions as well.

In [249]:
#Run this program and enter hello.
if(input()=="hello"):
    print("yes! you wrote hello")
else:
    print("Sorry")
hello
yes! you wrote hello

Chapter - 15 - Lists

  • We studied previously, that a single variable stores a single value
  • What if we have to store more than one value in a single variable?
  • We use lists to store multiple values and then reference them one after the other.
  • Every entry is
  • This saves us the effort to define plenty of varaibles organzes things
  • A list can have same kind of data or it can store different kinds of data.

Syntax:

  • We define the list as:
    list_name = ["first_element","second_element","third_element"]
  • Now we can access the first element of list, we can do it like list_name[0]. The 0 in the statement is called index value
  • The index values go from 0 until one less than the total length of list
In [250]:
# Example:
# Lets define a list of city names
cities = ["Moscow","Islamabad","Lahore","Peshawar"]
In [251]:
# Printing complete list 
print(cities)
['Moscow', 'Islamabad', 'Lahore', 'Peshawar']
In [252]:
# printing individual elements of list
print(cities[0])
print(cities[1])
print(cities[2])
print(cities[3])
Moscow
Islamabad
Lahore
Peshawar
You can use the list in same way as a variable
In [253]:
print("The list of cities are ",cities)
The list of cities are  ['Moscow', 'Islamabad', 'Lahore', 'Peshawar']
In [254]:
print("The first city in list is ",cities[0])
The first city in list is  Moscow

Adding an element to list:

  • you can add an element by using list_name.append(new_element) function.
  • Let's add a city to the list of cities we already made. Lets add Karachi and Quetta
In [255]:
# Adding Karachi and Quetta to the list
print(cities)
print("\nAfter adding Karachi: ")
cities.append("Karachi")
print(cities)
print("\nAfter adding Quetta: ")
cities.append("Quetta")
print(cities)
['Moscow', 'Islamabad', 'Lahore', 'Peshawar']

After adding Karachi: 
['Moscow', 'Islamabad', 'Lahore', 'Peshawar', 'Karachi']

After adding Quetta: 
['Moscow', 'Islamabad', 'Lahore', 'Peshawar', 'Karachi', 'Quetta']

adding a list to another list.

  • Sometimes, instead of adding a single element, you may need to append another list.
  • This can be done using + sign.
  • Lets add two more cities Faisalabad and Multan using array
In [256]:
cities = cities + ["Faisalabad","Multan"]
print(cities)
['Moscow', 'Islamabad', 'Lahore', 'Peshawar', 'Karachi', 'Quetta', 'Faisalabad', 'Multan']

append() appends the new values at the end of list.

We use insert() if we wish to add a value at a specific location.

  • insert gets two values within the parenthesis. first value specifies the index location and second value specifies the value that is to be inserted.
  • Lets add Gujrat and Gujranwala at index values 2 and 5 respectively.
In [257]:
cities.insert(2,"Gujrat")
print("after inserting Gujrat")
print(cities)
cities.insert(5,"Gujranwala")
print("after inserting Gujranwala")
print(cities)
after inserting Gujrat
['Moscow', 'Islamabad', 'Gujrat', 'Lahore', 'Peshawar', 'Karachi', 'Quetta', 'Faisalabad', 'Multan']
after inserting Gujranwala
['Moscow', 'Islamabad', 'Gujrat', 'Lahore', 'Peshawar', 'Gujranwala', 'Karachi', 'Quetta', 'Faisalabad', 'Multan']
In [ ]:
# 

Chapter - 17 - Slices out of Lists

  • If we wish to get a subset of consecutive items in the list, we can use slices.

Syntax:

  • You can use the index values separated by a colon in the indices.
  • e.g. cities[2:5] returns the values at index values 2, 3 and 4.
  • cities[:5] returns the values at index 0 until 4.
  • cities[5:] rreturns the values from index 5 until the end of the list.
In [258]:
print(cities[2:5])
print(cities[:5])
print(cities[5:])
['Gujrat', 'Lahore', 'Peshawar']
['Moscow', 'Islamabad', 'Gujrat', 'Lahore', 'Peshawar']
['Gujranwala', 'Karachi', 'Quetta', 'Faisalabad', 'Multan']

Chapter - 18 - Deleting and removing elements from list

  • If we want to delete an element from list, we can use del command

Syntax:

  • we can simply write del followed by the element that we want to delete.
  • Lets remove cities Moscow and Multan from the list. Moscow is at index 0 and multan is at index
In [259]:
del cities[9] #to delete multan
print("After deleting Multan: ")
print(cities)
del cities[0] #to delete multan
print("After deleting Moscow: ")
print(cities)
After deleting Multan: 
['Moscow', 'Islamabad', 'Gujrat', 'Lahore', 'Peshawar', 'Gujranwala', 'Karachi', 'Quetta', 'Faisalabad']
After deleting Moscow: 
['Islamabad', 'Gujrat', 'Lahore', 'Peshawar', 'Gujranwala', 'Karachi', 'Quetta', 'Faisalabad']

What if we dont know the index value?

  • If we wish to remove the city name by mentioning its name and not index value, we can use remove() instead of del. #### Syntax:
  • list_name.remove(value)
In [260]:
#Example
#Lets remove Quetta from the list of cities we are working with. 

cities.remove("Quetta")
print("After removing Quetta:",cities)
After removing Quetta: ['Islamabad', 'Gujrat', 'Lahore', 'Peshawar', 'Gujranwala', 'Karachi', 'Faisalabad']

Pop out value

  • when you remove or delete a value, it simply vanishes. Sometimes you need the removed value in a variable to use.
  • to keep value in a variable and remove from list at the same time, we use pop command. #### Syntax:
  • some_variable = list_name.pop(index_value)
Example:
  • Lets pop out the Gujrat from list and assign the value to a variable which is at index value 1
In [261]:
city_name = cities.pop(1)
print(city_name)
print("cities list after popping out Gujrat ",cities)
Gujrat
cities list after popping out Gujrat  ['Islamabad', 'Lahore', 'Peshawar', 'Gujranwala', 'Karachi', 'Faisalabad']