Practical Guide and Programs

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 48

PRACTICAL GUIDE AND PROGRAMS

Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows programmers to express
their concepts in fewer lines of code.

Keywords are some predefined and reserved words in python that have special meanings.
Keywords are used to define the syntax of the coding.
Identifier is a name used to identify a variable, function, class, module, etc. The identifier is a
combination of character digits and underscore. The identifier should start with a character or
Underscore then use a digit. The characters are A-Z or a-z, an Underscore ( _ ) , and digit (0-9). we
should not use special characters ( #, @, $, %, ! ) in identifiers. 
Examples of valid identifiers:
var1
_var1
_1_var
var_1
Examples of invalid identifiers
!var1
1var
1_var
var#1

Total Python keywords


Keywords                                                                            Description

This is a logical operator it returns true if both the operands are true else return
and false.

This is also a logical operator it returns true if anyone operand is true else return
Or false.

This is again a logical operator it returns True if the operand is false else return
not false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement the elif statement is


elif executed if the previous conditions were not true

Else is used with if and elif conditional statement the else block is executed if the
else given condition is not true.
Keywords                                                                            Description

for This is created for a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

This function is used for debugging purposes. Usually used to check the correctness
assert of code

class It helps us to define a class.

continue It continues to the next iteration of a loop

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is use with exceptions, a block of code that will be executed no matter if
finally there is an exception or not.
Keywords                                                                            Description

from The form is used to import specific parts of any module.

global This declares a global variable.

import This is used to import a module.

in It’s used to check if a value is present in a list, tuple, etc, or not.

is This is used to check if the two variables are equal or not.

None This is a special constant used to denote a null value or avoid. It’s important to
remember, 0, any empty container(e.g empty list) do not compute to None

nonlocal It’s declared a non-local variable.

raise This raises an exception

yield It’s ends a function and returns a generator.

Data Structures
Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.
List is the most basic Data Structure in python. List is a mutable data structure i.e items can be
added to list later after the list creation. It’s like you are going to shop at the local market and
made a list of some items and later on you can add more and more items to the list.
append() function is used to add data to the list.

# Python program to illustrate a list 


  
# creates a empty list
nums = [] 
  
# appending data in list
nums.append(21)
nums.append(40.5)
nums.append("String")
  
print(nums)

Output:
[21, 40.5, String]
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments
Input and Output
In this section, we will learn how to take input from the user and hence manipulate it or simply
display it. input() function is used to take input from the user.

# Python program to illustrate


# getting input from user
name = input("Enter your name: ") 
  
# user entered the name 'harssh'
print("hello", name)

Output:
hello harssh

# Python3 program to get input from user


  
# accepting integer from the user
# the return type of input() function is string ,
# so we need to convert the input to integer
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
  
num3 = num1 * num2
print("Product is: ", num3)

Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
Selection
Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)

# Python program to illustrate


# selection statement
  
num1 = 34
if(num1>12):
    print("Num1 is good")
elif(num1>35):
    print("Num2 is not gooooo....")
else:
    print("Num2 is great")

Output:
Num1 is good
input ( prompt )
input (): This function first takes the input from the user and converts it into a string. The type
of the returned object always will be <type ‘str’>. It does not evaluate the expression it just
returns the complete statement as String. For example, Python provides a built-in function called
input which takes the input from the user. When the input function is called it stops the program
and waits for the user’s input. When the user presses enter, the program resumes and returns
what the user typed. 
Syntax:
inp = input('STATEMENT')

Example:
1. >>> name = input('What is your name?\n') # \n ---> newline ---> It causes a line break
>>> What is your name?
Ram
>>> print(name)
Ram

# ---> comment in python


Taking String as an input:
Python3

name = input('What is your name?\n')     # \n ---> newline 


---> It causes a line break
print(name)

How the input function works in Python : 


 
When input() function executes program flow will be stopped until the user has given input.
The text or message displayed on the output screen to ask a user to enter an input value is
optional i.e. the prompt, which will be printed on the screen is optional.
Whatever you enter as input, the input function converts it into a string. if you enter an integer
value still input() function converts it into a string. You need to explicitly convert it into an integer
in your code using typecasting. 
Using split() method : 
This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator. Generally, users use a
split() method to split a Python string but one can use it in taking multiple inputs.
Syntax : 
input().split(separator, maxsplit)
Example : 
Python3

# Python program showing how to


# multiple input using split
  
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
print()
  
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
print()
  
# taking two inputs at a time
a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a,
b))
print()
  
# taking multiple inputs at a time 
# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of students: ", x)

Output: 
 

Python print() function prints the message to the screen or any other standard output
device.
Syntax: 
print(value(s), sep= ' ', end = '\n', file=file, flush=flush)
Parameters: 
value(s): Any value, and as many as you like. Will be converted to a string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default:
False
Return Type: It returns output to the screen.
Though it is not necessary to pass arguments in the print() function, it requires an empty
parenthesis at the end that tells python to execute the function rather calling it by name. Now,
let’s explore the optional arguments that can be used with the print() function.
String Literals
String literals in python’s print statement are primarily used to format or design how a specific
string appears when printed using the print() function.
\n : This string literal is used to add a new blank line while printing a statement.
“” : An empty quote (“”) is used to print an empty line.

Example : Using print() function in Python


Python3

# Python 3.x program showing


# how to print data on
# a screen
 
# One object is passed
print("GeeksForGeeks")
 
x =5
# Two objects are passed
print("x =", x)
 
# code for disabling the softspace feature
print('G', 'F', 'G', sep='')
 
# using end argument
print("Python", end='@')
print("GeeksforGeeks")

Python if...else
Statement
In computer programming, we use
the  if  statement to run a block code only
when a certain condition is met.
For example, assigning grades (A, B,
C) based on marks obtained by a student.
1. if the percentage is above 90, assign
grade A
2. if the percentage is above 75, assign
grade B
3. if the percentage is above 65, assign
grade C

In Python, there are three forms of


the  if...else  statement.
1. if  statement

2. if...else  statement

3. if...elif...else  statement

1. Python if statement
The syntax of  if  statement in Python is:

if condition:
# body of if statement

The  if  statement evaluates  condition .


1. If  condition  is evaluated to  True , the code
inside the body of  if  is executed.
2. If  condition  is evaluated to  False , the code
inside the body of  if  is skipped.
Working of if Statement

Example 1: Python if Statement


number = 10

# check if number is greater than 0


if number > 0:
print('Number is positive.')

print('The if statement is easy')


Run Code

Output

Number is positive.
The if statement is easy

In the above example, we have created a


variable named  number . Notice the test
condition,

number > 0

Here, since  number  is greater than 0, the


condition evaluates  True .
If we change the value of variable to a
negative integer. Let's say -5.

number = -5

Now, when we run the program, the output


will be:

The if statement is easy

This is because the value of  number  is less


than 0. Hence, the condition evaluates
to  False . And, the body of  if  block is
skipped.

2. Python if...else Statement


An  if  statement can have an
optional  else  clause.
The syntax of  if...else  statement is:

if condition:
# block of code if condition is True

else:
# block of code if condition is False

The  if...else  statement evaluates the


given  condition :
If the condition evaluates to  True ,
 the code inside  if  is executed
 the code inside  else  is skipped
If the condition evaluates to  False ,
 the code inside  else  is executed
 the code inside  if  is skipped

Working of if...else Statement

Example 2. Python if...else Statement


number = 10

if number > 0:
print('Positive number')

else:
print('Negative number')

print('This statement is always executed')


Run Code

Output
Positive number
This statement is always executed

In the above example, we have created a


variable named  number . Notice the test
condition,

number > 0

Since the value of  number  is 10, the test


condition evaluates to  True . Hence code
inside the body of  if  is executed.
If we change the value of variable to a
negative integer. Let's say -5.

number = -5

Now if we run the program, the output will


be:

Number is negative.
This statement is always executed.

Here, the test condition evaluates to  False .


Hence code inside the body of  else  is
executed.

3. Python if...elif...else
Statement
The  if...else  statement is used to execute
a block of code among two alternatives.
However, if we need to make a choice
between more than two alternatives, then
we use the  if...elif...else  statement.
The syntax of the  if...elif...else  statement
is:

if condition1:
# code block 1

elif condition2:
# code block 2

else:
# code block 3

Here,

1. If condition1 evaluates to  true , code block


1 is executed.
2. If condition1 evaluates to  false ,
then condition2 is evaluated.
a. If condition2 is  true , code block 2 is
executed.
b. If condition2 is  false , code block 3 is
executed.
Working of if...elif Statement

Example 3: Python if...elif...else


Statement
number = 0

if number > 0:
print("Positive number")

elif number == 0:
print('Zero')
else:
print('Negative number')

print('This statement is always executed')


Run Code

Output

Zero
This statement is always executed

In the above example, we have created a


variable named  number  with the value 0.
Here, we have two condition expressions:
Here, both the conditions evaluate to  False .
Hence the statement inside the body
of  else  is executed.

Python Nested if statements


We can also use an  if  statement inside of
an  if  statement. This is known as a nested
if statement.
The syntax of nested if statement is:

# outer if statement
if condition1:
# statement(s)

# inner if statement
if condition2:
# statement(s)

Notes:
 We can add  else  and  elif  statements to the
inner  if  statement as required.
 We can also insert inner  if  statement inside
the outer  else  or  elif  statements(if they
exist)
 We can nest multiple layers
of  if  statements.
Example 4: Python Nested if
Statement
number = 5

# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')

# outer else statement


else:
print('Number is negative')

# Output: Number is positive


Run Code

In the above example, we have used


a nested if statement to check whether the
given number is positive, negative, or 0.

Python for Loop


In computer programming, loops are used to
repeat a block of code.

For example, if we want to show a


message 100 times, then we can use a
loop. It's just a simple example; you can
achieve much more with loops.
There are 2 types of loops in Python:

 for loop
 while loop

Python for Loop


In Python, the for loop is used to run a block
of code for a certain number of times. It is
used to iterate over any sequences such
as list, tuple, string, etc.
The syntax of the for loop is:

for val in sequence:


# statement(s)

Here, val accesses each item of sequence


on each iteration. Loop continues until we
reach the last item in the sequence.

Flowchart of Python for Loop


Working of Python for loop

Example: Loop Over Python


List
languages = ['Swift', 'Python', 'Go',
'JavaScript']

# access items of a list using for loop


for language in languages:
print(language)
Run Code

Output
Swift
Python
Go
JavaScript

In the above example, we have created a


list called languages.
Initially, the value of language is set to the
first element of the array,i.e. Swift, so the
print statement inside the loop is executed.
language is updated with the next element of
the array and the print statement is
executed again. This way the loop runs until
the last element of an array is accessed.

Python for Loop with Python


range()
A range is a series of values between two
numeric intervals.
We use Python's built-in function range() to
define a range of values. For example,

values = range(4)

Here, 4 inside range() defines a range
containing values 0, 1, 2, 3.
In Python, we can use for loop to iterate
over a range. For example,
# use of range() to define a range of values
values = range(4)

# iterate from i = 0 to i = 3
for i in values:
print(i)
Run Code

Output

0
1
2
3

In the above example, we have used


the for loop to iterate over a range
from 0 to 3.
The value of i is set to 0 and it is updated to
the next number of the range on each
iteration. This process continues until 3 is
reached.
Iteration Condition Action

1st True 0 is printed.

2nd True 1 is printed.

3rd True 2 is printed.

4th True 3 is printed.

5th False The loop is terminated

Note: To learn more about the use


of for loop with range, visit Python range().
Python for loop with else
A for loop can have an optional else block
as well. The else part is executed when the
loop is finished. For example,
digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")
Run Code

Output

0
1
5
No items left.

Here, the for loop prints all the items of


the digits list. When the loop finishes, it
executes the else block and prints No items

left.

Note: The else block will not execute if the


for loop is stopped by a break statement.

Python while Loop


In programming, loops are used to repeat a
block of code. For example, if we want to
show a message 100 times, then we can
use a loop. It's just a simple example, we
can achieve much more with loops.
In the previous tutorial, we learned
about Python for loop. Here, we are going to
learn about  while  loops.

Python while Loop


Python  while  loop is used to run a specific
code until a certain condition is met.
The syntax of  while  loop is:

while condition:
# body of while loop

Here,

1. A  while  loop evaluates the  condition


2. If the  condition  evaluates to  True , the code
inside the  while  loop is executed.
3. condition  is evaluated again.
4. This process continues until the condition
is  False .
5. When  condition  evaluates to  False , the loop
stops.
Flowchart for Python While
Loop

Flowchart for while Loop in Python

Example: Python while Loop


# program to display numbers from 1 to 5
# initialize the variable
i = 1
n = 5

# while loop from i = 1 to 5


while i <= n:
print(i)
i = i + 1
Run Code

Output

1
2
3
4
5

Here's how the program works:

Variable Condition: i <= n Action

i = 1
True 1 is printed.
n = 5

i = 2
True 2 is printed.
n = 5

i = 3
True 3 is printed.
n = 5

i = 4
True 4 is printed.
n = 5

i = 5
True 5 is printed.
n = 5
i = 6
False The loop is terminated.
n = 5

Example 2: Python while Loop to


Display Game Level
current_level = 0
final_level = 5

game_completed = True

while current_level <= final_level:


if game_completed:
print('You have passed level',
current_level)
current_level += 1

print('Level Ends')
Run Code

Output

You have passed level 0


You have passed level 1
You have passed level 2
You have passed level 3
You have passed level 4
You have passed level 5
Level Ends

In the above example, we have used


the  while  loop to check the current level and
display it on the console.
Infinite while Loop in Python
If the  condition  of a loop is always  True , the
loop runs for infinite times (until the memory
is full). For example,

# infinite while loop


while True:
# body of the loop

In the above example, the  condition  is


always  True . Hence, the loop body will run
for infinite times.

Python While loop with else


A  while  loop can have an optional  else  block
as well.
The  else  part is executed after
the  condition  in the while loop evaluates
to  False . For example,
counter = 0

while counter < 3:


print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Run Code

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we have used the  counter  variable to


print the  'Inside Loop'  string three times.
On the fourth iteration, the condition
in  while  becomes  False . Hence, the  else  part
is executed.

Note: The else block will not execute if the


while loop is stopped by a break statement.

Python for vs while loops


The  for  loop is usually used when the
number of iterations is known. For example,
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
Run Code

And while loop is usually used when the


number of iterations are unknown. For
example,
while condition:
# body of loop

Python Program to Print Hello


world!
print('Hello, world!')

Python Program to Add Two


Numbers
Example 1: Add Two Numbers
# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Example 2: Add Two Numbers With User Input


# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Python Program to Find the


Square Root
Example: For positive numbers
# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Python Program to Calculate the


Area of a Triangle
If  a ,  b  and  c  are three sides of a triangle. Then,

s = (a+b+c)/2

area = √(s(s-a)*(s-b)*(s-c))

Source Code
# Python Program to find the area of triangle

a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Python Program to Swap Two


Variables
Using a temporary variable
# Python program to swap two variables

x = 5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

Without Using Temporary Variable


x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)

Python Program to Convert


Kilometers to Miles
Example: Kilometers to Miles
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))

# conversion factor
conv_fac = 0.621371

# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))

Python Program to Convert


Celsius To Fahrenheit
fahrenheit = celsius * 1.8 + 32

# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result


celsius = 37.5

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))
Python Program to Check if a
Number is Positive, Negative or 0
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Python Program to Check if a


Number is Odd or Even

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

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


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Python Program to Check Leap
Year

A leap year is exactly divisible by 4 except for century years

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

Python Program to Find the


Largest Among Three Numbers

Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


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

Python Program to Print all Prime


Numbers in an Interval

# Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

Factorial of a Number using Loop


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

Python Program to Display the


multiplication Table

# Multiplication table (from 1 to 10) in Python

num = 12

# To take input from the user


# num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Python Program to Find LCM
Program to Compute LCM
# Python Program to find the L.C.M. of two input number

def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = 54
num2 = 24

print("The L.C.M. is", compute_lcm(num1, num2))

Python Program to Make a Simple


Calculator
Example: Simple Calculator by Using Functions
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Run Code

Output

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no

In this program, we ask the user to choose an operation. Options 1, 2, 3,


and 4 are valid. If any other input is given, Invalid Input is displayed and
the loop continues until a valid option is selected.
Two numbers are taken and an if...elif...else branching is used to
execute a particular section. User-defined
functions add(), subtract(), multiply() and divide() evaluate respective
operations and display the output.

Python Program to Create Pyramid


Patterns
Programs to print triangles using *, numbers and
characters
Example 1: Program to print half pyramid using *

* *
* * *

* * * *

* * * * *

Source Code
rows = int(input("Enter number of rows: "))

for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
Run Code

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 2: Program to print half pyramid a using numbers

1 2

1 2 3
1 2 3 4

1 2 3 4 5

Source Code
rows = int(input("Enter number of rows: "))

for i in range(rows):
for j in range(i+1):
print(j+1, end=" ")
print("\n")
Run Code

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 .

 In the second loop, we print numbers starting from  1  to  j , where  j  ranges
from  0  to  i .
 After each iteration of the first loop, we print a new line.

Example 3: Program to print half pyramid using alphabets

B B

C C C

D D D D

E E E E E
Source Code
rows = int(input("Enter number of rows: "))

ascii_value = 65

for i in range(rows):
for j in range(i+1):
alphabet = chr(ascii_value)
print(alphabet, end=" ")

ascii_value += 1
print("\n")
Run Code

The working of the above example is also similar to the other examples
discussed above except that the ascii values are printed here. The ascii
value for alphabets start from 65 (i.e. A). Therefore, in each iteration, we
increase the value of  ascii_value  and print its corresponding alphabet.

Programs to print inverted half pyramid using * and


numbers
Example 4: Inverted half pyramid using *

* * * * *

* * * *

* * *

* *

*
Source Code
rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):


for j in range(0, i):
print("* ", end=" ")

print("\n")
Run Code

This example is similar to an upright pyramid except that here we start from
the total number of  rows  and in each iteration we decrease the number
of  rows  by 1.

Example 5: Inverted half pyramid using numbers

1 2 3 4 5

1 2 3 4

1 2 3

1 2

Source Code
rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):


for j in range(1, i+1):
print(j, end=" ")

print("\n")
Run Code
The only difference between an upright and an inverted pyramid using
numbers is that the first loop starts from the total number of  rows  to 0.

Programs to print full pyramids


Example 6: Program to print full pyramid using *

* * *

* * * * *

* * * * * * *

* * * * * * * * *

Source Code
rows = int(input("Enter number of rows: "))

k = 0

for i in range(1, rows+1):


for space in range(1, (rows-i)+1):
print(end=" ")

while k!=(2*i-1):
print("* ", end="")
k += 1

k = 0
print()
Run Code

This type of pyramid is a bit more complicated than the ones we studied
above.
 The outermost loop starts from  i = 1  to  i = row + 1 .

 Among the two inner loops, the for loop prints the required spaces for each
row using formula  (rows-i)+1 , where rows is the total number of rows
and  i  is the current row number.
 The while loop prints the required number stars using formula  2 * i - 1.

This formula gives the number of stars for each row, where row is  i .

Example 7: Full Pyramid of Numbers

2 3 2

3 4 5 4 3

4 5 6 7 6 5 4

5 6 7 8 9 8 7 6 5

Source Code
rows = int(input("Enter number of rows: "))

k = 0
count=0
count1=0

for i in range(1, rows+1):


for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1

while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1

count1 = count = k = 0
print()
Run Code

Like example 6, this example also makes use of two loops inside a for loop.

 The outer for loop iterates through each row.

 Here we use two counters  count  and  count1  for printing the spaces and
numbers respectively.
 The inner for loop prints the required spaces using formula  (rows-i)+1 ,
where rows is the total number of rows and  i  is the current row number.
 The while loop prints the numbers where  2 * i - 1  gives the number of
items in each row.

Example 8: Inverted full pyramid of *

* * * * * * * * *

* * * * * * *

* * * * *

* * *

Source Code
rows = int(input("Enter number of rows: "))

for i in range(rows, 1, -1):


for space in range(0, rows-i):
print(" ", end="")
for j in range(i, 2*i-1):
print("* ", end="")
for j in range(1, i-1):
print("* ", end="")
print()
Run Code

In this example, we have used a total of 4 for loops.

 The outer for loop iterates from  i = rows  to  i = 1 .

 The first inner for loop prints the spaces required in each row.

 The second inner for loop prints the first half of the pyramid (vertically cut),
whereas the last inner for loop prints the other half.

Example 9: Pascal's Triangle

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

Source Code
rows = int(input("Enter number of rows: "))
coef = 1

for i in range(1, rows+1):


for space in range(1, rows-i+1):
print(" ",end="")
for j in range(0, i):
if j==0 or i==0:
coef = 1
else:
coef = coef * (i - j)//j
print(coef, end = " ")
print()
Run Code

In this example, we have used three for loops.

 The outer loop iterates from  1  to  rows + 1.

 The first inner loop prints the spaces.

 The second inner loop first finds the number to be printed using
statement  coef = coef * (i - j) // j  and then prints it. Here,  i  is the row
number and  j  is the value ranging from  0  to  i .

Example 10: Floyd's Triangle

2 3

4 5 6

7 8 9 10

Source Code
rows = int(input("Enter number of rows: "))
number = 1

for i in range(1, rows+1):


for j in range(1, i+1):
print(number, end=" ")
number += 1
print()
Run Code
This is one of the easiest patterns.

 number  variable is initialized with value 1.


 The outer for loop iterates from 1 to the total number of rows.

 The inner for loop starts from  1  to  i + 1, where i is the row number. After
each iteration, the value of the  number  is increased.

You might also like