Lecture 04
Lecture 04
Lecture 4
Lecture Outline
– CS1001 Lecture 4 –
Control Logic
– CS1001 Lecture 4 – 1
What happens if a negative value is
entered?
## Calculate the circumference of a circle from its radius
## Step 1: Ask for the radius
## Step 2: Apply the circumference formula
## Step 3: Print out the results
circumference = 2 * pi * radius
– CS1001 Lecture 4 – 2
Unexpected input
False
radius >= 0?
True
circumference = 2*pi*r
print("The circumference...
– CS1001 Lecture 4 – 3
Conditional control flow
if radius >= 0:
circumference = 2 * pi * radius
print("The circumference is",circumference)
– CS1001 Lecture 4 – 4
Logical/Boolean expressions
– CS1001 Lecture 4 – 5
If statements
if boolean-expression:
statement(s)-if-expression-is-true
Boolean False
expression
True
Statement(s)
– CS1001 Lecture 4 – 6
If-else statements
• If the condition in an if statement (radius>=0 for
example) is False then the statements within the
if are not executed, and execution continues from
the next statement outside of the if (not indented).
True False
Boolean
expression
Statement(s) Statement(s)
for true case for false case
– CS1001 Lecture 4 – 7
If-else statements
if radius >= 0:
circumference = 2 * pi * radius
print("The circumference is",circumference)
else:
print("Negative input")
– CS1001 Lecture 4 – 8
Example: subtraction
– CS1001 Lecture 4 – 9
The random module
– CS1001 Lecture 4 – 10
Example: subtraction
# Generate two single-digit integers num1 and num2
# If num1 < num2, swap num1 with num2
# Ask the student to answer ’What is num1 - num2?
# Check the student’s answer and display whether the answer is correct
if answer == result :
print("Correct!", num1, "-", num2, "=", answer)
else:
print("Incorrect", num1, "-", num2, "is not", answer,
"it is", result)
Sample output:
What is 9 - 7?2
Correct! 9 - 7 = 2
– CS1001 Lecture 4 – 11
What is 5 - 4?2
Incorrect 5 - 4 is not 2 it is 1
– CS1001 Lecture 4 – 12
Logical operators
• Logical expressions can be combined with the use
of logical operators not, and, and or.
Operator Example Result
and (2<5) and (2>7) False
or (2<5) or (2>7) True
not not(2==5) True
A B A and B A B A or B
T T T T T T
T F F T F T
F T F F T T
F F F F F F
A not A
T F
F T
– CS1001 Lecture 4 – 13