UNIT 2 Python
UNIT 2 Python
The input function in python reads the input as a string, which can then
be converted into other data types, such as integers, floating-point
numbers, or booleans.
• Handling Exceptions
When converting the input into other data types, it is essential to handle
exceptions. If the input provided by the user cannot be converted into the
desired data type, it will cause an error.
• Default Value
The input function also allows us to provide a default value, which will
be used if the user does not provide any input.
Conditional Statements in Python
• Conditional Statements are statements in Python that provide a
choice for the control flow based on a condition.
• It means that the control flow of the Python program will be
decided based on the outcome of the condition.
Types of Conditional Statements in Python
1. If Conditional Statement in Python
2. If else Conditional Statements in Python
3. Nested if..else Conditional Statements in Python
4. If-elif-else Conditional Statements in Python
5. Ternary Expression Conditional Statements in Python
If Conditional Statement in Python
if condition:
# Statements to execute if
# condition is true
# if statement example
if 10 > 5:
print("10 greater than 5")
print("Program ended")
Python supports the standard mathematical logical
conditions:
• 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 utilized in a variety of ways in the if
statement.
Practice Question :Program using ‘if’ statement
1. Python program to illustrate if the number is even using if
statement
2. Program to print the largest of the three numbers.
1.
2.
The if-else statement
• The if-else statement provides an else block combined with
the if statement which is executed in the false case of the
condition.
if condition:
#block of statements
else:
#another block of statements
(else-block)
Practice questions : ‘if-else’ statement
1. Program to check whether a person is eligible to vote or not.
2. Program to check whether a number is even or not.
1.
2.
The elif statement
• The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the true
condition among them.
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
One line if statement:
if a > b: print("a is greater than b“)
•
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 x in animal :
print(x)
# you can understand this as ; for every animal ‘x’ in the list ‘animal’ ,print
the animal ‘x’.
#’x’ is known as the iterator and ‘animals’ is known as the iterable
Output :- cat
dog
penguin
whale
zebra **for and in are both Python keywords**
How to write a for loop in Python
Step 1
Tell Python you want to create a for loop by starting the statement with
for.
Step 2
Write the iterator variable (or loop variable). The iterator takes on each
value in an iterable (for example a list, tuple, or range) in a for loop one
at a time during each iteration of the loop.
**iterable means an object that can be looped over.
String Iteration
or
Python for Loop with Strings
Example
The following example compares each character and displays if it is not a
vowel ('a', 'e', 'i', 'o', 'u').
Text =
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Practice Program :
1. Write a for loop that prints the numbers from 1 to 10, inclusive.
(Hint: There's more than one way to do this)
o/p =
• The range() function has the following syntax −
range(start, stop, step)
Where,
• Start − Starting value of the range. Optional. Default is 0
• Stop − The range goes upto stop-1
• Step − Integers in the range increment by the step value. Option,
default is 1.
• Example :
Output :
PROGRAMS FOR PRACTICE :
• Python program to calculate the sum of all numbers from 1 to a given
number.
• Python program to calculate the sum of all the odd numbers within
the given range.
• Python program to print a multiplication table of a given number.
• Python program to display numbers from a list using a for loop.
• Python program to check if the given string is a palindrome.
• Python program to check if a given number is an Armstrong number
• Python program to check whether a given num is prime number or
not.
• Python program to get the Fibonacci series between 0 to 50
#Taking user input
Prime num inputn = int(input("Enter a number: "))
if inputn > 1:
# check for factors
for i in range(2,inputn):
if (inputn % i) == 0:
print(inputn,"is not a prime number.")
print(i,"times",inputn//i,"is",inputn)
break
else:
print(inputn,"is a prime number.")
#If the input number is less than or equal to 1, then it is not prime
else:
print(inputn,"is not a prime number.")
Algorithm
1.Add integer value to num variable.
2.Then initialize two variables n1 and n2 with value 0 and 1.
3. Check if num value is equal to 1, then print n1 only.
4.Else
1.Print the value of n1 and n2.
2.Then run a for loop from range(2, num) and inside the for loop perform the
following operations.
1.Initialize n3 with value of n1 + n2.
2.Update n1 to n2.
3.Update n2 to n3.
4.At last print n3.
• Tip: We can end a for loop before iterating through all the items by
using a break statement.
The continue Statement
With the continue statement we can stop the current iteration of the
loop, and continue with the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
In the above program, let's see how the pattern is printed.
• First, we get the height of the pyramid rows from the user.
• In the first loop, we iterate from i = 0 to i = rows.
• The second loop runs from j = 0 to i + 1. In each iteration of this loop,
we print i + 1 number of * without a new line. Here, the row number
gives the number of * required to be printed on that row. For example,
in the 2nd row, we print two *. Similarly, in the 3rd row, we print three
*.
• Once the inner loop ends, we print new line and start printing * in a
new line.
Example 4: Inverted half pyramid using *
*****
****
***
**
*
rows = int(input("Enter number of rows: "))
print()
Example : 2
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
print (x,":",numbers[x])
Output :
10 : Ten
20 : Twenty
30 : Thirty
40 : Forty
Example 3:
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.items():
print(x)
Output :
Difference in While and For loop :
• A While loop operates without prior knowledge of iterations
and allows for flexible initialization within its body.
• With the continue statement we can stop the current iteration, and
continue with the next:
Example
• Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i) // print is inside while loop and outside if loop
Pass statement :
• When the user does not know what code to write, So user simply
places a pass at that line.
• When the pass statement is executed, nothing happens, but you
avoid getting an error when empty code is not allowed.
When to use: When you don't know what to code or want to skip
an iteration of a loop.
How it works: The pass statement is executed by skipping past the
loop condition, function, or class.
Why it's useful: It can be used to prevent scripts from crashing,
focus on the structure of a script, or design class architecture
Example 1: Creating Empty Blocks of Code
if x < 0:
# TODO: Handle negative values
pass
else:
# TODO: Handle positive values
pass
In this example, an if statement checks whether x is less than 0. If it is, we
need to handle negative values. However, we have yet to decide what to
do, so we use the pass statement to create an empty code block. Similarly,
we use the pass statement for the else block since we have yet to decide
what to do with positive values
Using pass With Conditional Statement
Eg :- 1
n = 10
print('Hello')
Output :- Hello
Suppose we didn't use pass or just put a comment as:
n = 10
if n > 10:
# write code later
print('Hello')
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Faq :
Q: What is the while loop in Python?
A: The while loop in Python is a control flow statement that allows you
to repeatedly execute a block of code as long as a specified condition is
true. It provides a way to create iterative processes in your program.
print(myList)
Output :-
2.
n = 10
Output :-
3.
myTuple = (10,20,30,40,50,60)
i=0
Output :-
4.
myList = [23,45,12,10,25]
i=0
sum = 0
print(sum)
5.
fruitsList = ["Mango","Apple","Orange","Guava"]
while fruitsList:
print(fruitsList.pop())
print(fruitsList)
Output :-