Introduction to Python
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)
• Interpreter
based (No compiling, translated code runs on an
intermediate layer)
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
• 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
9
Hello World
• Signin to google colab /alternatively you can create new file in the
Gdrive
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
11
Print function
• Numbers , strings and variables can be passed as parameters
• Try following
print(8*10)
Print(8*’hello’)
12
DATA TYPES AND
VARIABLES
13
Variables
• Variable are place holders (locations in memory)
15
Lets do some math
•A circle has a radius 3cm
• Write a program to calculate its Area
16
• Modify your program to get the radius from the user
Hint :
some_variable = input(‘your text here’)
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
multiply(2,3)
20
• Create a function to return the area when radius is given
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"]
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:
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
del thislist[0]
29
Copy and reference by address
What do you expect ?
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")
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)
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
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
47
Nested loops
• You can nest loops inside each other
for x in adj:
for y in fruits:
print(x, y)
48