Tutorial 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

TUTORIAL 4

234128 – Introduction to
Computing with Python

Written and edited by Bronislav Demin


Today
• IF Statements
• IF-Else
• Numbers and Characters
• Default Function Behavior

234128 – Introduction to Computing with Python 2


IF STATEMENTS

234128 – Introduction to Computing with Python 3


IF Statements
• Thus far we used logical expressions for printing or
calculating values.
• However, logical expressions can be used to make our
programs behave differently according to different
results.
• This can be done in Python using an IF Statement.

234128 – Introduction to Computing with Python 4


IF Statements
• Structure: if expression:
statement
statement
• The expression can be any legal expression:
• if the expression is True, statements will be
evaluated.
• if the expression is False, statements won’t be
evaluated. if (x >= 55):
print("You succeeded!")
234128 – Introduction to Computing with Python 5
Spaces and Indentation
• Python doesn’t care about spaces in a line:


if x > 0: if x > 0:
print(”Positive”) print (”Positive” )

• With indentations it’s another story:


if x > 0:
print(”Positive”) ≠ if x > 0:
print(”Positive”)

234128 – Introduction to Computing with Python 6


IF: Example
grade = int(input("Enter test grade: "))
if (grade < 55):
print("Failed.")
if (grade >= 55):
print("Passed.")

• Such pair of checks complete one another: If one passes, the other
one surely fails and vise versa.
• These sorts of conditions (if x do this, otherwise do that…) are
common.

234128 – Introduction to Computing with Python 7


IF-Else
• Like last example, but with cleaner and more readable code:

if expression:
statement
statement
else:
statement
statement
• if the expression is True, only initial statements will be evaluated.
• if the expression is False, only secondary statements will be evaluated.

234128 – Introduction to Computing with Python 8


IF-Else: Example

grade = int(input("Enter test grade: "))


if (grade < 55):
print("Failed.")
else:
print("Passed.")

• The expression is evaluated only once!


• Note: notice the indentations.
234128 – Introduction to Computing with Python 9
Exercise 1
• Write a program which prints the maximum between
2 variables. In case of equality, print either.

234128 – Introduction to Computing with Python 10


Exercise 1 - Solution
• Write a program which prints the maximum between
2 variables. In case of equality, print either.
if x > y:
print(x)
else:
print(y)

234128 – Introduction to Computing with Python 11


Exercise 1 - Solution
• Write a program which prints the maximum between 2 variables. In case of
equality, print either.
• One line solution is also possible: if x > y:

print(x if x > y else y) <=> else:


print(x)

print(y)
• Even better:
Using Python standard library max function:

print(max(a, b, c,…)) Any number of variables is possible

Similarly, Python standard library has a min function.

234128 – Introduction to Computing with Python 12


IF-Else: elif
• In cases where many options need to be checked, it is better to use elif:

if a < -10:
… if a < -10:
else: …
if a == 10: elif a == 10:

else:

<=> …
elif a > 10:

if a > 10:
… else:
else: print(‘???’)
print(‘???’) Cleaner and more readable code

234128 – Introduction to Computing with Python 13


Exercise 2
• Write a program to find max of two integers. In case
of equality, inform with a printed message.

234128 – Introduction to Computing with Python 14


Exercise 2 - Solution
• Write a program to find max of two integers. In case
of equality, inform with a printed message.
if x > y:
print(x)
elif y > x:
print(y)
else:
print(”Numbers are equal!”)

234128 – Introduction to Computing with Python 15


Exercise 3
• Write a program which receives as input:
1. Name
2. ID
3. Date of birth

• Section I:
- If all forms are filled, print “Thank you!”
- If at least one form is missing, print “Please do not leave empty fields”

• Section II:
- If one form is filled, print “Thank you!”
- If all forms are missing, print “Please do not leave empty fields”

234128 – Introduction to Computing with Python 16


Exercise 3 – Solution A
• Section I solution:
print("Enter below the following details:")
name = input("name:")
identity = input("id:")
date = input("date of birth:")

if name and identity and date:


print("Thank you!")
else:
print("Please do not leave empty fields")
234128 – Introduction to Computing with Python 17
Exercise 3 – Solution B
• Section II solution:
print("Enter below the following details:")
name = input("name:")
identity = input("id:")
date = input("date of birth:")

if name or identity or date:


print("Thank you!")
else:
print("Please do not leave empty fields")
234128 – Introduction to Computing with Python 18
Exercise 4
• Write a program that receives a number as input.
• The program prints if given number has one digit,
two digits, three digits or more.

234128 – Introduction to Computing with Python 19


Exercise 4 - Solution
• Write a program that receives a number as input.
• The program prints if given number has one digit, two digits, three digits or
more.
n = int(input("Enter any number:"))
if n>=0 and n<10:
print("One digit number")
elif n>10 and n<100:
print("Two digit number")
elif n>100 and n<1000:
print("Three digit number")
else:
print("More than three digit number")

234128 – Introduction to Computing with Python 20


NUMBERS AND CHARACTERS

234128 – Introduction to Computing with Python 21


ASCII Table (Part of Unicode)

234128 – Introduction to Computing with Python 22


ASCII Table (Part of Unicode)

234128 – Introduction to Computing with Python 23


Numbers and Characters
• Character – a string of length 1, e.g.: ‘C’, ‘p’, ‘5’.
• Unicode – an international standard for representing text in
computing systems.
• Every character is represented by a corresponding number according
to the Unicode standard.

• Python has special functions for mapping a character to a number


and vice versa:
ord(character) → returns the numerical value of the character
chr(number) → returns the character the number represents

234128 – Introduction to Computing with Python 24


chr(78) = ‘N’ ord(‘A’) = 65
Example: Printing Characters

Ord:
character to
number
We don’t need to
remember this!

234128 – Introduction to Computing with Python 26


Exercise 5
• Write a program that prints the abc.

234128 – Introduction to Computing with Python 27


Exercise 5 - Solution
• Write a program that prints the abc.

234128 – Introduction to Computing with Python 28


Example: Location in Alphabet
• How can we know a location of a letter in the alphabet?
Letter (char): ‘A’ ‘B’ ‘C’ … ‘X’ ‘Y’ ‘Z’
Unicode Value: x x+1 x+2 … x+23 x+24 x+25
Distance from ‘A’: 0 1 2 … 23 24 25

• It is all relative. For example, the relation between the letters


‘X’ and ‘A’:
ord(‘X’) – ord(‘A’) = 23

Location of letter
in the ABC = Unicode value
of letter - Unicode value
of ‘A’

234128 – Introduction to Computing with Python 29


Example
• Find the location in the alphabet of an uppercase letter in
English:

• Convert a lowercase letter to an uppercase letter in English:

234128 – Introduction to Computing with Python 30


Exercise 6
• Write a program that receives a single character as
input.
• The program checks whether the character is
uppercase, lowercase, digit, or neither.

234128 – Introduction to Computing with Python 31


ASCII Table
Reminder: (Part of Unicode)
This is the
ASCII table

Let’s see, for example,


how to check for
UPPERCASE letters

234128 – Introduction to Computing with Python 32


ASCII/UNICODE Table - Reminder

ord(‘A’) = 65
• For a single character (char) to chr(65) = ‘A’
be UPPERCASE, it must fulfil:

(65 <= ord(char)) and (ord(char) <= 90)

• Or: ord(‘Z’) = 90
chr(90) = ‘Z’
65 <= ord(char) <= 90

234128 – Introduction to Computing with Python 33


Exercise 6 - Solution
• Write a program that receives a single character as input.
• The program checks whether the character is uppercase, lowercase,
digit, or neither.
char = input("Enter a character to check: ")
if 65 <= ord(char) <= 90:
print(“Uppercase letter")
elif (ord(char)) >= 97 and (ord(char) <= 122):
print(“Lowercase letter")
elif (ord(char) >= 48) and (ord(char) <= 57):
print(“Digit")
else:
print(“Special character")

234128 – Introduction to Computing with Python 34


Exercise 6 – Better Solution
• Write a program that receives a single character as input.
• The program checks whether the character is uppercase, lowercase,
digit, or neither.
char = input("Enter a character to check: ")
if ord(‘A’) <= ord(char) <= ord(‘Z’):
print(“Uppercase letter")
elif ord(‘a’) <= ord(char) <= ord(‘z’):
No need to remember
print(“Lowercase letter")
ord() values!
elif ord(‘0’) <= ord(char) <= ord(‘9’):
print(“Digit")
else:
print(“Special character")

234128 – Introduction to Computing with Python 35


Exercise 6
• Write a program that receives an integer as input and
prints whether it is odd or even.

234128 – Introduction to Computing with Python 36


Exercise 6 - Solution
• Write a program that receives an integer as input and
prints whether it is odd or even.
num = int(input(“Type an integer: “))
if (num % 2) == 0:
print(f“{num} is even")
else:
print(f“{num} is odd")

234128 – Introduction to Computing with Python 37


DEFAULT FUNCTION BEHAVIOR

234128 – Introduction to Computing with Python 38


Print Function Options
• When using Python functions, some function behaviors are dictated according to
default parameters.
• For example, the print function includes the parameter end. This parameter sets
what the function will print at the end.
• By default: end = ‘\n’ (print a new line at the end).
• This behavior can be changed by modifying the end parameter.

234128 – Introduction to Computing with Python 39


234128 – Introduction to Computing with Python 40

You might also like