INTRODUCTION TO PYTHON
1
Content
• What is Python
• Data types and variables
• Lists, Tuples , Sets and Dictionaries
• Conditional Branching
• Loop Structures
2
WHAT IS PYTHON
3
Python
• Is
a programing language (Give instruction to a computer on what
to do)
• High level (easy to understand / write codes , close to English)
• Interpreter
based (No compiling, translated code runs on an
intermediate layer)
• Supports OOP, Structured and Functional Programming
4
Pros and Cons
Advantages Disadvantages
Easy to learn Slow
High readability Multithreading is an Issue
Many libraries
Free and Open source
5
Coding and running a python
program
What we need
• An editor (IDE preferred)
• Jupyter , Pycharm and VS code are popular free IDE for python
• Python environment
6
• Anaconda installs python and several editors (including Jupyter)
It is free for individual use (https://www.anaconda.com/)
• Google colab allow you to run your python program for free.
• https://colab.research.google.com
• It used Jupyter IDE
7
8
What is a program/script/code
•A set of instruction given to the computer
• They are written in languages known as programming languages
• Python is one such language
• The‘grammar’ of the language (the way it is written) is called the
syntax
9
Hello World
• Signin to google colab /alternatively you can create new file in the
Gdrive
• Enter following in code section
print (“hello world”)
• Press ctrl + enter
10
Comments
• Comments are ignored by the computer
• They are used to inform humans (programmers) about details
• E.g.
when the program was written , who wrote it ,What is this variable,
Why this statement is used
• Inline comments ‘#’
• No official support for multiline comments in python
11
Print function
• Numbers , strings and variables can be passed as parameters
• Output is a string printed on the prompt
• Escape characters can also be used (\n ,\t…)
• Try following
print(8*10)
Print(8*’hello’)
12
DATA TYPES AND
VARIABLES
13
Variables
• Variable are place holders (locations in memory)
• Theymake the code compact, manageable, readable and easy to
update
• Python variable naming
• names are case sensitive
• can not have spaces
• can only start from a letter or an underscore
• can only have alpha numeric characters
• keywords cannot be used as names
14
Variable properties
• No declaration is needed
• Data type can change during re assignation
• Data type can be found using ‘type’ keyword
print(type(x))
• Data type can be changed by casting
x = str(3)
• Multiple variables can be assigned same time
x, y, z = "Orange", "Banana", "Cherry"
15
Lets do some math
•A circle has a radius 3cm
• Write a program to calculate its Area
• Define variable r as radius
• Import math library to get pi
• Calculate (remember exponent is ** , not ^)
• Print the result
16
• Modify your program to get the radius from the user
Hint :
some_variable = input(‘your text here’)
If you get an error check the variable types !
17
Functions
•Avariable is used to prevent typing the same value at multiple
places. It also makes it easy to update
•A function is used to prevent typing the same code. If same thing
is done at multiple places we can define that as a function.
def my_function():
print("Hello from a function")
my_function()
18
• def keyword is used to define a function
• After def the function name followed by “:”
• Content
of the function should be indented (Most other
languages use {} for this)
def my_function():
print("Hello from a function")
19
• Optionally
data can be passed in and out from a function. These
are known as arguments
def multiply(num1,num2):
answer = num1*num2
return answer
• When calling, function name and arguments (the signature) should
match
multiply(2,3)
20
• Create a function to return the area when radius is given
• Modify your previous example to include the function
21
LISTS, TUPLES , SETS
AND DICTIONARIES
22
Lists , Tuples , Sets and Dictionary
• Allow storing multiple ‘items’ in a single variable
fruit_list = ["apple", "banana", "cherry"]
• Tuples are immutable (read only)
• Lists are mutable
• Tuples and Lists are ordered , Sets are unordered
• Dictionaries use key:value pairs
23
Lists and Tuples
• These can be created using the constructor as well
a_list = list()
a_tuple = tuple()
a_list = [1,2,3,4,5]
a_tuple = (1,2,3,4,5)
24
Sets
• Unordered and unindexed
• Duplicate values will be ignored
•A set can contain different data types:
thisset = {"abc", 34, True, 40, "male"}
print(thisset)
• Set operations ( union , intersection…) can be applied
25
Dictionary
• Ordered (Python version 3.7 and above)
• Duplicate keys not allowed
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
26
Lists
• Similar to arrays
• Changeable
• Allow duplicate values.
• Ordered
• indexed, the first item has index [0] (Zero based)
mylist = ["apple", "banana", "cherry"]
mylist[0]
• Retrive number of items in a list from len() function
print(len(mylist))
27
List key functions
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant“ # Change an item
thislist[1:3] = ["blackcurrant", "watermelon"] #Change 1,2 index
items
thislist.insert(2, "watermelon") # insert item to second index
thislist.extend(second_list) # append two lists
list3 = list1 + list2 # this also do the same
28
thislist.remove("banana")
del thislist[0]
thislist.clear() # Remove all items from the list
29
Copy and reference by address
What do you expect ?
original = ["apple", "banana", "cherry"]
list_1 = original
original[1] = "coconut"
print(list_1)
mylist2 = copy.deepcopy(original)
30
Deep copy
import copy
original = ["apple", "banana", "cherry"]
list_2 = copy.deepcopy(original)
original[1] = "coconut"
print(list_2)
31
CONDITIONAL
BRANCHING
32
Conditions
• Do something based on a condition.
a = 33
b = 200
if b > a:
print("b is greater than a")
• Remember the indentation and : at the end
33
Logical conditions
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
34
Elif and else
a = 200
b = 33
if b > a:
print("b is greater than a") # first condition satisfied
elif a == b:
print("a and b are equal") # all above condisions are false, but this
one is true
else:
print("a is greater than b") # None of the above is true
35
Logical operands
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
36
Nested conditions
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
37
Exercise
• Print the grade of the student based on following
• Prompt user to enter marks
• If marks less than 20 fail grade
• Above or equal to 20 but less than 40 : C
• Above or equal to 40 but less than 60 : B
• Above or equal to 60 but less than 80 : A
• Above or equal to 80: A+
38
Random numbers
# Generate a random integer in the range including 5,10
import random
x = random.randint(5,10)
print(x)
#Generate a real number between 0-1
random.random()
#Generate a real number between and including 20,60
random.uniform(20, 60)
39
Random shuffle
# Shuffle items in following list
import random
mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist)
print(mylist)
# return a random element
random.choice(mylist))
40
LOOP STRUCTURES
41
While Loop
• Repeat until a condition is satisfied
i=1
while i < 6:
print(i)
i += 1
42
Exercise
• Create a random number
• If it is odd , add one
• If it is even divide it by 2
• Repeat until the number is less than or equal to 1
• Print answer in each step
• Remainder of a division can be obtained by ‘%” operator
e.g. 7%2
43
For Loop
• Iterate over a set number of times or a sequence
for x in range(6):
print(“Hello world”)
for x in range(10,20,2):
print(x)
44
Iterate through a list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
45
Exercise 2
• Followingare the marks of students. Print their grades based on
previous grade sheet
68 33 97 24 50 46
46
Break and continue statements
• Common to while and for loops
• break immediately exists a loop
• continue immediately move it to the next iteration
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
47
Nested loops
• You can nest loops inside each other
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
48