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

Pythone

The document talks about flow control in Python programs using conditional statements like if, else, elif and also loops like for and while loops. It explains how to use conditional blocks, loops on different data types like lists, strings with examples.

Uploaded by

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

Pythone

The document talks about flow control in Python programs using conditional statements like if, else, elif and also loops like for and while loops. It explains how to use conditional blocks, loops on different data types like lists, strings with examples.

Uploaded by

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

UNIT 2- Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops

in python, For loop using ranges, string, list and dictionaries. Use of while loops in python,
Loop manipulation using pass, continue, break and else. Programming using Python
conditional and loop blocks.

A program executes a series of coded instructions to perform a task. Flow control refers to the
order in which these instructions are executed.

Conditional Statements: Conditional statements, also known as if statements, allow us to


evaluate a condition and execute a block of code in response.

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.

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

b is greater than a

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")

O/P: 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")
O/P:

a is greater than b

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

One line if statement:

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

Example: a is greater than b

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")
O/P: =

Nested If

You can have if statements inside if statements, this is called nested if statements.

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

O/P:

Above ten,
and also above 20!

Python For Loops:


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.

for Loop Syntax


for val in sequence:
# statement(s)

Example:
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
O/p:

apple
banana
cherry
For loop using ranges:

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):
print(x)

O/P:

0
1
2
3
4
5

range(6) is not the values of 0 to 6, but the values 0 to 5.

Syntax of Python range() function


Syntax: range(start, stop, step)
Parameter :
 start: [ optional ] start value of the sequence
 stop: next value after the end value of the sequence
 step: [ optional ] integer value, denoting the difference between any two numbers in the
sequence
Python range() function takes can be initialized in 3 ways.
 range (stop) takes one argument.
 range (start, stop) takes two arguments.
 range (start, stop, step) takes three arguments.

Python range (stop)


When the user call range() with one argument, the user will get a series of numbers that
starts at 0 and includes every whole number up to, but not including, the number that the
user has provided as the stop.

Python range (start, stop)


When the user call range() with two arguments, the user gets to decide not only where the
series of numbers stops but also where it starts, so the user doesn’t have to start at 0 all the
time
Python range (start, stop, step)
When the user call range() with three arguments, the user can choose not only where the
series of numbers will start and stop, but also how big the difference will be between one
number and the next

If a user wants to increment, then the user needs steps to be a positive number.

# incremented by 4
for i in range(0, 30, 4):
print(i, end=" ")
print()

O/P: 0 4 8 12 16 20 24 28

If a user wants to decrement, then the user needs steps to be a negative number.

# incremented by -2
for i in range(25, 2, -2):
print(i, end=" ")
print()

O/p: 25 23 21 19 17 15 13 11 9 7 5 3

Python range() with Float Values

Python range() function doesn’t support float numbers. i.e. user cannot use floating-point or
non-integer numbers in any of its arguments. Users can use only integer numbers.
# using a float number
for i in range(3.3):
print(i)
O/P:

TypeError: 'float' object cannot be interpreted as an integer

Some points:

 All arguments must be integers. Users can not pass a string or float number or any other
type in a start, stop, and step argument of a range().
 All three arguments can be positive or negative.
 The step value must not be zero. If a step is zero, python raises a ValueError exception.

Python String:

Python string is the collection of the characters. In Python, strings can be created by enclosing
the character or the sequence of characters in the quotes. Python allows us to use single
quotes, double quotes, or triple quotes to create the string.

Consider the following example in Python to create a string.

#string
str = "Hi Python !"
print(str)

O/P: Hi Python !

In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.

Strings indexing and splitting:

Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given in the below figure.

Example:

str = "HELLO"
print(str[6])

O/P:
IndexError: string index out of range

The slice operator [] is used to access the individual characters of the string. However, we can
use the : (colon) operator in Python to access the substring from the given string. Consider the
following example.

We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.
String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

O/P:

Helloworld

Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

O/P:

Hello World

STRING FORMAT:

We cannot combine strings and numbers like this:

Example:

age = 36
txt = "My name is John, I am " + age
print(txt)

O/P:

Traceback (most recent call last):


File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:

Example
Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

O/P: My name is John, and I am 36

You might also like