Sei sulla pagina 1di 71

Conditional Statements:

if, while and for


• Comparison/logical relational operator are used in python for
decision making for conditional instructions
• These are used to control the flow of execution of a program if needed.
Depending upon the decision based on operator as True/False path is
taken in the program.
• Following is the general form of a typical decision making structure
found in most of the programming languages –
• Python programming language assumes
any non-zero and non-null values as TRUE,
and
• if it is either zero or null, then it is assumed as
FALSE value.
• The general form of the if statement is:
if condition :
block
• The reserved word ‘ if’ begins an if statement.
The condition is a comparison operator
expression that determines whether or not the
body/block will be executed.
• A colon (:) must follow the condition.

• The block is a block of one or more statements
to be executed if the condition is true.
• The statements within a block must all be
indented the same number of spaces from the
left. The block within an if must be indented
more spaces than the line that begins the if
statement.
• The block technically is part of the if
statement. This part of the if statement is
sometimes called the body of the if.
Python Indentation
• Most of the programming languages like C, C++, Java use
braces { } to define a block of code. Python uses indentation.
• A code block (body of a function, loop etc.) starts with
indentation and ends with the first unindented line. The
amount of indentation is up to you, but it must be consistent
throughout that block.
• Generally four whitespaces are used for indentation and is
preferred over tabs. ‘tab’ key is also used to insert four white
spaces Here is an example.
num = int(input('write input number = '))
if (num>0):
print(num)
print("is a positive number.“)
print("This is always printed.")
print ('end')
OUTPUT IS ON NEXT PAGE
• Output is
write input number = 6
6
is a positive number.
This is always printed.
end
• The enforcement of indentation in Python
makes the code look neat and clean. This
results into Python programs that look similar
and consistent.
• Indentation can be ignored in line continuation. But it's
a good idea to always indent. It makes the code more
readable. For example:
• if True:
• print('Hello')
• a=5

• and
• if True:
• print('Hello'); a = 5

• both are valid and do the same thing. But the former
style is clearer.
• Incorrect indentation will result into Indentation Error.
• Single Statement Suites
• Python requires the block to be indented. If the block
contains just one statement, some programmers will place
it on the same line as the if; for example, the following if
statement that optionally assigns y
• if x < 10:
y=x
• could be written
if x < 10: y = x
• Here is an example of a one-line if clause −
• Example: 5
• var = 100
• if ( var == 100 ) : print "Value of expression is 100“
• print "Good bye!”
• Output is:
Value of expression is 100
Good bye!
Example 1:
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
When the above code is
executed, it produces the
following result –
1 - Got a true expression
value
100
Good bye!
Example 1a Find the quotient

# Get two integers from the user


dividend = int(input('Please enter dividend: '))
divisor = int(input('Please enter dividend: '))
# If possible, divide them and report the result
if divisor != 0:
quotient = dividend/divisor
print(dividend, '/', divisor, "=", quotient)
print('Program finished')
• Python programming language provides following
types of decision making statements.
Sr.No. Statement
• 1 if statements Description: An if
statement consists of a boolean expression
followed by one or more statements.
• 2 if...else statements Description: An if
statement can be followed by an optional else
statement, which executes when the comparison
expression is FALSE.
• 3 nested if statements Description: You
can use one if or else if statement inside
another if or else if statement(s).
Python IF...ELSE Statements

• An else statement can be combined with


an if statement. An else statement contains the block
of code that executes if the conditional expression in
the if statement resolves to 0 or a FALSE value.
• The else statement is an optional statement and there
could be at most only one else statement following if.
• The syntax of the if...else statement is −
• if expression:
statement(s)
else:
statement(s)
Example:2
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"

The output is :
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
Example
# Get two integers from the user
dividend, divisor = eval(input('Please enter two numbers to divide: '))
# If possible, divide them and report the result
if divisor != 0:
print(dividend, '/', divisor, "=", dividend/divisor)
else:
print('Division by zero is not allowed')
Example
value = int(input("Please enter an integer value in the range 0...10: "))
if value >= 0: # First check
if value <= 10: # Second check
print(value, "is in range")
else:
print(value, "is too large")
else:
print(value, "is too small")
print("Done")
• Example nested if/else statement:
value = eval(input("Please enter an integer in the range 0...5: "))
if value < 0:
print("Too small")
else:
if value == 0:
print("zero")
else:
if value == 1:
print("one")
else:
if value == 2:
print("two")
else:
if value == 3:
print("three")
else:
if value == 4:
print("four")
else:
if value == 5:
print("five")
else:
print("Too large")
print("Done")
The elif Statement
• The elif statement allows you to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions
evaluates to TRUE.
• Similar to the else, the elif statement is optional. However,
unlike else, for which there can be at most one statement, there can
be an arbitrary number of elif statements following an if. syntax
• if expression1:
statement(s)
• elif expression2:
statement(s)
• elif expression3:
statement(s)
• else:
statement(s)
• Core Python does not provide switch or case statements as in other
languages, but we can use if..elif...statements to simulate switch case
as follows −
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows
Example 3

var = 100
if var == 200:
print ("1 - Got a true expression value")
print (var)
elif var == 150:
print ("2 - Got a true expression value")
print (var)
elif var == 100:
print ("3 - Got a true expression value")
print (var)
else:
print ("4 - Got a false expression value")
print (var)
print ("Good bye!")

The output will be


3 - Got a true expression value
100
Good bye
Example program equivalent to Example 3 with if statement
var = 100
if var == 200:
print ("1 - Got a true expression value")
print (var)
if var == 150:
print ("2 - Got a true expression value")
print (var)
if var == 100:
print ("3 - Got a true expression value")
print (var)
else:
print ("4 - Got a false expression value")
print (var)
print ("Good bye!")
Output is
3 - Got a true expression value
100
Good bye!
Python nested IF statements
• There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the
nested ifconstruct.
• In a nested if construct, you can have an if...elif...else construct inside
another if...elif...else construct.
• The Syntax of the nested if...elif...else construct may be −
• if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example 4:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
print "Good bye!"
The output of the above program segment is
Expression value is less than 200
Which is 100
Good bye!
Example 5
value = eval(input("Please enter an integer in the range 0...5: "))
if value < 0:
print("Too small")
elif value == 0:
print("zero")
elif value == 1:
print("one")
elif value == 2:
print("two")
elif value == 3:
print("three")
elif value == 4:
print("four")
elif value == 5:
print("five")
else:
print("Too large")
print("Done")
• Loops
• A loop statement allows us to execute a statement or group
of statements multiple times. The following diagram
illustrates a loop statement −

Python programming language provides following


types of loops to handle looping requirements.
• 1 while loop
Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing
the loop body.
• 2 for loop
Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
• 3 nested loops
You can use one or more loop inside any another while,
for or do..while loop.
Python while Loop Statements
A while loop statement in Python programming
language repeatedly executes a target statement as
long as a given condition is true.
• The syntax of a while loop in Python
• while expression:
statement(s)
• Here, statement(s) may be a single statement or a
block of statements. The condition may be any
expression, and true is any non-zero value. The loop
iterates while the condition is true.
• When the condition becomes false, program control
passes to the line immediately following the loop.
• In Python, all the statements indented by the same
number of character spaces after a programming
construct are considered to be part of a single block of
code.
Example 6

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"

When the above code is executed, it


produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Example 6 b
done = False # Enter the loop at least once
while not done:
entry = int(input()) # Get value from user
if entry == 999: # Did user provide the magic number?
done = True # If so, get out
else:
print(entry) # If not, print it and continue

Example 6 c
n=1
stop = int(input('feed the value stop = '))
while n <= stop:
print(n)
n += 1
Using else Statement with Loops
• Python supports to else statement associated with a loop statement.
• If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.
• The following example illustrates the combination of an else
statement with a while statement that prints a number as long as it is
less than 5, otherwise else statement gets executed
• Example 7
• count = 0
• while count < 5:
• print (count, " is less than 5“)
• count = count + 1
• else:
• print (count, "is not less than 5“)
• Single Statement Suites
• Similar to the if statement syntax, if
your while clause consists only of a single
statement, it may be placed on the same line as
the while header.
• Syntax and example of a one-line while clause
• flag = 1
while (flag): print 'Given flag is really true!‘
print "Good bye!"
• It is better not try above example because it goes
into infinite loop and you need to press CTRL+C
keys to exit.
Parameters for ‘for’ loop
range() Parameters
• range() takes mainly three arguments having the same use
in both definitions:
• start - integer starting from which the sequence of integers
is to be returned
• stop - integer before which the sequence of integers is to
be returned.
The range of integers end at stop - 1.
• step (Optional) - integer value which determines the
increment between each integer in the sequence
• return value from range()
• range() returns an immutable sequence object of numbers
depending upon the definitions used:
• range(stop)
• Returns a sequence of numbers starting from 0 to stop - 1
• Returns an empty sequence if stop is negative or 0.
• range(start, stop[, step])
• The return value is calculated by the following
formula with the given constraints:
• r[n] = start + step*n (for both positive and negative
step) where, n >=0 and r[n] < stop (for positive step)
where, n >= 0 and r[n] > stop (for negative step)(If
no step) Step defaults to 1.
• Returns a sequence of numbers starting
from start and ending at stop - 1.
• (if step is zero) Raises a ValueError exception
• (if step is non-zero) Checks if the value constraint is
met and returns a sequence according to the formula
If it doesn't meet the value constraint,
• Empty sequence is returned.
Example : How range works in Python?
# empty range
print(list(range(0)))
# using range(stop)
print(list(range(10)))
When you run the program, the output will be:
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
# using range(start, stop)
start = 2
stop = 14
step = 2
print(list(range(start, stop, step)))
When you run the program, the output will be:
[2, 4, 6, 8, 10, 12]
• The for Statement
• The while loop is ideal for indefinite loops.
• programmer cannot always predict how many times a
while loop will execute. We have used a while loop
to implement a definite loop, as in
• n=1
• while n <= 10:
• print(n)
• n += 1
• The print statement in this code executes exactly 10
times every time this code runs. This code requires
• three crucial pieces to manage the loop:
• • initialization: n = 1
• • check: n <= 10
• • update: n += 1
Python range() function
• Python provides a more convenient way to express a
definite loop. The for statement iterates over a range of
values. These values can be a numeric range, or, as we
shall, elements of a data structure like a string, list, or
tuple. The above while loop can be rewritten
• for n in range(1, 11):
• print(n)
• The expression range(1, 11) creates an object known as
an iterable that allows the for loop to assign to the
variable n the values 1, 2, . . . , 10. During the first
iteration of the loop, n’s value is 1 within the block.
• In the loop’s second iteration, n has the value of 2. The general
form of the range function call is
• range( begin,end,step )
• Where begin is the first value in the range; if omitted, the default
value is 0; the end value may not be omitted, change is the
amount to increment or decrement; if the change parameter is
omitted, it defaults to 1 (counts up by ones)
• begin, end, and step must all be integer values; floating-point
values and other types are not allowed.
• The range function is very flexible. Consider the following loop
that counts down from 21 to 3 by threes:
• for n in range(21, 0, -3):
print(n, '', end='')
• It prints
• 21 18 15 12 9 6 3
Python len()
• The len() function returns the number of items (length)
of an object.
• The syntax of len() is:
• len(s)
• len() Parameters
• s is a sequence (string, bytes, tuple, list, or range)
• Return Value from len()
The len() function returns the number of items of an
object.
Failing to pass an argument or passing an invalid
argument will raise a TypeError exception
Example 8
# use of string for ‘for’ statement
for letter in 'Python':
print 'Current Letter :', letter
# use of list for ‘for’ statement
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
print ("Good bye!“)

It produces the following result −


• Current Letter : P
• Current Letter : y
• Current Letter : t
• Current Letter : h
• Current Letter : o
• Current Letter : n
• Current fruit : banana
• Current fruit : apple
• Current fruit : mango
• Good bye!
Iterating by Sequence Index
• An alternative way of iterating through each item is by
index offset into the sequence itself. Following is a simple
example −
# Example.9
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!“

It produces the following result −


• Current fruit : banana
• Current fruit : apple
• Current fruit : mango
• Good bye!
• Here, we took the assistance of the len() built-in function,
which provides the total number of elements in the tuple
as well as the range() built-in function to give us the actual
sequence to iterate over.
Example 10
lower = 10
upper = 20
# uncomment the following lines to take input from the user
#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
for i in range(2,num):
if (num % i) == 0:
break
else:
print ('%d is a prime number \n' %(num))
• It produces the following result −
• ('Prime numbers between', 10, 'and', 20, 'are:')
• 11 is a prime number
• 13 is a prime number
• 17 is a prime number
• 19 is a prime number
Python nested loops

• Python programming language allows to use one loop inside


another loop. Following section shows few examples to
illustrate the concept.
• Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
• The syntax for a nested while loop statement in Python
programming language is as follows −
while expression:
while expression:
statement(s)
statement(s)
• A final note on loop nesting is that you can put any type of
loop inside of any other type of loop. For example a for loop
can be inside a while loop or vice versa.
Example.11
Write a program to find the prime numbers between 2 and 15
i=2
while(i < 15):
j=2
while(j <= (i/j)):
if not(i%j):break
j=j+1
if (j > i/j):print i,"is prime"
i=i+1
print "Good bye!"

• It produces following result −


• 2 is prime
• 3 is prime
• 5 is prime
• 7 is prime
• 11 is prime
• 13 is prime
Loop Control Statements
• Loop control statements change execution from its normal
sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.
• Python supports the following control statements.

Control Statement & Description


• 1 break statement
• Terminates the loop statement and transfers execution to
the statement immediately following the loop.
• 2 continue statement
• Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
• 3 pass statement
• The pass statement in Python is used when a statement is
required syntactically but you do not want any command or
code to execute.
Python break statement
• It terminates the current loop and resumes execution at the
next statement, just like the traditional break statement in C.
• The most common use for break is when some external
condition is triggered requiring a hasty exit from a loop.
The break statement can be used in both while and for loops.
• If you are using nested loops, the break statement stops the
execution of the innermost loop and start executing the next
line of code after the block.

#Example.12
# First Example
for letter in 'Python':
if letter == 'h':
break
print ('Current Letter :', letter )
Output:
• Current Letter : P
• Current Letter : y
• Current Letter : t
# Second Example
var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!”)

• When the above code is executed, it produces the following result −


• Current variable value : 10
• Current variable value : 9
• Current variable value : 8
• Current variable value : 7
• Current variable value : 6
• Good bye!
• Python continue statement
• It returns the control to the beginning of the
while loop.. The continue statement rejects all
the remaining statements in the current
iteration of the loop and moves the control
back to the top of the loop.
• The continue statement can be used in
both while and for loops.
Example: 13
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
When the above code is executed, it produces the following
result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Example 14
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
Output is
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye
Python pass Statement
• It is used when a statement is required syntactically but
you do not want any command or code to execute.
• The pass statement is a null operation; nothing
happens when it executes. The pass is also useful in
places where your code will eventually go, but has not
been written yet
• Example:15
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye")
• With pass
• Current Letter : P
• Current Letter : y
• Current Letter : t
• This is pass block
• Current Letter : h
• Current Letter : o
• Current Letter : n
• Good bye
• With break
• >>>
• Current Letter : P
• Current Letter : y
• Current Letter : t
• Good bye
• With Continue
• >>>
• Current Letter : P
• Current Letter : y
• Current Letter : t
• Current Letter : o
• Current Letter : n
• Difference between for and while
• while loop is used in situations where we do
not know how many times loop needs to be
executed beforehand. However it is used for
fixed iteration as well.

• for loop is used where we already know about


the number of times loop needs to be
excuted. Typically for a index used in iteration.
Example: 16 See the output on next page when height is 7
# Get tree height from user
height = int(input("Enter height of tree: "))
# Draw one row for every unit of height
row = 0
while row < height:
# Print leading spaces; as row gets bigger, the number of
# leading spaces gets smaller
count = 0
while count < height - row:
print(end="#")
count += 1
# Print out stars, twice the current row plus one:
# 1. number of stars on left side of tree
# = current row value
# 2. exactly one star in the center of tree
# 3. number of stars on right side of tree
# = current row value
count = 0
while count < 2*row + 1:
print(end="*")
count += 1
# Move cursor down to next line
print()
row += 1 # Consider next row
• Enter height of tree: 7

*
***
*****
*******
*********
***********
*************

Listing uses two sequential while loops nested within a


while loop. The outer while loop is responsible for
drawing one row of the tree each time its body is
executed:
Example 17
Question (leadingzeros.py) requests an integer value from the user. The
program then displays the number using exactly four digits. The program
pre pends leading zeros where necessary to ensure all four digits are
occupied. The program treats numbers less than zero as zero and numbers
greater than 9,999 as 9999.
# Request input from the user
num = eval(input("Please enter an integer in the range 0...9999: "))
# Attenuate the number if necessary
if num < 0: # Make sure number is not too small
num = 0
if num > 9999: # Make sure number is not too big
num = 9999
print(end="[") # Print left brace
# Extract and print thousands-place digit
digit = num//1000 # Determine the thousands-place digit
print(digit, end="") # Print the thousands-place digit
num %= 1000 # Discard thousands-place digit
# Extract and print hundreds-place digit
digit = num//100 # Determine the hundreds-place digit
print(digit, end="") # Print the hundreds-place digit
num %= 100 # Discard hundreds-place digit
# Extract and print tens-place digit
digit = num//10 # Determine the tens-place digit
print(digit, end="") # Print the tens-place digit
num %= 10 # Discard tens-place digit
# Remainder is the one-place digit
print(num, end="") # Print the ones-place digit
print("]") # Print right brace
#Example 18
# Allow the user to enter a sequence of non-negative
# numbers. The user ends the list with a negative
# number. At the end the sum of the non-negative
# numbers entered is displayed. The program prints
# zero if the user provides no non-negative numbers.

entry = 0 # Ensure the loop is entered


sum = 0 # Initialize sum

# Request input from the user


print("Enter numbers to sum, negative number ends list:")

while entry >= 0: # A negative number exits the loop


entry = eval(input()) # Get the value
if entry >= 0: # Is number non-negative?
sum += entry # Only add it if it is non-negative
print("Sum =", sum) # Display the sum
Example: 19
# Print a multiplication table to 10 x 10
# Print column heading
print(" 1 2 3 4 5 6 7 8 9 10")
print(" +----------------------------------------")
for row in range(1, 11): # 1 <= row <= 10, table has 10 rows
if row < 10:
# Need to add space?
print(" ", end="")
print(row, "| ", end="") # Print heading for this row.
for column in range(1, 11): # Table has 10 columns.
product = row*column; # Compute product
if product < 100:
# Need to add space?
print(end=" ")
if product < 10:
# Need to add another space?
print(end=" ")
print(product, end=" ") # Display product
print() # Move cursor to next row
1 2 3 4 5 6 7 8 9 10
+-----------------------------------------------------
1 | 1 2 3 4 5 6 7 8 9 10
2 | 2 4 6 8 10 12 14 16 18 20
3 | 3 6 9 12 15 18 21 24 27 30
4 | 4 8 12 16 20 24 28 32 36 40
5 | 5 10 15 20 25 30 35 40 45 50
6 | 6 12 18 24 30 36 42 48 54 60
7 | 7 14 21 28 35 42 49 56 63 70
8 | 8 16 24 32 40 48 56 64 72 80
9 | 9 18 27 36 45 54 63 72 81 90
10 | 10 20 30 40 50 60 70 80 90 100
>>>
Problems (ref5)
1. Write a Python program that requests an integer value
from the user. If the value is between 1 and
100 inclusive, print ”OK;” otherwise, do not print
anything.
2. Write a Python program that requests an integer value
from the user. If the value is between 1 and
100 inclusive, print ”OK;” otherwise, print ”Out of
range.”
3. Write a Python program that allows a user to type in
an English day of the week (Sunday, Monday,
etc.). The program should print the Spanish
equivalent, if possible
4. Consider the following Python code fragment:
# i, j, and k are numbers

if i < j:
if j < k:
i=j
else:
j=k
else:
if j > k:
j=i
else:
i=k
print("i =", i, " j =", j, " k =", k)
What will the code print if the variables i, j, and k have the
following values?
(a) i is 3, j is 5, and k is 7
(b) i is 3, j is 7, and k is 5
(c) i is 5, j is 3, and k is 7
(d) i is 5, j is 7, and k is 3
(e) i is 7, j is 3, and k is 5
(f) i is 7, j is 5, and k is 3
5. Consider the following Python program that prints one line of text:
val = eval(input())
if val < 10:
if val != 5:
print("wow ", end='')
else:
val += 1
else:
if val == 17:
val += 10
else:
print("whoa ", end='')
print(val)
What will the program print if the user provides the following input?
(a) 3
(b) 21
(c) 5
(d) 17
(e) -5
6. Write a Python program that requests five integer values from the
user. It then prints the maximum and minimum values entered. If the
user enters the values 3, 2, 5, 0, and 1, the program would indicate
that 5 is the maximum and 0 is the minimum. Your program should
handle ties properly;
for example, if the user enters 2, 4 2, 3 and 3, the program should
report 2 as the minimum and 4 as maximum.
7. Write a Python program that requests five integer values from the
user. It then prints one of two things: if any of the values entered are
duplicates, it prints "DUPLICATES"; otherwise, it prints
"ALL UNIQUE".
8. How many asterisks does the following code fragment print?
a=0
while a < 10:
print('*', end='')
a += 1
print()

9. How many asterisks does the following code fragment print?


a=0
while a < 10:
print('*', end='')
print()
10. How many asterisks does the following code fragment print?
a=0
while a > 10:
print('*', end='')
a += 1
print()

11. How many asterisks does the following code fragment print?
a=0
while a < 10:
b = 0;
while b < 5:
print('*', end='')
b += 1
print()
a += 1
12. How many asterisks does the following code fragment print?
a=0
while a < 10:
if a % 5 == 0:
print('*', end='')
a += 1
print()
13. How many asterisks does the following code fragment print?
a=0
while a < 10:
b=0
while b < 10:
if (a + b) % 2 == 0:
print('*', end='')
b += 1
print()
a += 1
10. How many asterisks does the following code fragment print?
a=0
while a < 5:
b=0
while b < 2:
c=0
while c < 2:
print('*', end='')
c += 1
b += 1
a += 1
print()
11. How many asterisks does the following code fragment print?
for a in range(100):
print('*', end='')
print()
15. How many asterisks does the following code fragment print?
for a in range(20, 100, 5):
print('*', end='')
print()
16. How many asterisks does the following code fragment print?
for a in range(100, 0, -2):
print('*', end='')
print()
17. How many asterisks does the following code fragment print?
for a in range(1, 1):
print('*', end='')
print()
18. How many asterisks does the following code fragment print?
for a in range(-100, 100):
print('*', end='')
print()
19. How many asterisks does the following code fragment print?
for a in range(-100, 100, 10):
print('*', end='')
print()
20. Rewrite the code in the previous question so it uses a while instead of
a for. Your code should behave identically.
21. How many asterisks does the following code fragment print?
for a in range(-10, 10, -1):
print('*', end='')
print()
22. How many asterisks does the following code fragment print?
for a in range(10, -10, 1):
print('*', end='')
print()
23. How many asterisks does the following code fragment print?
for a in range(10, -10, -1):
print('*', end='')
print()
24. What is printed by the following code fragment?
a=0
while a < 10:
print(a)
a += 1
print()
25. Rewrite the code in the previous question so it uses a for instead of a
while. Your code should behave identically.

26. What is printed by the following code fragment?


a=0
while a > 10:
print(a)
a += 1
print()
27. Rewrite the following code fragment using a break statement and
eliminating the done variable.
Your code should behave identically to this code fragment.
done = False
n, m = 0, 10
while not done and n != m:
n = int(input())
if n < 0:
done = True
print("n =", n)
29. Rewrite the following code fragment so it eliminates the continue statement. Your new code’s
logic
should be simpler than the logic of this fragment.
x = 10
while x > 0:
y = int(input())
if y == 10:
x += 1
continue
x = int(input())
print('x =', x)
30. What is printed by the following code fragment?
a=0
while a < 100:
print(a, end='')
a += 1
print()
31. Modify Listing example 16 (flexibletimestable.py) so that the
it requests a number from the user. It should then print a
multiplication table of the size entered by the user; for
example, if the users enters 15, a 15×15 table should be
printed. Print nothing if the user enters a value lager than 18.
Be sure everything lines up correctly, and the table looks
attractive.
32. Write a Python program that accepts a single integer value entered by the
user. If the value entered is less than one, the program prints nothing. If the
user enters a positive integer, n, the program prints an n×n box drawn with *
characters.
If the users enters 1, for example, the program prints
*
If the user enters a 2, it prints
**
**
An entry of three yields
***
***
***
and so forth. If the user enters 7, it prints
*******
*******
*******
*******
*******
*******
*******
that is, a 7×7 box of * symbols.
33. Write a Python program that allows the user to enter exactly twenty floating-
point values. The program then prints the sum, average (arithmetic mean),
maximum, and minimum of the values entered.
34. Write a Python program that allows the user to enter any number of non-
negative floating-point values. The user terminates the input list with any
negative value. The program then prints the sum, average (arithmetic mean),
maximum, and minimum of the values entered. The terminating negative
value is not used in the computations.
35. Redesign Listing problem (startree.py) so that it draws a sideways tree
pointing right; for example, if the user enters 7, the program would print
*
**
***
****
*****
******
*******
******
*****
****
***
**
*
33. Redesign Listing example 16 (startree.py) so that
it draws a sideways tree pointing left; for example, if
the user enters 7, the program would print
*
**
***
****
*****
******
*******
******
*****
****
***
**
*

Potrebbero piacerti anche