Python Decision Making and Loops
DECISION MAKING:
If Statement
An if statement consists of a boolean expression followed by one or
more statements.
nested if else statement
An if statement can be followed by an
optional else statement, which
executes when the boolean expression is FALSE.
You can
use one if or else if statement inside another if or else if statement(s).
Ex:
var = 100 #indentation
is important if ( var ==100):
print
"Good bye!"
Else:
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.
if expression: statement(s)
else:
statement(s)
2) a=10
if(a>10):
print("Value of a is greater")
else :
print("Value of a is 10")
3)
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!"
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 expression1: statement(s)
elif expression2: statement(s)
elif expression3: statement(s)
else:
statement(s)
4)
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!"
5)
var1 =
1+2j
print("Type of the variable is Integer")
elif (type(var1) ==
float):
print("Type of the variable is Float")
elif (type(var1) ==
complex)
print("Type of the variable is Complex")
elif (type(var1) ==
bool):
print("Type of the variable is Bool")
elif (type(var1) ==
str):
print("Type of the variable is String")
elif (type(var1) == tuple):
print("Type
of the variable is Tuple") elif (type(var1) == dict):
print("Type
of the variable is Dictionaries")
elif (type(var1) == list):
print("Type
of the variable is List")
17.else:
print("Type
of the variable is Unknown")
6)
x =
raw_input("What is the time?")
if x < 10:
print "Good morning" elif x<12:
print "Soon
time for lunch"
elif x<18:
print "Good day"
elif x<22:
print "Good
evening"
else:
print "Good night"
7)
total = int(raw_input('What is the total amount for your online shopping?')) country =
raw_input('Shipping within the US or Canada?')
if country == "US": if total <= 50:
print "Shipping Costs $6.00" elif total <= 100:
print "Shipping Costs $9.00" elif total <= 150:
print
"Shipping Costs $12.00"
else:
print "FREE"
if country == "Canada": if total <= 50:
print "Shipping Costs $8.00" elif total <= 100:
print "Shipping Costs $12.00" elif total <= 150:
print "Shipping Costs $15.00" else:
print
"FREE"
9)
allowed_users
= ['bill', 'steve']
# Get the username from a prompt
username = raw_input("What is
your login? : ")
# Control if the user belongs to allowed_users if username in
allowed_users:
print
"Access granted"
else:
print "Access denied"
10)
age =
38
1. if
(age >= 11):
2. print
("You are eligible to see the
Football match.") 3. if (age
<= 20 or age >= 60):
4.
print("Ticket price is $12")
5.
else:
6.
print("Tic kit price is $20")
7.
else:
8.
print ("You're
not eligible to buy a ticket.")
LOOPS:
In general, statements are executed
sequentially: The first statement in a function is executed first, followed by
the second, and so on. There may be a situation when you need to execute a block
of code several number of times.
Programming languages provide various control
structures that allow for more complicated execution paths.
A loop statement allows us to execute a
statement or group of statements multiple times
Loop Type
|
Description
|
Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing the loop body.
|
|
Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
|
|
You can use one or more loop inside any another while, for or
do..while loop.
|
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. Click the following links to check
their detail.
Control Statement
|
Description
|
Terminates the loop statement and transfers execution to the
statement immediately following the loop.
|
|
Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
|
|
The pass statement in Python is used when a statement is
required syntactically but you do not want any command or code to execute.
|
For Loop:
iteration
statement, which allows a code block to be repeated a certain number of
times. .
for <variable>
in <sequence>:
<statements>
else:
<statements>
Example of a
simple for loop in Python:
1)
>>>
languages = ["C", "C++", "Perl",
"Python"]
>>> for
x in languages:
... print(x)
...
C
C++
Perl
Python
>>>
2)
edibles =
["ham", "spam","eggs","nuts"]
for food in
edibles:
if food == "spam":
print("No more spam please!")
break
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally,
I finished stuffing myself")
$ python for.py
Great,
delicious ham
No more spam
please!
Finally, I
finished stuffing myself
3)
edibles =
["ham", "spam","eggs","nuts"]
for food in
edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally,
I finished stuffing myself")
Great,
delicious ham
No more spam
please!
Great, delicious
eggs
Great,
delicious nuts
I am so glad:
No spam!
Finally, I
finished stuffing myself
>>
The built-in
function range() is the right function to iterate over a sequence of numbers.
It generates an iterator of arithmetic progressions:
Example:
>>> range(10)
range(0, 10)
>>>
list(range(10))
[0, 1, 2, 3, 4,
5, 6, 7, 8, 9]
>>>
Syntax;
The built-in
function range() is the right function to iterate over a sequence of numbers.
It generates an iterator of arithmetic progressions:
Example:
>>>
range(10)
range(0, 10)
>>>
list(range(10))
[0, 1, 2, 3, 4,
5, 6, 7, 8, 9]
>>>
Ex:
>>>
list(range(42,-12,-7))
[42, 35, 28,
21, 14, 7, 0, -7]
Ex:
n = 100
sum = 0
for counter in
range(1,n+1):
sum = sum + counter
print("Sum
of 1 until %d: %d" % (n,sum))
Whileloop
does the exactly same thing what "if statement" does, but instead of
running the code block once, they jump back to the point where it began the
code and repeats the whole process again.
Syntax
While expression:
Statement:
Ex:
x=0
while (x<4):
print x
x= x+1
o/p:
0
1
2
3
Comments
Post a Comment