Python 4
Python 4
Composition
• So far, we have looked at the elements of a program — variables,
expressions, statements, and function calls — in isolation, without talking
about how to combine them.
• One of the most useful features of programming languages is their ability
to take small building blocks and compose them into larger chunks.
• For example, we know how to get the user to enter some input, we know
how to convert the string we get into a float, we know how to write a
complex expression, and we know how to print values. Let’s put these
together in a small four-step program that asks the user to input a value for
the radius of a circle, and then computes the area of the circle from
• the formula Area = 𝜋𝑅2
• Firstly, we’ll do the four steps one at a time:
• Example:
q = 7 // 3 # This is integer division operator
print(q)
2
r=7%3
print(r)
1
Input>> 4700
Output>> Hrs= 1 mins= 18 secs= 20
Boolean values and
expressions
Boolean values and expressions
• A Boolean value is either True or False.
• In Python, the two Boolean values are True and False (the capitalization
must be exactly as shown), and the Python type is bool.
• Example:
print(type(True))
<class 'bool'>
print(type(true))
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'true' is not defined
• A Boolean expression is an expression that evaluates to produce a result which is a
Boolean value. For example, the operator == tests if two values are equal. It produces (or
yields) a Boolean value:
• Example:
print(5 == (3 + 2) ) # Is five equal 5 to the result of 3 + 2?
True
print( 5 == 6)
False
j = "hel"
print( j + "lo" == "hello")
True
• In the first statement, the two operands evaluate to equal values, so the expression
evaluates to True; in the second statement, 5 is not equal to 6, so we get False.
Comparison Operators
• The == operator is one of six common comparison operators which
all produce a bool result; here are all six:
• x == y # Produce True if ... x is equal to y
• x != y # ... x is not equal to y
• x>y # ... x is greater than y
• x<y # ... x is less than y
• x >= y # ... x is greater than or equal to y
• x <= y # ... x is less than or equal to y
• Although these operations are probably familiar, the Python symbols are
different from the mathematical symbols. A common error is to use a
single equal sign (=) instead of a double equal sign (==). Remember that = is
an assignment operator and == is a comparison operator. Also, there is no
such thing as =< or =>.
• Example:
age = 19
old = age >= 18
print(old)
True
type(old)
<class 'bool'>
Logical operators
• There are three logical operators, and, or, and not, that allow us to build
more complex Boolean expressions from simpler Boolean expressions. The
semantics (meaning) of these operators is similar to their meaning in
English.
• For example, x > 0 and x < 10 produces True only if x is greater than 0 and
at the same time, x is less than 10.
• n % 2 == 0 or n % 3 == 0 is True if either of the conditions is True, that is, if
the number n is divisible by 2 or it is divisible by 3.
• Finally, the not operator negates a Boolean value, so not (x > y) is True if
(x > y) is False, that is, if x is less than or equal to y. In other words: not True
is False, and not False is True.
Note
• The expression on the left of the or operator is evaluated first: if the
result is True, Python does not (and need not) evaluate the
expression on the right — this is called short-circuit evaluation.
Similarly, for the and operator, if the expression on the left yields
False, Python does not evaluate the expression on the right. So there
are no unnecessary evaluations.
Truth Tables
• A truth table is a small table that allows us to list all the possible
inputs, and to give the results for the logical operators. Because the
and and or operators each have two operands, there are only four
rows in a truth table that describes the semantics of and, or and not.
Simplifying Boolean Expressions
• A set of rules for simplifying and rearranging expressions is called an
algebra. For example: n * 0 == 0.
• not (not x) == x
Python Looping
Overview
• Looping allows you to run a group of statements repeatedly. Some
loops repeat statements until a condition is False; others repeat
statements until a condition is True. There are also loops that repeat
statements a specific number of times.
Each subsequent lone in the loop also needs to be indented by 4 or more spaces. If a line is not
indented it is considered outside the loop and will also terminate any additional lines considered in the
loop. A common mistake is remove the spaces and therefore prematurely end the loop.
Syntax
for iterating_var in sequence:
statements(s)
primes = [2, 3, 5, 7]
for x in primes:
print(x)
Example
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
• Example: Output:
print(range(10)) range(0, 10)
print(list(range(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
for var in list(range(5)): This will produce the following output.
print (var) 0
1
OR 2
3
for var in range(5): 4
print (var)
Example
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
Output:
print() Current Letter : P
Current Letter : y
Current Letter : t
fruits = ['banana', 'apple', 'mango'] Current Letter : h
for fruit in fruits: # traversal of List sequence Current Letter : o
Current Letter : n
print ('Current fruit :', fruit)
Current fruit : banana
Current fruit : apple
print ("Good bye!") Current fruit : mango
Good bye!
Iterating by Sequence Index
• We can use the range() function in for loops to iterate through a sequence
of numbers. It can be combined with the len() function to iterate through a
sequence using indexing. Here is an example.
• Example:
m = ['pop', 'rock', 'jazz'] Output:
• Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something]
• The program first encounters the outer loop, executing its first
iteration. This first iteration triggers the inner, nested loop, which
then runs to completion. Then the program returns back to the top of
the outer loop, completing the second iteration and again triggering
the nested loop. Again, the nested loop runs to completion, and the
program returns back to the top of the outer loop until the sequence
is complete or a break or other statement disrupts the process.
Example
Output:
num_list = [1, 2, 3] 1
a
alpha_list = ['a', 'b', 'c'] b
c
2
for number in num_list: a
b
print(number) c
3
for letter in alpha_list: a
b
print(letter) c