0% found this document useful (0 votes)
8 views27 pages

ICT582 Topic 02

Uploaded by

Hammad anwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views27 pages

ICT582 Topic 02

Uploaded by

Hammad anwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Topic 2

Branching and Iterartion


LAST WEEK

§ Syntax and semantics


§ Scalar objects
§ Simple operations
§ Expressions, variables and values
§ Output statement print( … )
§ Converting something to int or float:
int( ….)
float( … )
LECTURE 2 2
TODAY’S LECTURE

§ String object type


§ Type casting
§ Branching and conditionals
§ Indentation
§ Iteration and loops

LECTURE 2 3
STRINGS
§ A string contains a sequence of letters, special characters,
spaces, digits enclosed in single quotes or double quotes
hi = 'hello there'
Py = "Python is fun"

§ concatenate two strings


name = "buddy"
greet = hi + name
greeting = hi + ' ' + name
§ do some operations on a string as defined in Python docs
silly = hi + (" " + name)*3
LECTURE 2 4
STRINGS
§ You may use single quotes or double quotes
interchangeably. However, if the string contains a double
quote character, you may want to use single quotes:
hi = '"Good morning", said Mary'

§ And vice versa:


msg = "You've got an error"

LECTURE 2 5
INPUT/OUTPUT: print

§ used to output stuff to the console (eg, terminal)


§ keyword is print
x = 5
print(x)

§ A numeric number such as 5 and a string "5" may look the


same when they are printed, but they are very different in
terms of the operations performed on them.

§ Sometimes, we need to convert a number to a string, or a


string to a number. Eg, convert a number to a string
x_str = str(x) 6
LECTURE 2
print("my fav num is " + x_str )
INPUT/OUTPUT: input("")

§ prints whatever is in the quotes


§ user types in something as input and then hits enter
§ binds that value to a variable
text = input("Type anything... ")
print(5*text)

§ input gives you a string so must cast if working with


numbers (ie, converted to a number)
num = int(input("Type a number... "))
print(5*num)
Question: what would be printed
LECTURE 2 if no type casting? 7
ACTIVITY

§ Write a program that takes the unit code and total mark in
that unit as input and prints following customized message.
unit = input("Type in your unit code: ")
mark = input("Type in your mark: ")
print("Your unit code is " + unit + "and your mark is " + mark)

§ Repeat the above, but increase the mark by 10%

LECTURE 2 8
COMPARISON OPERATORS ON
int, float, string

§ i and j are variable names


§ comparisons below evaluate to a Boolean
i > j
i >= j
i < j
i <= j
i == j -> equality test, True if i is the same as j
i != j -> inequality test, True if i not the same as j
9
LECTURE 2
LOGIC OPERATORS ON bools

§ a and b are variable names (with Boolean values)


not a -> True if a is False
False if a is True
a and b -> True only if both a and b are True
a or b -> True if either a or b is True

A B A and B A or B

True True True True


True False False True
False True False True
LECTURE 2 1
False False False False 0
COMPARISON EXAMPLE

pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)

drive = True
drink = False
both = drink and drive
print(both)

LECTURE 2 1
1
CONDITION AND BRANCHING

LECTURE 2 1
2
CONTROL FLOW - BRANCHING

if <condition>: if <condition>:
<statement> <statement>
<statement> <statement>
... ...
elif <condition>:
if <condition>: <statement>
<statement> <statement>
<statement> ...
... else:
else: <statement>
<statement> <statement>
<statement> ...

§ <condition> has a value True or False


§ Execute the statements in that block if <condition>
LECTURE 2 1
3
is
True
INDENTATION AND BLOCK

§ matters in Python
§ how you denote blocks of code
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x/y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
1
print("thanks!") LECTURE 2
4
INDENTATION AND BLOCK

§ Indentation is important
- Python replies on the indentation to define the scope of a block
- Statements in the same block MUST have the same indentation
- Although the number of spaces in an indentation can vary –
Ø it is recommended that you use the same indentation, such as 4 spaces,
throughout your program – don’t try to be smart!

Ø It is also recommended that you use space character rather than tab
character to create an indentation.

Ø You can define the size of indentation in Idle (go to Preferences)

§ Many other programming languages use explicit begin and


LECTURE 2 1

end words to delineate a block: begin/end, {/}, etc. 5


INDENTATION AND BLOCK

§ Check the following code and identify errors:


x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x/y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")
LECTURE 2 1
6
ACTIVITIES

§ Write a program that takes the unit code and total mark in
that unit as input and prints the letter grade according to
following letter grade conversion table:

HD 80-100
D 70-79
C 60-69
P 50-59
N <50

LECTURE 2 1
7
ACTIVITIES

§ Solution
unit = input("Type in your unit code: ")
mark = int(input("Type in your mark: "))
grade = 'N'
if mark >= 80:
grade = 'HD'
if mark >= 70 and mark <80:
grade = 'D'

# complete the rest of the code


# also try to use a single if-elif-else statement to do the same

print("Your unit mark is ", mark, " your unit grade is " + grade)

LECTURE 2 1
8
CONTROL FLOW: while LOOPS

while <condition>:
<statement>
<statement>
...
§ <condition> evaluates to a Boolean
§ if <condition> is True, do all the steps inside
the while code block
§ check <condition> again
§ repeat until <condition> is False

LECTURE 2 1
9
CONTROL FLOW: while LOOPS

You are in the Lost Forest.


************
************
J
************
************
Go left or right?

PROGRAM:
n = input("You're in the Lost Forest. Go left or right? ")
while n == "right":
n = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")

LECTURE 2 2
0
CONTROL FLOW: while LOOPS

§ iterate through numbers in a sequence

# more complicated with while loop


n = 0
while n < 5:
print(n)
n = n+1

# shortcut with for loop


for n in range(5):
print(n)

LECTURE 2 2
1
CONTROL FLOW: for LOOPS
for <variable> in range(<some_num>):
<statement>
<statement>
...
§ Python function range returns a sequence of number
starting with 0 and incremented by 1 by default
- So range(5) returns the sequence 0,1,2,3,4
§ each time through the loop, <variable> takes a value of the
sequence
- first time, <variable> starts at the 1st value (0)
- next time, <variable> gets the next value 2
LECTURE 2
2
- etc.
range(start,stop,step)

§ default values are start = 0 and step = 1 and optional


§ loop until value is stop - 1

mysum = 0
for i in range(7, 10):
mysum += i # same as mysum = mysum + 1
print(mysum)

mysum = 0
for i in range(5, 11, 2):
mysum += i
print(mysum) LECTURE 2 2
3
break STATEMENT

§ immediately exits whatever loop it is in


§ skips remaining expressions in code block
§ exits only the innermost loop!

while <condition_1>:
<statement_b>
if <condition_2>:
break
<statement_c>
LECTURE 2 2
4
break STATEMENT

mysum = 0
for i in range(5, 12, 2):
if mysum > 10:
break
mysum += i
print(mysum)

§ what happens in this program?

LECTURE 2 2
5
for VS while LOOPS

for loops while loops


§ know number of §unbounded number of
iterations iterations
§ can end early via break
§ can end early via
break §can use a counter but must
initialize before loop and
§ uses a counter increment it inside loop
§ can rewrite a for loop §may not be able to rewrite a
using a while loop while loop using a for loop

LECTURE 2 2
6
ACKNOWLEDGEMENT

§ Sources used in this presentation include:


• Programiz.com
• MIT OCW

27

You might also like