Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
255 views

Python Conditional Statements

The document discusses conditional statements and loops in Python. It explains that conditional statements like if-else statements allow executing code based on whether a condition is met. It provides examples of using if, elif and else statements to check different conditions in a calculator program. It also discusses while and for loops, stating that while loops repeat code while a condition is true and for loops iterate over elements in a specified range or collection.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views

Python Conditional Statements

The document discusses conditional statements and loops in Python. It explains that conditional statements like if-else statements allow executing code based on whether a condition is met. It provides examples of using if, elif and else statements to check different conditions in a calculator program. It also discusses while and for loops, stating that while loops repeat code while a condition is true and for loops iterate over elements in a specified range or collection.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

PYTHON CONDITIONAL STATEMENTS

Python code is normally executed in the order in which it is written. However, there comes
a time when we want to execute a specific code if a condition is met. For this, we rely on
conditional statements. Conditional statements first determine whether a specific condition
exists before executing the code. This awards you the ability to control the flow of the
code and have different lines of codes that are executed only when a certain condition is
met. For example, when creating a calculator app, you may want to check which operator
the user entered and execute specific code based on the operator.

If Statement

In python, a conditional statement uses an if-else statement in the following format. The
first code is executed if the condition is true, otherwise, the program moves and executes
the code provided under the else statement.
#syntax for a conditional statement
if condition:
code to execute if true
else:
code to execute otherwise

To build intuition, let’s start working on our calculator. Imagine that we have a python
program that takes three inputs from the user, num1, operator and num2 and returns the
results depending on the operator. For this, we will need to check which operator the user
entered and execute the relevant part of the function.

We must first prompt the user to enter the two numbers and the operator. Please note
that to get user input, we rely on the python built-in input method. Give Google a visit to
learn about it. By default, the input will be a string so we need to cast it to a float using
float(“string”):
#get user input
#get first number
num1 = float(input("Enter first number: ")
#get operator
op = input("Enter operator: ")
#get second number
num2 = float(input("Enter second number: ")

At this point, our program simply requests the user to enter the three different inputs and
assigns them to the relevant operators. Let’s now define our calculator functions. Create
a python file (simpleCalculator.py) in your preferred editor and let’s get cracking.

code for defining the different calculator functions


For the next step, we will need an if-statement to check whether the operator is an
addition or subtraction sign:
# define an answer variable to hold our solution
answer = 0
# if addition sign
if op == "+":
# call the add function
answer = add(num1, num2)
# print the results
print(num1, "+", num2, "=", answer)
else:
# call the subtract function
answer = subtract(num1, num2)
# print the results
print(num1, "-", num2, "=", answer)

if-elif-else statement

So far, our calculator can only do two functions, addition and subtraction. If we want to
expand its functionality and make use of the other functions we defined, we will need to
use an “elif statement” — short for else if. This will allow us to check for multiple other
conditions before exiting with an else statement. We will use the last condition (else) for
cases where the user enters an invalid arithmetic sign. See the code:
# define an answer variable to hold our solution
answer = 0
# if addition sign
if op == "+":
# call the add function
answer = add(num1, num2)
# print the results
print(num1, "+", num2, "=", answer)
# if subtraction sign
elif op == "-":
# call the subtract function
answer = subtract(num1, num2)
# print the results
print(num1, "-", num2, "=", answer)
# if multiplication sign
elif op == "*":
# call the multiple function
answer = multiply(num1, num2)
# print the results
print(num1, "*", num2, "=", answer)
# if division sign
elif op == "/":
# call the division function
answer = division(num1, num2)
# print the results
print(num1, "/", num2, "=", answer)
# if modulus sign
elif op == "%":
# call the mod function
answer = mod(num1, num2)
# print the results
print(num1, "%", num2, "=", answer)
# if exponential
elif op == "**":
# call the exp function
answer = exp(num1, num2)
# print the results
print(num1, "^", num2, "=", answer)
# if not a recognized arithmatic sign
else:
print("Invalid operator")

It is also possible to put another “if-elif-else statement” inside another if statement. This
is referred to as a “nested if statement”. In fact, nesting allows you to add multiple if-elif-
else statements inside another if statement. For example, we can modify our code to check
if the second number is not zero to avoid division by zero. Modify the code to be as follows:
elif op == "/":
# if second number is zero
if num2 == 0:
print("Error - division by zero")
else:
# call the division function
answer = division(num1, num2)
# print the results
print(num1, "/", num2, "=", answer)
# if modulus sign

PYTHON LOOPS

Like other programming languages, Python also uses a loop but instead of using a range
of different loops it is restricted to only two loops “While loop” and “for loop”.

• While loops are executed based on whether the conditional statement is true or
false.
• For loops are called iterators, it iterates the element based on the condition set
• Python For loops can also be used for a set of various other things (specifying the
collection of elements we want to loop over)
• Breakpoint is used in For Loop to break or terminate the program at any particular
point
• Continue statement will continue to print out the statement, and prints out the
result as per the condition set
• Enumerate function in “for loop” returns the member of the collection that we are
looking at with the index number

What is While Loop?


While Loop is used to repeat a block of code. Instead of running the code block once, It
executes the code block multiple times until a certain condition is met.

How to use “While Loop”


While loop 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
Example:

#
#Example file for working with loops
#
x=0
#define a while loop
while(x <4):
print(x)
x = x+1

Output:

0
1
2
3

• Code Line 4: Variable x is set to 0


• Code Line 7: While loop checks for condition x<4. The current value of x is 0.
Condition is true. Flow of control enters into while Loop
• Code Line 8: Value of x is printed
• Code Line 9: x is incremented by 1. Flow of control goes back to line 7. Now the
value of x is 1 which is less than 4. The condition is true, and again the while loop
is executed. This continues till x becomes 4, and the while condition becomes false.

How to use “For Loop”


In Python, “for loops” are called iterators.

Just like while loop, “For Loop” is also used to repeat the program.

But unlike while loop which depends on condition true or false. “For Loop” depends on
the elements it has to iterate.

Example:

#
#Example file for working with loops
#
x=0
#define a while loop
#while(x <4):
#print x
#x = x+1

#Define a for loop


for x in range(2,7):
print(x)
Output:

2
3
4
5
6
For Loop iterates with number declared in the range.

For example,

For Loop for x in range (2,7)

When this code is executed, it will print the number between 2 and 7 (2,3,4,5,6). In this
code, number 7 is not considered inside the range.

For Loops can also be used for a set of other things and not just number. We will see
thin in next section.

You might also like