Python Session 5 Conditional
Python Session 5 Conditional
Module 1
• Topic 1: Why should you learn to write programs
• Topic 2: Variables, expressions and statements
• Topic 3: Conditional execution
• Topic 4: Functions
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program
displays a message to that effect. If the condition is false, the second set of statements is
executed.
Since the condition must either be true or false, exactly one of the alternatives will be
executed. The alternatives are called branches, because they are branches in the flow of
execution.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
3.9 Debugging
The traceback Python displays when an error occurs contains a lot of information, but it
can be overwhelming. The most useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can
be tricky because spaces and tabs are invisible and we are used to ignoring them.
>>> x = 5
>>> y = 6
File "", line 1 y = 6 ^ IndentationError: unexpected indent
In this example, the problem is that the second line is indented by one space. But the
error message points to y, which is misleading. In general, error messages indicate where
the problem was discovered, but the actual error might be earlier in the code, sometimes
on a previous line.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Exercises
Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40
hours.
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by
printing a message and exiting the program. The following shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Exercises
hours = input('Enter Hours:')
try:
hours = int(hours)
try:
rate=input('Enter rate:')
rate= float(rate)
pay = hours*rate
print(pay)
except:
print('Please enter a number')
except:
print('Please enter a number')
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Exercises
Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the
score is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Exercises