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

Unit Ii

The document discusses various input and output functions in Python like input(), print(), eval() and ways to take multiple inputs from the user using split(), map(), list comprehension. It also covers formatting output using print() and control flow statements.

Uploaded by

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

Unit Ii

The document discusses various input and output functions in Python like input(), print(), eval() and ways to take multiple inputs from the user using split(), map(), list comprehension. It also covers formatting output using print() and control flow statements.

Uploaded by

Upendra Neravati
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

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

We can write the code in single line also


print('The sum of Two numbers = ', int(input("Enter num1: "))+
int(input("Enter num2: ")))
Enter num1: 6
Enter num2: 8
The sum of Two numbers = 14

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)

How to read multiple values from the keyboard in a single line:


a) Using split() function
b) Using input () function
c) Using map () function
d) Using List Comprehension
a) Using split() function
 This function helps in getting multiple inputs from users.
 This function generally breaks the given input by the specified separator and in case the
separator is not provided then any white space is considered as a separator.
 This function is generally used to separate a given string into several substrings. However,
you can also use it for taking multiple inputs.
Syntax : input().split(separator, maxsplit)
 separator: This is a delimiter. The string splits at this specified separator. If it is not provided then
any white space is a separator.
 maxsplit: It is a number, which tells us to split the string into a maximum of provided number of
times. If it is not provided then the default is -1 which means there is no limit.
i) Taking two inputs at a time:

a, b = input("Enter 2 variables: ").split()


print("a is: ",a)
print("b is: ",b)
Enter 2 variables: hi there
a is: hi
b is: there
Enter 2 variables: 34 56
a is: 34
b is: 56
Note: As you can see, the input given can be any: int, string, float, etc. We haven’t mentioned the
separator used hence whitespace is considered as default.
ii) Taking Inputs with Separator and Maxsplit defined
x, y, z = input("Enter variables: ").split(",",3)
print(x, y, z)
Enter variables: how,are,you
how are you
x, y, z = input("Enter variables: ").split(",")
print(x,y,z)
Enter variables: how,are,you
how are you
Note: Whether or not maxsplit was defined, the results were the same. For both the above cases only
3 inputs (not more or less can be provided corresponding to defined variables!)
iii) Taking Unlimited Inputs:
x= input("Enter variables: ").split(",")
print(x)
Enter variables: how,are,you,dear
['how', 'are', 'you', 'dear’]
iv) Taking Multiple Inputs As List
Taking multiple inputs at a time and type casting using the list() function.
With Map Function:
Used Map Function (Optional) to convert the input into an integer.
x = list(map(int, input("Enter multiple value: ").split()))
print("List of students: ", x)
Enter multiple value: 67 90 89 54 12 34 09
List of students: [67, 90, 89, 54, 12, 34, 9]
For the above code, because of the use of the map integer function, our input can only be integers
Without Map Function:
x = list(input("Enter multiple value: ").split())
print("List of students: ", x)
Enter multiple value: hey 78 amazing person 2021
List of students: ['hey', '78', 'amazing', 'person', '2021’]
Note: Here as we did not use any map function, the type of input can be any!
b) input ()
You can take multiple inputs in one single line by using the input function several times as shown
below.
#multiple inputs in Python using input
x, y = input("Enter First Name: "), input("Enter Last Name: ")
print("First Name is: ", x)
print("Second Name is: ", y)
Output:
Enter First Name: FACE
Enter Last Name: Prep
First Name is: FACE
Second Name is: Prep
c) map()
map() is another function that will help us take multiple inputs from the user. In general, the syntax
for the map function is the map (fun, iter). Here fun is the function to which the map function passes
each iterable.
Syntax for multiple input using map(): variable 1, variable 2, variable 3 =
map(int,input().split())
An example to take integer input from the user.
#multiple inputs in Python using map
x, y = map(int, input("Enter two values: ").split())
print("First Number is: ", x)
print("Second Number is: ", y)
Output:
Enter two values: 7 1
First Number is: 7
Second Number is: 1

An example to take string input from the user.


#multiple inputs in Python using map
x, y = map(str, input("Enter your first and last name: ").split())
print("First Name is: ", x)
print("Second Name is: ", y)

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

Taking Multiple Inputs at a time:


x = [int(x) for x in input().split()]
print("Number of list is: ", x)
43 12 34 67 09 653 2321 12
Number of list is: [43, 12, 34, 67, 9, 653, 2321, 12]
Taking User-Defined Number of Inputs:
#Inputs of Number of inputs user want to enter:
n = int(input())
# defining empy list:
L= []
# Taking multiple inputs based on n:
for i in range(n):
t = input().split()
print(t)
The result for the above code would be a list with n number of user inputs.

Multiple Input Using Separator

x = [int(x) for x in input().split(",")]


print("Number of list is: ", x)
67,432,11,1,2,3,4
Number of list is: [67, 432, 11, 1, 2, 3, 4]

List Comprehension: Programs

Write a program to find square of odd numbers from range 1 to 20


odd_square = [x ** 2 for x in range(1, 21) if x % 2 == 1]
print(odd_square)
Output: [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

Write a program to find square of even numbers from range 1 to 20.


even_square = [x ** 2 for x in range(1, 21) if x % 2 == 0]
print(even_square)
Output: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

Write a program to find power of 2 from 1 to 10


square = [x ** 2 for x in range(1, 11)] print(square)
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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

Form-2: print() function to print of string argument


print("Mechanical Engineering")
Output: Mechanical Engineering

We can use escape characters also


print("Mechanical\nEngineering")
Mechanical
Engineering
print("Mechanical\tEngineering")
Mechanical Engineering

We can use repetition operator (*) in the string.


print("Mechanical Engineering"*2)
print('RGMCET'*2)
Mechanical EngineeringMechanical Engineering
RGMCETRGMCET
We can use + operator also
print('Mechanical'+'Engineering')
MechanicalEngineering
Note:
If both arguments are string type then + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will get Error
If both arguments are number type then + operator acts as arithmetic addition operator.

**Form-3: print() with variable number of arguments:**

a, b, c = 10,20, 30
print("The values are: ", a, b, c)
The values are: 10 20 30

Form-4: print() with 'sep' attribute: sep' attribute:


By default output values are separated by space. If we want we can specify a separator by using the
"sep" attribute
'sep' means separator.

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

print("The values are: ", a, b, c, sep = ':')


The values are: :10:20:30

print("The values are: ", a, b, c, sep = '-')


The values are: -10-20-30

Form-5: print() with 'end' attribute:


print("Mechanical")
print("Engineering")
Mechanical
Engineering

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.

print("Mechanical", end = ' ')


print("Engineering")

Eg: Program to demonstrate both 'sep' and 'end' attributes.

print(10, 20, 30, sep = ':', end = '**') # output: 10:20:30**Engineering


print("Engineering")

print("Mechanical" + "Engineering") # Concatanation


MechanicalEngineering
print("Mechanical", "Engineering") #',' means space is the separator
Mechanical Engineering

Form-6: print(object) statement:


 We can pass any object (like list,tuple,set etc)as argument to the print() statement.
Syntax : print(objects)
 Here, objects are the values to be printed.
 We can use commas to print multiple variables / values at a time as shown below.
x = "Apple"
y = 10
z = 21.5
print(x, y, z)
Apple 10 21.5
Ex:
list=[1,2,3,4,5]
tuple=(1,2,3,4,5)
set={"mech", 'engg'}
dict={"Mech":1995, "dept":2022}
print(list)
print(tuple)
print(set)
print(dict)

Form-7: print(String, variable list):


We can use print() statement with String and any number of arguments.
Ex:
a = 'Mechanical'
b = 'students'
c = 'python programming class'
print("Hello", a, "Engineering", b)
print("welcome", 'to',c)
Hello Mechanical Engineering students
welcome to python programming class

Form-8: print(formatted string):


Syntax: print("formatted string" %(variable list))

• %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]

Form-9: print() with replacement operator {}


x = -100
y = 300
z = x + y

# normal way old style of printing


print(x, "plus", y, "is", z, "and", x, "is -ve")
# using format
print("{} plus {} is {} and {} is -ve".format(x, y, z, x))
print("{0} plus {1} is {2} and {0} is -ve".format(x, y, z))

# 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.

Conditional Statements (or) Selection Statements


 In Python, condition statements act depending on whether a given condition is true or false.
 You can execute different blocks of codes depending on the outcome of a condition.
 Condition statements are always evaluated to be either True or False.
The following are the types of conditional statements.
 if statement
 if-else
 if-elif-else
 nested if-else
if Statement (One-way):
' if ' statement is used to decide whether a certain statement(s) have to be executed or not.
Syntax:
if condition:
statements
What does the colon ':' operator do in Python?
 The : symbol is also used to start an indent suite of statements in case of if, while, for, def and
class statements
 As slice operator with a sequence:
The : operator slices a part from a sequence object such as list, tuple or string. Ex: >>> a=[1,2,3,4,5]
>>> a[1:3]
[2, 3]

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.

num1 = int(input("Enter a number: "))


num2 = int(input("Enter a number: "))
if num1 > num2:
print("num1 is greater than num2")
else:
print("num2 is greater than num1")
print("The End")
Enter a number: 12
Enter a number: 35
num2 is greater than num1
The End
Ex:
Python Program to Check Whether a String is Palindrome or Not
# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
output:
The string is a palindrome.

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.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
Enter first number: 23
Enter second number: 14
Enter third number: 25
The largest number is 25.0

Ex:
# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# 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.

score = float(input("Enter Score :"))


if score >= 90.0:
print("grade = 'A'")
elif score >= 80.0:
print("grade = 'B'")
elif score >= 70.0:
print("grade = 'C'")
elif score >= 60.0:
print("grade = 'D'")
else:
print("grade = 'F'")
output:
Enter Score :60
grade = 'D'

Looping (while, while-else)


 In Python, iterative statements allow us to execute a block of code
repeatedly as long as the condition is True. We also call it a loop
statements.
 Python provides us the following two loop statements to perform some
actions repeatedly
 for loop
 while loop
for loop (fixed number of times):
• In the syntax, i is the iterating variable, and the range specifies how many times the loop
should run. For example, if a list contains 10 numbers then for loop will execute 10 times to
print each number.
• In each iteration of the loop, the variable i get the current value.

Why use for loop?


• Definite Iteration: When we know how many times we wanted to run a loop, then we use count-
controlled loops such as for loops. It is also known as definite iteration. For example, Calculate
the percentage of 50 students. here we know we need to iterate a loop 50 times (1 iteration for
each student).
• Reduces the code’s complexity: Loop repeats a specific block of code a fixed number of times.
It reduces the repetition of lines of code, thus reducing the complexity of the code. Using for
loops and while loops we can automate and repeat tasks in an efficient manner.
• Loop through sequences: used for iterating over lists, strings, tuples, dictionaries, etc., and
perform various operations on it, based on the conditions specified by the user.
Ex:
To display numbers from 0 to 5
for num in range(0,6):
print(num)
output:
0
1
2
3
4
5
Ex:
numbers = [1, 10, 20, 30, 40, 50]
sum = 0
# Find sum of all the numbers using for loop
for i in numbers:
sum = sum + i
print ("The sum of numbers is", sum) # print sum here
colors = ['red', 'orange', 'green', 'yellow', 'white', 'violet']
for i in colors:
print(i)
# Similarly ierate over the given colors and print the colors
Ex:
To display odd numbers from 0 to 10
for num in range(0,10):
if num%2 !=0:
print(num)
1
3
5
7
9
Ex:
To display even numbers from 0 to 10
for num in range(0,10):
if num%2 ==0:
print(num)
0
2
4
6
8
Ex:
To display numbers from 5 to 1 in descending order.
for num in range(5,0,-1):
print(num)
5
4
3
2
1
Ex: Write a Program to print characters present in the given string

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

# Reversed numbers using reversed() function


list1 = [10, 20, 30, 40]
for num in reversed(list1):
print(num)
Or
numbers = [1, 2, 3, 4]
for i in numbers[::-1]:
print(i)

# Iterating over a tuple


print("\nTuple Iteration")
t = ( "Programming", "is", "fun" )
for i in t:
print(i)

# Iterating over a dictionary


print("\nDictionary Iteration")
d = {"a" : 1, "b" : 2, "c" : 3}
for i in d:
print(i, d[i])
print("\nThe End")

Ex:
# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7
# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
The factorial of 7 is 5040

Steps to Print Pattern in Python


 Decide the number of rows and columns
 There is a typical structure to print any pattern, i.e., the number of rows and columns. We need
to use two loops to print any pattern, i.e., use nested loops.
 The outer loop tells us the number of rows, and the inner loop tells us the column needed to print
the pattern.
 Accept the number of rows from a user using the input() function to decide the size of a pattern.
 Iterate rows
 Next, write an outer loop to Iterate the number of rows using a for loop and range() function.
 Iterate columns
 Next, write the inner loop or nested loop to handle the number of columns. The internal loop
iteration depends on the values of the outer loop.
 Print star or number
 Use the print() function in each iteration of the nested for loop to display the symbol or number
of a pattern (like a star (asterisk *) or number).
 Add new line after each iteration of outer loop
 Add a new line using the print() function after each iteration of the outer loop so that the pattern
display appropriately

Nested for loop


Ex1:
*
* *
* * *
* * * *
* * * * *
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print('*', end = ' ')
print()

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:

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 = ' ')
for j in range(i):
print('*', end = ' ')
print()
Reverse hill pattern:
Enter no.of rows : 6
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
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 = ' ')
for j in range(i,rows-1):
print('*', end = ' ')
print()

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

Double hill pattern:


Enter no.of rows : 6
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
Program:
num = int(input('Enter no.of rows : '))
for i in range(1,num+1):
print(' '*(num-i), end = '')
for j in range(1,i+1):
print('*', end =' ')

print(' '*(num-i), end = '')


for k in range(1,i+1):
print('*', end = ' ')
print()

Ex: Enter a number5


**
**
****
****
******
******
********
********
**********
**********
Program:
n=int(input("Enter a number"))
for i in range(1,2*n+1):
if i%2==0:
print("*"*i,end=" ")
else:
print("*"*(i+1),end=" ")
print()
Ex: Diamond alphabet pattern:
A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A
# diamond alphabet pattern program
n = 5

# Upper triangle shape


for i in range(n):
for j in range(n - i - 1):
print(' ', end='')
for j in range(2 * i + 1):
print(chr(65 + j), end='')
print()

# Lower triangle shape


for i in range(n - 1):
for j in range(i + 1):
print(' ', end='')
for j in range(2*(n - i - 1) - 1):
print(chr(65 + j), end='')
print()

Ex:

Python Program to Check Prime Number


# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
output:
29 is a prime number

Python Program to Check If Two Strings are Anagram


‘Two strings are said to be anagram if we can form one string by arranging the characters of another
string. For example, Race and Care. Here, we can form Race by arranging the characters of Care’.
# program
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
output:
race and care are anagram.

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

Sample Input and Output 2:


Enter a number: -660
The sum is -218130

Ex:
Python Program to Print the Fibonacci sequence
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
output:
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

Transfer Statements: Break, Continue, and Pass


Statement Description

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.

How break statement works:


numbers = [10, 40, 120, 230]
for i in numbers:
if i > 100:
break
print('current number', i)
We used a break statement along with if statement. Whenever a specific condition occurs and a
break statement is encountered inside a loop, the loop is immediately terminated, and the
program control transfer to the next statement following the loop.
Let’s understand the above example iteration by iteration.
In the first iteration of the loop, 10 gets printed, and the condition i > 100 is checked. Since the
value of variable i is 10, the condition becomes false.
In the second iteration of the loop, 40 gets printed again, and the condition i > 100 is checked.
Since the value of i is 40, the condition becomes false.
In the third iteration of the loop, the condition i > 100 becomes true, and the break statement
terminates the loop

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.

How continue statement works:


We used the continue statement along with the if statement. Whenever a specific condition
occurs and the continue statement is encountered inside a loop, the loop immediately skips the
remaining body and moves to the next iteration.
Example: continue statement in for loop
In this example, we will iterate numbers from a list using a for loop and calculate its square. If
we found a number greater than 10, we will not calculate its square and directly jump to the next
number.
Use the if condition with the continue statement. If the condition evaluates to true, then the loop
will move to the next iteration.
Ex:
numbers = [2, 3, 11, 7]
for i in numbers:
print('Current Number is', i)
# skip below statement if number is greater than 10
if i > 10:
continue
square = i * i
print('Square of a current number is', square)
Output:
Current Number is 2
Square of a current number is 4
Current Number is 3
Square of a current number is 9
Current Number is 11
Current Number is 7
Square of a current number is 49

Pass Statement in Python


 In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty.
 If we want to bypass any code pass statement can be used.
 It is beneficial when a statement is required syntactically, but we want we don't want to execute
or execute it later.
 The difference between the comments and pass is that, comments are entirely ignored by the
Python interpreter, where the pass statement is not ignored.
 Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.
 Consider the following example.

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

How to find the index value for particular character


varaible name.index(character)
>>> Name.index('M')
2
>>> Name.index('T')
5
>>> len(Name)
6
>>> Name[len(Name)-1]
'T'
>>> Name[-len(Name)]
'R'
>>>

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.

Syntax: string[start : end : step]


 start - index start at which slicing is started
 end - index at which slicing is ended, end index is exclusive
 step - step value is with which start value gets incremented/decremented.
Note
 The default step value in string slicing is 1.

Strings Slicing: syntax: [starting index : ending index+1]


Form of indexing syntax that extracts substrings from a string, known as string slicing.
-6 -5 -4 -3 -2 -1

R G M C E T

0 1 2 3 4 5

# Get sub-string using start and end values


>>> Name = "RGMCET"
>>> Name[2:5] # Return a sub-string of characters from 2 to 4, excluding 5
'MCE’
# Get sub-string using only end value
>>> Name[:5] # Assumes start value as 0 & step value as 1 ‘RGMCE'
'RGMCE’
# Get sub-string using only Start value
>>> Name[2:] # Assumes end value as length of the string & step value as 1
‘MCET'
'MCET’
# Get entire string using slicing
>>> Name[:] # Returns entire string
'RGMCET'
>>> Name[::] # Returns entire string, same as above
'RGMCET'

# Modify/Custom step value


>>> Name[1:5:2]
‘GC’
# Get Sub-string using end and step value
>>> Name[:5:2] # So it assumes default start value as 0
‘RME’
# Get Sub-string using only step value
>>> Name[::2] # So it assumes default start value as 0
‘RME’
>>> Name[-5:-2]
'GMC'
>>> Name[0:6:2]
'RME'
>>> Name[5:0:-2]
'TCG'
>>> Name[::-1] # Reversing a string
'TECMGR'
>>> Name[5:2]
‘ ‘ # null string, We can solve this problem by step value negative
>>> Name[5:2:-1]
‘TEC’>>> Name[-6:-1:2]
‘RME’
>>> Name[-2:-6]
‘ ‘ # null string, We can solve this problem by
step value negative
>>> Name[-2:-6:-1]
‘ECMG’
Name [3] ='S'
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
Name [3] ='S'
TypeError: 'str' object does not support item assignment
>>> Name = "RGMCET"
>>> Name = Name.replace('C','S')
>>> Name
'RGMSET'
>>>

STRING METHODS
1. Functions of String Data Type

string = 'welcome To Python'


print(string.capitalize()) # used to capitalize first letter of string
print(string.upper()) #used to change entire string to upper case
print(string.lower()) #used to change entire string to lower case.
print(string.title()) #used to change string to title case i.e. first
characters of all the words of string are capitalized.
print(string.swapcase())#used to change lowercase characters into
uppercase and vice versa
print(string.split()) #used to returns a list of words separated by
space
Welcome to python
WELCOME TO PYTHON
welcome to python
Welcome To Python
WELCOME tO pYTHON
['welcome', 'To', 'Python']
a = "hello"
print(a.center(10, '&')) #Here the width is 10 and the string length is 5,
so now we need to fill the remaining width(10 - 5 = 5) with '&' special
character.
b = "Python"
print(b.center(10, '*'))
&&hello&&&
**Python**

2.Methods Of Strings

a = "happy married life happy birthday birthday baby"


#returns the number of occurrences of substring in particular string. If
the substring does not exist, it returns zeroo
print(a.count('happy'))
a = "java is simple"
print(a.replace('java' ,'Python'))
2
Python is simple
java is simple
b = '.'
List_1 = ['www', 'rgmcet', 'com']
#returns a string concatenated with the elements of an iterable. (Here
“List_1” is the iterable)
print(b.join(List_1))
www.rgmcet.com
string = 'Python'
print(string.isupper()) # used to check whether all characters (letters)
of a string are uppercase or not.
print(string.islower()) #used to check whether all characters (letters) of
a string are lowercase or not.
print(string.isalpha()) #used to check whether a string consists of
alphabetic characters only or not.
print(string.isalnum()) #used to check whether a string consists of
alphanumeric characters(both alphabets and digits, but not special
characters).
False
False
True
True
string_1 ='56789'
string_2 = 'rgm03'
print(string_1.isdigit()) #used to check whether a string consists of
digits only or not. If the string contains only digits then it returns
True, otherwise False.
print(string_2.isdigit())
True
False
string_1 = 'Mechanical Engineering'
string_2 =' '
print(string_1.isspace()) #checks whether a string consists of spaces only
or not. If it contains only white spaces then it returns True otherwise
False
print(string_2.isspace())
False
True
string_1 ='Mechanical Engineering'
string_2 ='Rajeev gandhi memorial College of Engineering and technology'
print(string_1.istitle()) #checks whether every word of a string starts
with upper case letter or not.
print(string_2.istitle())
True
False

3. Escape Sequences in Strings

print("hello\npython") # will print result as follows


print("hello\\how are you") # will print result as follows. It returns one
single backslash.
str = "Hello\tPython\nPython is very interesting"
print(str) # will print result as follows
print(repr(str))# Some times we want the escape sequence to be printed as
it is without being interpreted as special.
print(r"Hello\tPython\nPython is very interesting") # We can also use
both 'r'and 'R'. Internally they called repr() method.
print(R"Hello\tPython\nPython is very interesting") # We can also use both
'r'and 'R'. Internally they called repr() method.

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

You might also like