Unit Ii
Unit Ii
Syllabus:
Input and Output statements: input() function, reading multiple values from the keyboard in a single
line, print() function, ‘sep’ and ‘end’ attributes, Printing formatted string, replacement operator ({}).
Control flow statements: Conditional statements. Iterative statements. Transfer statements.
Strings: Operations on string, String slicing, important methods used on string.
Input ( ):
input() function can be used to read data directly in our required format.
In Python3, we have only the input() method and the raw_input() method (Python2) is not
available.
Every input value is treated as str type only.
Why does input() in Python 3 give priority to string type as return type?
Reason: The most commonly used type in any programming language is str type, that's why
they gave priority to str type as the default return type of input() function.
Ex1:
num1 = input("Enter num1: ")
num2 = input("Enter num2: ")
print('The sum of two numbers =', num1+num2)
output:
Enter num1: 15
Enter num2: 50
The sum of two numbers = 1550
Ex2:
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
print('The sum of Two numbers = ', num1+num2)
output:
Enter num1: 5
Enter num2: 6
The sum of Two numbers = 11
Ex3:
num1 = float(input("Enter num1: "))
num2 = float(input("Enter num2: "))
print('The sum of two numbers =', num1+num2)
output:
Enter num1: 5.2
Enter num2: 3
The sum of two numbers = 8.2
Write a program to read Employee data from the keyboard and print that data.
Employee_Number = int(input("Enter Employee No:"))
Employee_Name = input("Enter Employee Name:")
Employee_salary = float(input("Enter Employee Salary:"))
Employee_address = input("Enter Employee Address:")
Employee_marital_status = bool(input("Employee Married or Not Married:"))
print("Please Confirm your provided Information")
print("Employee No :",Employee_Number)
print("Employee Name :",Employee_Name)
print("Employee Salary :",Employee_salary)
print("Employee Address :",Employee_address)
print("Employee Married ? :", Employee_marital_status)
d) List Comprehension
List data types also help in taking multiple inputs from the user at a time. The syntax for creating a
list and storing the input in it is
x, y=[x for x in input("Enter two values: ").split()]
List allows you to take multiple inputs of different data type at a time. The below example will help
you understand better.
#multiple inputs in Python using list comprehension
x, y = [x for x in input("Enter your name and age: ").split(",")]
print("Your name is: ", x)
print("Your age is: ", y)
Output:
Enter your name and age: FACE Prep, 8
Your name is: FACE Prep
Your age is: 8
Explanation :
Here, we are using only one input function (i.e., input("Enter Your name and age:")). So whatever
you provide is treated as only one string.
Suppose, you are providing input as Face Prep, 20, this is treated as a single string.
If you want to split that string into multiple values, then we are required to use the split() function.
If we want to split the given string (i.e., Face Prep 20) with respect to space, then the code will be as
follows:
input(("Enter Your name and age:").split()
Here, we are passing an argument comma to split() function,
Now this single string(i.e., Face Prep, 20) is splitted into a list of two string values.
This concept is known as a list comprehension.
x,y = [x for x in input(("Enter Your name and age: ").split()] ===> it assigns Face Prep to x and
20 to y. This concept is called list unpacking.
2 Inputs at a Time:
x,y = [int(x) for x in input("Enter 2 values: ").split()]
print("x is ",x)
print("y is",y)
Enter 2 values: 6 78
x is 6
y is 78
x,y = [int(x) for x in input().split()]
print("x is ",x)
print("y is",y)
78 90
x is 78
y is 90
eval():
eval() Function is a single function that is the replacement of all the typecasting functions in Python.
If you provide an expression as a string type, eval Function take a String and evaluate the Result.
Eg:
x = eval('10+20+30')
print(x)
Output: 60
Eg:
x = eval(input('Enter Expression'))
Enter Expression: 10+2*3/4
Output: 11.5
Output function: print()
We can use print() function to display output to the console for end user
sake.
Multiple forms are there related to print() function.
Form-1:print() without any argument
Just it prints new line character (i.e.,\n)
Ex1:
print("Mechanical Engineering")
print("RGMCET: ")
Output:
Mechanical Engineering
RGMCET
Ex2:
print("Mechanical Engineering")
print()
print("RGMCET")
Output:
Mechanical Engineering
RGMCET
a, b, c = 10,20, 30
print("The values are: ", a, b, c)
The values are: 10 20 30
Ex1:
a, b, c = 10,20, 30
print("The values are: ", a, b, c)
The values are: 10 20 30
print("The values are: ", a, b, c, sep = '')
The values are: 102030
print("The values are: ", a, b, c, sep = ' ')
The values are: 10 20 30
Ex2:
print("The values are: ", a, b, c, sep = ',')
The values are: ,10,20,30
default value of 'end' attribute is newline character. (That means, if there is no end attribute,
automatically newline character will be printed)
If we want to output in the same line with space, we need to use the end attribute.
• %i====>int
• %d====>int
• %f=====>float
• %s======>String type
Ex:
a=10
b=20.5
c=30.3
s= "Hello Dear"
l=[10, 20, 50, 60]
print("a value is %i" %a)
print("b value is %f and c value is %f" %(b,c))
print("Hi %s....your items:%s" %(s,l))
output:
a value is 10
b value is 20.500000 and c value is 30.300000
Hi Hello Dear....your items:[10, 20, 50, 60]
# using f-string
print(f'{x} plus {y} is {z} and {x} is -ve')
Ex:
a,b,c,d = 10,20,30,40 # print a=10,b=20,c=30,d=40
print('a = {},b = {},c = {},d = {}'.format(a,b,c,d))
Flow Control Statements: Introduction
By default statements in a program are executed sequentially.
While executing the code,
We may require to skip the execution of some statements,
We may want to execute two or more blocks of statements exclusively,
We may need to execute a block of statements repeatedly,
We may need to direct the program's flow to another part of your program without
evaluating conditions.
In such cases, control structures become handy. Control structures are mainly used to control the
flow of execution. They are used for decision making which means we execute code only if
certain criteria is matching.
Indentation:
Python identifies code-blocks using indentation.
All the statements which need to be executed when the condition is True, should be placed
after 'if condition:' preceded by one tab(generally 4 spaces).
All the statements after 'if' statement with one tab indentation, are considered as if block
Ex:
number = int(input("Enter a number"))
if number >= 0:
print("The number entered by the user is a positive number")
print("The number entered by the user is a neither zero nor a positive
number")
In the above example, if the number is positive or zero then only 'if' block will get executed
Ex:
name = input("Enter name: ")
if name == "Mechanical":
print("Welcome to Mechanical Engineering")
print("Hi")
Program on if statement
#Program to illustrate simple if statement
num = int(input("Enter a number: "))
if (num % 3 == 0):
print('Given number {} is divisible by 3'.format(num))
print("End of program")
if-else
When we want to execute two blocks of code exclusively, we use the 'if-else' statement. Only one
block of code will be executed all the time.
Syntax:
if condition:
statements
else:
statements
Ex:
name = input("Enter name: ")
if name == "Mechanical":
print("Hello Good Morning to Mechanical Engineering")
else :
print("Hi students")
print("How are You")
Program 1:
Find the greatest number between two given numbers.
Another way:
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
output:
Yes
if-elif-else Statement:
When we have multiple exclusive cases, we use 'if-elif ladder'. Only one block of code will be
executed at any time.
Syntax:
if condition:
statements
elif condition:
statements
elif condition:
statements
.
.
.
else:
statements
Ex:
Program to print the greatest number among three numbers.
Ex:
# Python program to check if year is a leap year or not
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Output:
2000 is a leap year
Ex:
Program to print the grade assigned to the obtained marks.
str = "MECHANICAL"
for x in str:
print(x)
M
E
C
H
A
N
I
C
A
L
Example: Calculate the average of list of numbers
numbers = [10, 20, 30, 40, 50] #numbers = eval(input("Enter list"))
# definite iteration
# run loop 5 times because list contains 5 items
sum = 0
for i in numbers:
sum = sum + i
list_size = len(numbers)
average = sum / list_size
print("Sum of List of numbers: ", sum)
print("Average of List of numbers: ", average)
output:
Sum of List of numbers: 150
Average of List of numbers: 30.0
Ex:
# Python program to find the factorial of a number provided by the user.
factorial = 1
Ex2:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
#for j in range(rows-i):
for j in range(i, rows):
print('*', end = ' ')
print()
Ex3:
*
* *
* * *
* * * *
* * * * *
* * * * * *
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i,rows):
print(' ', end = ' ')
for j in range(i+1):
print('*', end = ' ')
print()
Ex:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
print()
Hill pattern:
Enter no.of rows : 6
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
Program:
Diamond pattern:
Enter no.of rows : 6
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
rows = int(input('Enter no.of rows : '))
for i in range(rows-1):
for j in range(i,rows):
print(' ', end = ' ')
for j in range(i+1):
print('*', end = ' ')
for j in range(i):
print('*', end = ' ')
print()
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
for j in range(i,rows-1):
print('*', end = ' ')
print()
Ex:
num = 29
While loop:
'while' loop is used to execute a block of statements repeatedly as long as a condition is true. Once the
condition is false, the loop stops execution and control goes immediate next statement after while
block.
The while statement checks the condition. The condition must return a boolean value. Either
True or False.
Next, If the condition evaluates to true, the while statement executes the statements present
inside its block.
The while statement continues checking the condition in each iteration and keeps executing its
block until the condition becomes false.
Why and When to Use while Loop in Python:
• Automate and repeat tasks.: As we know, while loops execute blocks of code over and over again
until the condition is met it allows us to automate and repeat tasks in an efficient manner.
• Indefinite Iteration: The while loop will run as often as necessary to complete a particular task.
When the user doesn’t know the number of iterations before execution, while loop is used instead
of a for loop
• Reduce complexity: while loop is easy to write. using the loop, we don’t need to write the
statements again and again. Instead, we can write statements we wanted to execute again and
again inside the body of the loop thus, reducing the complexity of the code
• Infinite loop: If the code inside the while loop doesn’t modify the variables being tested in the
loop condition, the loop will run forever.
Ex:
To print numbers from 1 to 5 by using while loop
x=1
while x <=5:
print(x)
x=x+1
To display the sum of first n numbers
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)
Ex: # Python program to find the sum of integers between 0 and n where n
is provided by user
num = int(input("Enter a number: "))
s = 0
if (num >= 0):
while (num >= 0):
s = s + num
num = num - 1
print('The sum is {}'.format(s))
elif (num < 0):
while (num < 0):
s = s + num
num = num + 1
print('The sum is {}'.format(s))
Sample Input and Output 1:
Enter a number: 250
The sum is 31375
Ex:
Python Program to Print the Fibonacci sequence
# Program to display the Fibonacci sequence up to n-th term
break Terminate the current loop. Use the break statement to come out of the loop instantly.
continue Skip the current iteration of a loop and move to the next iteration
Do nothing. Ignore the condition in which it occurred and proceed to run the program
pass
as usual
Break Statement in Python
• The break statement is used inside the loop to exit out of the loop (it may be for or while). In
Python, when a break statement is encountered/written inside a loop, the loop is immediately
terminated/executed, and the program control transfer to the next statement following the loop,
'else' will not be executed. It reduces execution time.
• For example, you are searching a specific email inside a file. You started reading a file line by
line using a loop. When you found an email, you can stop the loop using the break statement.
Continue Statement
The continue statement skip the current iteration and move to the next iteration. In Python, when
the continue statement is encountered inside the loop, it skips all the statements below it and
immediately jumps to the next iteration.
In some situations, it is helpful to skip executing some statement inside a loop’s body if a
particular condition occurs and directly move to the next iteration.
Ex:
for i in [12,3,4,5]:
if i==4:
pass
print('this is pass block',i)
print(i)
Ex:
# pass is just a placeholder for
# we will adde functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass
Indexing in strings
Indexing: Indexing is used to obtain individual elements from an ordered set data.
Individual elements are accessed directly by specifying the string name followed by a number in
square brackets ([]).
String indexing in Python is zero-based: the first character in the string has index 0, the next has
index 1, and so on. The index of the last character will be the length of the string minus one.
Python supports both positive indexing and negative indexing.
As we are already discussed, positive indexing moves in forward direction of string and starts from
0.
Negative indexing moves in reverse direction of string and starts from -1.
-6 -5 -4 -3 -2 -1
R G M C E T
0 1 2 3 4 5
Name = "RGMCET"
>>> Name[0]
'R'
>>> Name[3]
'C'
>>> Name[-1]
'T'
>>> Name[-4]
'M'
>>> Name[6]
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
Name[6]
IndexError: string index out of range
>>> Name[-7]
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
Name[-7]
IndexError: string index out of range
>>>
STRING SLICING
• Slicing: Slicing is used to obtain a sequence of elements.
• Slicing is a technique of extracting sub-string or a set of characters that form a string.
Individual characters in a string can be accessed using square brackets and indexing.
R G M C E T
0 1 2 3 4 5
STRING METHODS
1. Functions of String Data Type
2.Methods Of Strings
hello
python
hello\how are you
Hello Python
Python is very interesting
'Hello\tPython\nPython is very interesting'
Hello\tPython\nPython is very interesting
Hello\tPython\nPython is very interesting
4. Methods of strings
#startswith(substring)
string = 'department of mechanical engineering'
print(string.startswith('m')) #checks whether the main string starts with
given sub string. If yes it returns True, otherwise False.
print(string.endswith('g')) # checks whether the string ends with the
substring or not.
print(len(string)) # returns the length of the string or to find the
number of characters present in the string
print(min(string)) # returns the minimum character in the string
print(max(string)) # returns the maximum character in the string
print(string.find('of')) #returns the index of the first occurrence of the
substring, if it is found, otherwise it returns -1
print(string.rfind('e')) #The rfind() method finds/returns the index of
the last occurrence of the specified value/substring, if it is found,
otherwise it returns -1.
print(string.index('o')) #The index() method is almost the same as the
find() method, the only difference is that the index method will get
ValueError, if specified substring is not available.
print(string.rindex('ment')) #Python string method rindex() returns the
last index where the substring str is found, or raises an exception if no
such index exists.
False
True
36
t
11
31
11
6
# Removing spaces from the string
string = ' department of mechanical engineering '
print(string.strip()) #used To remove spaces both sides
print(string.lstrip()) #used To remove blank spaces present at the
beginning of the string (i.e.,left hand side)
print(string.rstrip()) #used To remove blank spaces present at end of the
string (i.e.,right hand side)
department of mechanical engineering
department of mechanical engineering
department of mechanical engineering