Week 3- Introduction to Python #2
Week 3- Introduction to Python #2
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')
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 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
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]
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
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).
grades=[90,88,84,30,100]
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
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
#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
# 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)
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