knc402 Python Programming UNIT-II

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

PYTHON PROGRAMMING

UNIT-II

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if


statements" and loops.

An "if statement" is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif
The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding
conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.

Example
One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:

Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And
The and keyword is a logical operator, and is used to combine conditional
statements:

Example
Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional
statements:

Example
Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the
conditional statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid getting an
error.
Example
a = 33
b = 200

if b > a:
pass
Expression Evaluation
1. In Python actions are performed in two forms :

a. Expression evaluation,
b. Statement execution.

2. The key difference between these two forms is that expression evaluation
returns a value whereas statement execution does not return any value.
3. A Python program contains one or more statements. A statement contains
zero or more expressions.
4. Python executes a statement by evaluating its expressions to values one
by one.
5. Python evaluates an expression by evaluating the sub-expressions and
substituting their values.
For example :

>>> program = ‚Hello Python‛

>>> program

‘Hello Python’ #Output

>>> print program

Hello Python #Output

6. An expression is not always a mathematical expression in Python. A value


by itself is a simple expression, and so is a variable.
7. In the given example, we assigned a value “Hello Python” to the variable
program. Now, when we type only program, we get the output „Hello
Python‟. This is the term we typed when we assigned a value to the
variable. When we use a print statement with program it gives the value of
the variable i.e., the value after removing quotes.

Float Representation
1. Floating point representations vary from machine to machine.
2. The float type in Python represents the floating-point number.
3. Float is used to represent real numbers and is written with a decimal point
dividing the integer and fractional parts.
4. For example: 97.98, 32.3 + e18, – 32.54e100 all are floating point
numbers.
5. Python float values are represented as 64-bit double-precision values.
6. The maximum value any floating-point number can be is approx 1.8 ×
10308
7. Any number greater than this will be indicated by the string inf in Python.
8. Floating-point numbers are represented in computer hardware as base 2
(binary) fractions.
9. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000,
and in the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8.
For example :

# Python code to demonstrate float values.

Print(1.7e308)

# greater than 1.8 * 10^308

# will print ‘inf’

print(1.82e308)

Output :
1.7e+308
inf
Loop
1. A loop is a programming structure that repeats a sequence of instructions
until a specific condition is met.
2. A loop statement allows us to execute a statement or group of statements
multiple times.
3. Python programming language provides following types of loops to handle
looping requirements:
a. For

b. While

c. Nested

4. Purpose : The purpose of loops is to repeat the same, or similar, code a


number of times. This number of times could be specified to a certain
number, or the number of times could be dictated by a certain condition
being met.
5. Working : Consider the flow chart for a loop execution :

a) In the flow chart if the test condition is true, then the loop is
executed, and if it is false then the execution breaks out of the
loop.
b) After the loop is successfully executed the execution again starts
from the loop entry and again checks for the test condition, and
this keeps on repeating until the condition is false.
While Loop
1. While loop statements in Python are used to repeatedly execute a certain
statement as long as the condition provided in the while loop statement is
true.
2. While loops let the program control to iterate over a block of code.
3. Syntax :
while test_expression:

body of while

4. Flow chart :

5. Working :
a. The program first evaluates the while loop condition.
b. If it is true, then the program enters the loop and executes the body
of the while loop.
c. It continues to execute the body of the while loop as long as the
condition is true.
d. When it is false, the program comes out of the loop and stops
repeating the body of the while loop.
For example :

>>>count = 0

while (count < 9) :

print ‘The count is :’, count

count = count + 1

Output :
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
For loop
1. For loop in python is used to execute a block of statements or code several
times until the given condition becomes false.
2. We use for loop when we know the number of times to iterate.
3. Syntax :
for variable in sequence:
Body of for loop
4. Flow chart :
For example :

i = 1

for i in range(1, 8) :

print 2*i

Output :
2
4
6
8
10
12
14
Nested Loop.
1. Loop defined within another loop is known as nested loops.
2. Nested loops are the loops that are nested inside an existing loop, that is,
nested loops are the body of another loop.
3. Syntax :
for condition1 :
for condition2 :
Body of for loop
3. For example :
# Running outer loop from 2 to 3

for i in range(2, 4):


# Printing inside the outer loop
# Running inner loop from 1 to 10
for j in range(1, 11):
# Printing inside the inner loop
print(i, "*", j, "=", i*j)
# Printing inside the outer loop
print()

Output :
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Break Statement

1. The break keyword terminates the loop and transfers the control to the end
of the loop.
2. While loops, for loops can also be prematurely terminated using the break
statement.
3. The break statement exits from the loop and transfers the execution from
the loop to the statement that is immediately following the loop.
For example :
count = 2
while True :
print count
count = count + 2
if count > 12 :
break # breaks the loop

Output :
2
4
6
8
10

Continue Statement

1. The continue statement causes execution to immediately continue at the


start of the loop, it skips the execution of the remaining body part of the
loop.
2. The continue keyword terminates the ongoing iteration and transfers the
control to the top of the loop and the loop condition is evaluated again. If
the condition is true, then the next iteration takes place.
3. Just as with while loops, the continue statement can also be used in
Python for loops
4. For example :

for i in range (1, 10) :

if i % 2 != 0 :

continue # if condition becomes true, it skips the print part

print i

OUTPUT
2
4
6
8

You might also like