0% found this document useful (0 votes)
13 views

Python 4

The document discusses various Python programming concepts like variables, expressions, statements, functions, loops, and Boolean logic. It provides examples of how to compose small program blocks into larger programs, such as calculating the area of a circle from user input, and using comparison, logical, and loop operators. The document also covers data types like integers, floats, strings, and Boolean values and expressions.

Uploaded by

balqa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python 4

The document discusses various Python programming concepts like variables, expressions, statements, functions, loops, and Boolean logic. It provides examples of how to compose small program blocks into larger programs, such as calculating the area of a circle from user input, and using comparison, logical, and loop operators. The document also covers data types like integers, floats, strings, and Boolean values and expressions.

Uploaded by

balqa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Python

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:

response = input("What is your radius? ")


r = float(response)
area = 3.14159 * r**2
print("The area is ", area)
• Now let’s compose the first two lines into a single line of code, and
compose the second two lines into another line of code.

r = float( input("What is your radius? ") )


print("The area is ", 3.14159 * r**2)
• If we really wanted to be tricky, we could write it all in one statement:

• print("The area is ", 3.14159*float(input("What is your radius?"))**2)


The modulus operator
• The modulus operator works on integers (and integer expressions) and gives the remainder when the first
number is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the
same as for other operators. It has the same precedence as the multiplication operator.

• Example:
q = 7 // 3 # This is integer division operator
print(q)
2

r=7%3
print(r)
1

• So 7 divided by 3 is 2 with a remainder of 1.


• The modulus operator turns out to be surprisingly useful. For
example, you can check whether one number is divisible by
another—if x % y is zero, then x is divisible by y.
Example
• let’s write a program to ask the user to enter some seconds, and we’ll convert them into
hours, minutes, and remaining seconds.

total_secs = int(input("How many seconds, in total?"))


hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, " mins=", minutes, "secs=", secs_finally_remaining)

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.

• Here we see a different algebra— the Boolean algebra— which provides


rules for working with Boolean values. First, the and operator:
• x and False == False
• False and x == False
• y and x == x and y
• x and True == x
• True and x == x
• x and x == x
• Here are some corresponding rules for the or operator:
• x or False == x
• False or x == x
• y or x == x or y
• x or True == True
• True or x == True
• x or x == x
• Two not operators cancel each other:

• 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.

• The following looping statements are available in Python:


• for - Uses a counter or loops through a each item in a list a specified number
of times.
• while - Loops while a condition is True.
• Nested loops - Repeats a group of statements for each item in a collection or
each element of an array.
Syntax
• Loop statements use a very specific syntax. Unlike other languages, Python
does not use an end statement for its loop syntax. The initial Loop
statement is followed by a colon : symbol. Then the next line will be
indented by 4 spaces. It is these spaces to the left of the line that is key.

for c in range(0, 3):


This is the loop
This is a second line and the last line of the for loop
This line is not part of the loop. It is the first line in the rest of the script.

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)

If a sequence contains an expression list, it is evaluated first. Then, the


first item in the sequence is assigned to the iterating
variable iterating_var. Next, the statements block is executed. Each
item in the list is assigned to iterating_var, and the statement(s) block
is executed until the entire sequence is exhausted.
Flow Diagram

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]

# variable to store the sum


sum = 0
Output:
# iterate over the list The sum is 48
for val in numbers:
sum = sum+val

print("The sum is", sum)


The range() function
• We can generate a sequence of numbers using range() function. range(10)
will generate numbers from 0 to 9 (10 numbers).

• Example: Output:
print(range(10)) range(0, 10)

print(list(range(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list(range(2, 8))) [2, 3, 4, 5, 6, 7]

print(list(range(2, 20, 3))) [2, 5, 8, 11, 14, 17]


Example
for x in range(5):
print(x)
# Prints out the numbers 0,1,2,3,4

for x in range(3, 6):


print(x)
# Prints out 3,4,5

for x in range(3, 8, 2):


print(x)
# Prints out 3,5,7
Example
• range() generates an iterator to progress integers starting with 0 upto
n-1. To obtain a list object of the sequence, it is typecasted to list().
Now this list can be iterated using the for statement.

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:

# iterate over the list using index I like pop


for i in range(len(m)): I like rock
print("I like", m[i]) ​I like jazz
Nested For Loops
• Loops can be nested in Python, as they can with other programming
languages.

• 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

You might also like