INTRODUCTION TO PYTHON
American University of Sharjah
Prepared by Dr. Jamal A. Abdalla, CVE
Revised by Dr. Tamer Shanableh, CSE
if Statement
2
# Initialize variables x and y
Output:
x = 12 Above ten
y = 10 x is greater than 10
z = 8 Both conditions are true
one or both conditions are true
# Nested if – else statement
if x > 10:
print('Above ten')
if x <= 10:
print('x is less than or equal to 10')
else: #note: there is no condition after else
print('x is greater than 10')
# if statement with and logical operator
if x > y and y > z:
print('Both conditions are true')
# if statement with or logical operator
if x > y or y > z:
print('one or both conditions are true')
grade = 89
if grade>= 95 and grade <=100: if statements example
print('A')
if grade>= 90 and grade < 95:
print('A-')
if grade >= 85 and grade < 90: Convert a numeric grade into
print('B+')
if grade >= 80 and grade < 85:
a letter grade
print('B')
if grade >= 75 and grade < 80:
print('B-')
if grade >= 70 and grade < 75:
Notice the use of “multiple” if
print('C+') statements (11 of them !)
if grade >= 65 and grade < 70:
print('C')
if grade >= 60 and grade < 65:
print('C-')
if grade >= 55 and grade < 60:
print('D')
if grade >= 0 and grade < 55:
print('F | See you next semester !')
if grade < 0 or grade > 100:
print('Invalid grade, enter a grade between 0 and 100 please...')
print ('Done with multiple if-statement!')
if – elif –else statement
(a.k.a. multiway if statements)
4
# Initialize variables x and y
x = 12
y = 10
# if statement
if x > y:
print('x is greater than y')
# if – else statement
if x > y:
print('x is greater than y')
else:
print('x is less than or equal to y')
# if – elif - else statement
if x > y:
print('x is greater than y')
elif x == y: Output:
print('x is equal to y') x is greater than y
else: x is greater than y
print('x is less than y')
x is greater than y
grade = 89 if-elif-else statement
if grade >= 95 and grade<=100:
print('A') example
elif grade >= 90 and grade < 95:
print('A-')
elif grade >= 85 and grade < 90:
print('B+') Convert a numeric grade
elif grade >= 80 and grade < 85:
print('B')
into a letter grade
elif grade >= 75 and grade < 80:
print('B-')
elif grade >= 70 and grade < 75:
print('C+')
Notice the use of “1”
elif grade >= 65 and grade < 70: if-elif-else statement
print('C')
elif grade >= 60 and grade < 65:
print('C-')
elif grade >= 55 and grade < 60:
print('D')
elif grade >= 0 and grade < 55:
print('F | See you next semester !')
elif grade < 0 or grade > 100:
print('Invalid grade, enter a grade between 0 and 100 please...')
#or use ‘else’ for the last part. Recall, there is no () after else
#else:
#print('Invalid grade, enter a grade between 0 and 100 please...')
print ('Done with if-elif-else statement!')
Indentation, Colon and line end
6
¨ A Indentation (whitespace) is used to specify the code
block.
¨ Four spaces are usually used
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
• Colons start of a new block in many constructs, e.g. function definitions,
then clauses
¨ if x > y:
print(“x is greater than y")
if x != y:
print(“x is not equal to y")
else:
print(“x is > or < or == to y“)
while Loop
7
The while loop executes a set of statements
as long as its condition is true
i = 1
#keep looping while i<6 Output:
1
while i < 6: 2
3
print(i) 4
5
i = i + 1 # or i += 1
While loop examples – 1(count up and countdown)
8
counter=0
while (counter<=10):#count up: keep looping while counter < 10
print('Loop iteration...', counter)
counter = counter + 1;
#end of loop
print('-----------------------')
counter=10
while (counter > 0):#countdown: keep looping while counter > 0
print('Loop iteration...',counter)
counter = counter - 1;
#end of loop
print('Done!')
While loop example-2 (with an if-statement)
counter=0
while (counter<10): #count up
if (counter%2==0):
print(counter, ' is even')
else:
print(counter, ' is odd')
#end of if statement
counter = counter + 1;
#end of loop
print('Done!')
While loop example - 3
10
grades=[90,80,99,100]
#find avg using built-in functions
avg = sum(grades)/len(grades)
print('avg = ', avg)
#find the avg using a while loop
idx=0
sum_grades=0;
while(idx<len(grades)):
sum_grades = sum_grades + grades[idx]
idx = idx + 1
avg = sum_grades/len(grades) # or divide by idx
print('avg = ', avg)
Nested while Loop
11
The while loop executes a set of statements as long
as its condition is true
Output:
i = 1
i= 1
while i <= 2:
print("i=", i) j= 1
j=1 j= 2
while j <= 3: j= 3
print("j=", j) i= 2
j = j+1
j= 1
i = i+1
j= 2
j= 3
Nested loops example with while-statements
#print out the multiplication table
i = 1 1*1=1
#outer loop 1*2=2
1*3=3
while i <= 10: 1*4=4
1*5=5
1*6=6
j=1 1*7=7
#inner loop, runs for each value of i=1..10 1*8=8
1*9=9
while j <= 10: 1 * 10 = 10
print(i,'*',j,'=',i*j) ---------
2*1=2
j = j+1 2*2=4
2*3=6
2*4=8
i = i+1 2 * 5 = 10
print('---------') 2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
…
while loop with else statement
13
The while loop executes a set of statements as long as its
condition is true. It executes the statements within the else block
when the condition is False
Print a message when the condition is false
i = 1
while i < 6:
print(i) Output:
1
i += 1 2
else: 3
print("i is no longer less than 6") 4
5
i is no longer less
than 6
for loop
14
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
cars = ['Toyota', 'Lexus', 'BMW', 'Tesla']
for x in cars:
Output:
print(x) Toyota
Lexus
BMW
Tesla
The range() function returns a sequence of numbers, starting from
0 by default, and increments by 1 (by default), and ends at a specified
number (minus 1, so 5 in this case). Output:
0
1
for x in range(6): 2
print(x) 3
4
5
For loop example
grades=[90,88,84,30,100]
#find avg using built-in functions
avg = sum(grades) / len(grades)
print('avg = ', avg)
#find avg using a for loop
sum_grades=0
for grade in grades:
sum_grades = sum_grades + grade
#end of loop
avg = sum_grades / len(grades)
print('avg = ', avg)
Nested for loops
16
Print each car for every color: Output:
Toyota red
cars = ["Toyota", "Lexus", "BMW", "Tesla"] Toyota white
colors = ["red", "white", "black", "blue"] Toyota black
Toyota blue
for x in cars: Lexus red
for y in colors: Lexus white
Lexus black
print(x, y)
Lexus blue
BMW red
BMW white
BMW black
BMW blue
Tesla red
Tesla white
Tesla black
Tesla blue
Range function examples:
# range (from, to-1) The function call range(10) represents a
for number in range(1, 10): sequence of consecutive integers starting from 0
print(number, ' ') and continuing up to, but not including 10. In
this case, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Output: 1 2 3 4 5 6 7 8 9
The function call range(1,10) represents a
sequence of consecutive integers starting from 1
# range (from, to-1, step) and continuing up to, but not including 10. In
for number in range(1, 10, 2): this case, 1, 2, 3, 4, 5, 6, 7, 8, 9
print(number, ' ')
The function call range(1,10,2) represents a
Output: 1 3 5 7 9 sequence of consecutive integers, with a step of
2, starting from 1 and continuing up to, but not
including 10. In this case, 1, 3, 5, 7, 9
Nested loops example with for-statements
18
#print out the multiplication table
1*1=1
#outer loop 1*2=2
1*3=3
for i in range(1,11): 1*4=4
1*5=5
1*6=6
#inner loop, runs for each value of i=1..10 1*7=7
for j in range(1,11): 1*8=8
1*9=9
print(i,'*',j,'=',i*j) 1 * 10 = 10
---------
2*1=2
2*2=4
print('---------') 2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
…
for loop with else statement
19
Print all integers from 0 to 5, and print a message
when the loop has ended:
for x in range(6):
print(x)
else:
print("End of for loop")
Output:
0
1
2
3
4
5
End of for loop
Classes and Objects-1
20
Python is an object oriented programming language.
Almost everything in Python is an object, with its variables (a.k.a. properties) and
functions (a.k.a. methods).
Defining a new class is like creating a new type in Python (in addition to int,
float,…we now have the type Person in the example below
A Class is like an object constructor, or a "blueprint" for creating objects.
#define a class called Person
class Person:
#initialization function/method to create Person objects
#the Person has 2 variables/properties: name and age
def __init__(self, name, age):
self.name = name
self.age = age
#"self" refers to the instance of a class
Classes and Objects-2
21
# To construct an instance of type Person and set its name
and age use:
p1 = Person("Hamad", 21) #this calls the __init__ function
p2 = Person ("Layla", 19) #this calls the __init__ function
# This prints its location in the memory which is useless
to us
print('Memory location of p1 is: ', p1)
#You can access the properties of the person using the '.'
print('p1: ',p1.name,' ',p1.age)
print('p2: ',p2.name,' ',p2.age)
Output:
Memory location of p1 is: <__main__.Person object at 0x785320ff7e80>
p1: Hamad 21
p2: Layla 19
Functions (programmer-defined functions)
22
A function is a block of code which only runs when it is called.
A function may take parameters and return data as arguments
Elements of a Function
23
# Ex-1 Function definition
def my_function():
print(“This is a print from my_function")
# Function call, the function is not ran until called
my_function()
# Ex-2 Function definition
def my_function(first_name, last_name):
print(first_name + " " + last_name)
# Function call
my_function(“Omar", “Al Omar")
Functions, return statement
24
Functions – summary -1
import math
#a function without parameters and without a return value (print result
from the function)
def findArea_1():
r = 100
area = math.pi * r**2
print('area = ', area)
#a function with a parameter and without a return value (print result
from the function)
def findArea_2(r):
#r = 100
area = math.pi * r**2
print('area = ', area)
#a function with a parameter and without a return value (print result
from the function)
def findArea_3(r):
#r = 100
area = math.pi * r**2
return area
#print('area = ', area)
Functions summary - 2
How to call the 3 function types ?
#call the functions
findArea_1() # function without a parameter and no return value
findArea_2(100)# function with a parameter and no return value
# function with a parameter and a return value
result = findArea_3(100)
print('area = ', result)
Adding functions to Classes
27
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def printInfo(self):
print("Hello my name is " + self.name)
print('I am',+ self.age, 'years old')
p1 = Person("Sami", 36)
p1.printInfo()
Output:
Hello my name is Sami
I am 36 years old
Interactive mode and script mode
28
¨ Interactive mode or command line mode (>>> or
Colab symbol)
¨ This for direct interaction with the interpreter.
¨ Interactive mode is a good way to test few lines of code.
¨ Script mode or Python file mode
¨ The script mode is done by saving the code to a file
and then execute the script/file. Python scripts have
names that end with .py such as (filename.py)
¨ Script mode is used for large number of code lines
Learning Outcomes
29
Upon completion of the course, students will be able to:
1. Identify the importance of AI and Data Science for society
2. Perform data loading, preprocessing, summarization and
visualization
3. Apply machine learning methods to solve basic regression
and classification problems
4. Apply artificial neural networks to solve simple engineering
problems
5. Implement basic data science and machine learning tasks
using programming tools