0% found this document useful (0 votes)
3 views65 pages

Python programs

The document contains a collection of basic Python programs demonstrating various functionalities such as printing statements, variable assignments, arithmetic operations, conditional statements, and user input handling. It includes examples of simple calculations, control flow structures, and mathematical functions, as well as practical applications like temperature conversion and area calculations. Overall, it serves as a beginner's guide to fundamental Python programming concepts.

Uploaded by

suthojunavadeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views65 pages

Python programs

The document contains a collection of basic Python programs demonstrating various functionalities such as printing statements, variable assignments, arithmetic operations, conditional statements, and user input handling. It includes examples of simple calculations, control flow structures, and mathematical functions, as well as practical applications like temperature conversion and area calculations. Overall, it serves as a beginner's guide to fundamental Python programming concepts.

Uploaded by

suthojunavadeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Basic Programs

# print statement to display hello world


print("Hello world!")
Hello world!

# To display your name with spaces


name = "shabana"
print("Hai", name)
Hai shabana

#To display your name with out spaces


name= "Shabana!"
print("Hello"+name, "Welcome to scientic programming")
HelloShabana! Welcome to scientic programming

# To find python version


import sys
print([Link])
3.10.9 | packaged by Anaconda, Inc. | (main, Mar 1 2023, [Link]) [MSC v.1916
64 bit (AMD64)]

#python uses indentation to indicate a block of code


if 5>2:
print("5 is greater than 2")
5 is greater than 2

# if no indentation will get error, atleast 4 spaces required. More than one is
preferable
if 5>2:
print("5 is greater than 2")
5 is greater than 2

if 5>2:
print("5 is greater than 2")
5 is greater than 2

if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Five is greater than two!
Five is greater than two!

#use the same number of spaces in the same block of code, otherwise Python will
give you an error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Five is greater than two!
Five is greater than two!

#assigning values to the variables


x=5
y = "Shabana"
print(x)
print(y)
5
Shabana

# single line comment


"""this
is
multi_line
comment"""

print("Hello World!");
print("Have a good day.");
# multi statements & semicolons are optional in python
print("Learning Python is fun!");
Hello World!
Have a good day.
Learning Python is fun!
#You can write multiple statements on one line by separating them with ;
print("Hello"); print("How are you?"); print("Bye bye!")
Hello
How are you?
Bye bye!

#Two statements on the same line without a separator (newline or ;), Python will
give an error:
print("Python is fun!");print("Really!")
Python is fun!
Really!

#You can use either " double quotes or ' single quotes:
print("This will work!")
print('This will also work!')
This will work!
This will also work!

#if you forget to put the text inside quotes, Python will give an error:
print(This will cause an error)
Cell In[25], line 2
print(This will cause an error)
^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
"""By default, the print() function ends with a new line.
If you want to print multiple words on the same line, you can use the end
parameter"""

print("Hello World!", end=" ")


print("I will print on the same line.")
Hello World! I will print on the same line.

print(3)
print("shabana")
print(3+10)
print(3.5)
name = "Shabana!"
age = 40
print(f"Hello {name} {age} years old")
print("I am shabana", 35, "years old")
3
shabana
13
3.5
Hello Shabana! 40 years old
I am shabana 35 years old

x=10
x="shabana"
print(x)
shabana

x=int(3)
y=str(3)
z=float(3)
print(x,y,z)
3 3 3.0

x=3
y="shabana"
z=3.5
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'str'>
<class 'float'>

x="shabana"
X="shabana"
print(x)
print(X)
shabana
shabana

x="shabana"
x='Shabana'
print(x)
Shabana

x=4
X="shabana"
print(x)
print(X)
4
shabana

x="shabana"
y="sha"
z="ssss"
print(x,y,z)
shabana sha ssss

a = 15
b = 12
res = a + b
print(res)

# taking user input


a = input("First number: ")
b = input("Second number: ")
res = float(a) + float(b) # converting input to float and adding
print(res)

res = lambda a, b: a + b
print(res(10, 5))

import operator
print([Link](10, 5))
print(sum([10, 5]))
a=7
b=3
print(max(a, b))

a=7
b=3
print(a if a > b else b) # using ternary operator

# program to add two numbers


a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
sum=a+b
print("Sum=", sum)

Enter first number:12


Enter second number:24
Sum= 36

#program to perform arithmatic operations


a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
print("Sum=", a+b)
print("Sub=", a-b)
print("Mul=", a*b)
print("Div=", a/b)
print("Mod=", a%b)
#print("\n")
print(f"sum= {a} + {b} = {a+b}")

Enter first number:10


Enter second number:20
Sum= 30
Sub= -10
Mul= 200
Div= 0.5
Mod= 10
sum= 10 + 20 = 30

#square root of a given number


import math
a=float(input("Enter a number:"))
sqrt = [Link](a)
print("Square of a given number:",sqrt)

Enter a number:2
Square of a given number: 1.4142135623730951

"""python program to find area of a triangle

perimeter s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))"""

import math

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


b=float(input("Enter second number:"))
c=float(input("Enter third number:"))

s=(a+b+c)/2
print("perimeter =", s)

area=[Link]((s*(s-a)*(s-b)*(s-c)))
print("The area of the triangle is %0.2f" %area)

Enter first number:1


Enter second number:2
Enter third number:3
perimeter = 3.0
The area of the triangle is 0.00
#program to find area of right-angled triangle (1/2)*base*height
b=float(input("Enter first number:"))
h=float(input("Enter second number:"))
area=b*h*0.5
print("Area of right-angled triangle: %0.3f" %area)

Enter first number:45


Enter second number:33
Area of right-angled triangle: 742.500

""" program to solve quadratic equation


ax2 + bx + c = 0, where
a, b and c are real numbers and a ≠ 0

The solutions of this quadratic equation is given by:


(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)"""

import cmath

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


b=float(input("Enter second number:"))
c=float(input("Enter third number:"))

t=(b*b)-(4*a*c)
sol1= (-b+[Link](t))/(2*a)
sol2= (-[Link](t))/(2*a)

print("quadratic roots are {0} and {1}:" .format (sol1,sol2))


#print('The solution are {0} and {1}'.format(sol1,sol2))

Enter first number:1


Enter second number:5
Enter third number:6
quadratic roots are (-2+0j) and (-3+0j):

# program to swap two variables

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


b=int(input("Enter second number:"))

print("Before swapping:")
print("a=", a, "b=", b)

temp=a
a=b
b=temp

print("After swapping:")
print("a=", a, "b=", b)

Enter first number:345


Enter second number:234
Before swapping:
a= 345 b= 234
After swapping:
a= 234 b= 345
#swap with XOR
a=24
b=50
print("Before swapping:")
print("a=", a, "b=", b)

a = a ^ b # Step 1: XOR and store in a


b = a ^ b # Step 2: XOR again to get original a in b
a = a ^ b # Step 3: XOR again to get original b in a

print("After swapping:")
print("a=", a, "b=", b)

Before swapping:
a= 24 b= 50
After swapping:
a= 50 b= 24

#swap with out 3rd variable


a=24
b=50

print("Before swapping:")
print("a=", a, "b=", b)

a = a + b # sum stored in a
b = a - b # original a stored in b
a = a - b # original b stored in a

print("After swapping:")
print("a=", a, "b=", b)
Before swapping:
a= 24 b= 50
After swapping:
a= 50 b= 24
#Python (Tuple Unpacking)
a=24
b=50

print("Before swapping:")
print("a=", a, "b=", b)

a,b=b,a

print("After swapping:")
print("a=", a, "b=", b)

Before swapping:
a= 24 b= 50
After swapping:
a= 50 b= 24

#Simple Interest
p = float(input("Principal: "))
r = float(input("Rate: "))
t = float(input("Time: "))
si = (p * r * t) / 100
print("Simple Interest =", si)

Principal: 3
Rate: 4
Time: 5
Simple Interest = 0.6

# Generate a random number


import random
print(f"random number:{[Link](1,100)}")

random number:57

#program to conver km to miles 1km=0.621371 miles


km=float(input("Enter distance in kms:"))
miles=km*0.621371
print(f" conversion of {km} kilometers to {miles} miles")

Enter distance in kms:100


conversion of 100.0 kilometers to 62.137100000000004 miles

#conversion of foreign heat to celcius c=(f-32)*(5/9)

f=float(input("Enter foreign heat value:"))

print(f" conversion of {f} value into Celcius is {(f-32)*(5/9)}")

Enter foreign heat value:98.6


conversion of 98.6 value into Celcius is 37.0

#Simple Interest
p = float(input("Principal: "))
r = float(input("Rate: "))
t = float(input("Time: "))
si = (p * r * t) / 100
print("Simple Interest =", si)

Principal: 1000
Rate: 2
Time: 4
Simple Interest = 80.0

#Compound Interest
p = float(input("Principal: "))
r = float(input("Rate (%)): "))
t = float(input("Time (years): "))
amount = p * (1 + r/100) ** t
ci = amount - p
print("Compound Interest =", ci)

Principal: 1000
Rate (%)): 3
Time (years): 4
Compound Interest = 125.50881000000004

#Factorial of a number
n = int(input("Enter number: "))
fact = 1
for i in range(1, n+1):
fact = fact * i
print("Factorial =", fact)

Enter number: 6
Factorial = 720

# odd numbers less than 40


li=[12,3,23,45,57,79]
res=print([x for x in li if x%2!=0 and x<40])
print(res)

[3, 23]

#Even or Odd
n = int(input("Enter a number: "))

if n % 2 == 0:
print("Even")
else:
print("Odd")
Enter a number: 22
Even

#Vowel or Consonant
ch = input("Enter a character: ")
if [Link]() in "aeiou":
print("Vowel")
else:
print("Consonant")

Enter a character: C
Consonant

#Leap Year
year = int(input("Enter year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):


print("Leap Year")
else:
print("Not a Leap Year")
Enter year: 2001
Not a Leap Year

#Divisible by 5 and 11

n = int(input("Enter number: "))

if n % 5 == 0 and n % 11 == 0:
print("Divisible by 5 and 11")
else:
print("Not divisible by 5 and 11")
Enter number: 52
Not divisible by 5 and 11

#Grade Calculation

marks = int(input("Enter marks: "))

if 90 <= marks <= 100:


print("Grade A")
elif 80 <= marks <= 89:
print("Grade B")
elif 70 <= marks <= 79:
print("Grade C")
elif 60 <= marks <= 69:
print("Grade D")
else:
print("Grade F")
Enter marks: 95
Grade A

#Valid Triangle

a = int(input("Enter side1: "))


b = int(input("Enter side2: "))
c = int(input("Enter side3: "))

if a+b>c and a+c>b and b+c>a:


print("Valid Triangle")
else:
print("Invalid Triangle")

Enter side1: 1
Enter side2: 2
Enter side3: 3
Invalid Triangle

#Simple Calculator

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


b = float(input("Enter second number: "))
op = input("Enter operator (+,-,*,/): ")

if op == '+':
print("Result:", a+b)
elif op == '-':
print("Result:", a-b)
elif op == '*':
print("Result:", a*b)
elif op == '/':
print("Result:", a/b)
else:
print("Invalid operator")

#Multiple of 3 or 7
n = int(input("Enter number: "))
if n % 3 == 0 or n % 7 == 0:
print("Multiple of 3 or 7")
else:
print("Not a multiple of 3 or 7")

#Smallest of Three Numbers

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


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a <= b and a <= c:


print("Smallest:", a)
elif b <= a and b <= c:
print("Smallest:", b)
else:
print("Smallest:", c)

#Voting Eligibility

age = int(input("Enter age: "))


if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

#Type of Triangle

a = int(input("Enter side1: "))


b = int(input("Enter side2: "))
c = int(input("Enter side3: "))

if a == b == c:
print("Equilateral")
elif a == b or b == c or a == c:
print("Isosceles")
else:
print("Scalene")

#Character Type

ch = input("Enter character: ")

if [Link]():
print("Uppercase")
elif [Link]():
print("Lowercase")
elif [Link]():
print("Digit")
else:
print("Special Character")

#Day of Week
n = int(input("Enter number (1-7): "))

days =
["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]

if 1 <= n <= 7:
print(days[n-1])
else:
print("Invalid input")

#Temperature Conversion

temp = float(input("Enter temperature: "))


unit = input("Enter unit (C/F): ")

if [Link]() == 'C':
f = (temp * 9/5) + 32
print("Fahrenheit:", f)
elif [Link]() == 'F':
c = (temp - 32) * 5/9
print("Celsius:", c)
else:
print("Invalid unit")

# Positive, Negative, or Zero**

n = float(input("Enter a number: "))

if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
#Roots of Quadratic Equation
import math

a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))

d = b*b - 4*a*c

if d > 0:
r1 = (-b + [Link](d))/(2*a)
r2 = (-b - [Link](d))/(2*a)
print("Two real roots:", r1, r2)
elif d == 0:
r = -b/(2*a)
print("One real root:", r)
else:
print("No real roots")

#Electricity Bill

units = int(input("Enter units: "))

if units <= 100:


bill = units * 5
elif units <= 200:
bill = 100*5 + (units-100)*7
else:
bill = 100*5 + 100*7 + (units-200)*10

print("Total Bill:", bill)

#Armstrong Number

n = int(input("Enter 3-digit number: "))


temp = n
sum = 0

while temp > 0:


digit = temp % 10
sum += digit**3
temp //= 10

if sum == n:
print("Armstrong Number")
else:
print("Not Armstrong")

#Positive and Even

n = int(input("Enter number: "))


if n > 0 and n % 2 == 0:
print("Positive and Even")
else:
print("Condition not satisfied")

#Alphabet, Digit or Special

ch = input("Enter character: ")

if [Link]():
print("Alphabet")
elif [Link]():
print("Digit")
else:
print("Special Symbol")

#Oldest and Youngest

a = int(input("Age of person1: "))


b = int(input("Age of person2: "))
c = int(input("Age of person3: "))

print("Oldest:", max(a,b,c))
print("Youngest:", min(a,b,c))

#Bonus Calculation

salary = float(input("Enter salary: "))


exp = int(input("Enter years of experience: "))

if exp > 5:
bonus = salary * 0.05
print("Bonus:", bonus)
else:
print("No bonus")

#Century Year

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

if year % 100 == 0:
print("Century Year")
else:
print("Not a Century Year")

#Profit or Loss

cp = float(input("Enter Cost Price: "))


sp = float(input("Enter Selling Price: "))

if sp > cp:
print("Profit:", sp-cp)
elif cp > sp:
print("Loss:", cp-sp)
else:
print("No Profit No Loss")

#Square or Rectangle

l = float(input("Enter length: "))


b = float(input("Enter breadth: "))

if l == b:
print("Square")
else:
print("Rectangle")

#Determine Input Type

x = input("Enter something: ")

try:
val = int(x)
print("Integer")
except:
try:
val = float(x)
print("Float")
except:
print("String")

#Number to Words (1-5)

n = int(input("Enter number (1-5): "))

words = {1:"One",2:"Two",3:"Three",4:"Four",5:"Five"}

if n in words:
print(words[n])
else:
print("Invalid number")
#Right-Angled Triangle

a = int(input("Enter side1: "))


b = int(input("Enter side2: "))
c = int(input("Enter side3: "))
sides = sorted([a,b,c])

if sides[0]**2 + sides[1]**2 == sides[2]**2:


print("Right-Angled Triangle")
else:
print("Not a Right-Angled Triangle")

#Display elements between 10 and 40 in a list


arr = [5, 12, 45, 60, 9, 30]
result = [x for x in arr if x > 10 and x < 40]
print(result)

x=float(1)
y=float(2.3)
z=float(4.56)
print(x);print(y);print(z)

1.0
2.3
4.56

a = "Hello, World!"
print(len(a))
print(a[1])
13
e

for x in "shabana":
print(x)
s
h
a
b
a
n
a
txt = "The best things in life are free!"
print("free" in txt)
if "free" in txt:
print("Yes, 'free' is present.")

True
Yes, 'free' is present.

txt = "The best things in life are free!"


print("expensive" not in txt)
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

True
No, 'expensive' is NOT present.

#Sliicing
b = "Hello, World!"
print(b[2:5])
print(b[:5])
print(b[2:])
print(b[-5:-2])

llo
Hello
llo, World!
orl

a = " Hello, World! "


print([Link]())
print([Link]())
print([Link]())
print([Link]("H", "J"))
print([Link](","))

HELLO, WORLD!
hello, world!
Hello, World!
Jello, World!
[' Hello', ' World! ']

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

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

#F-strings
age = 36
txt = f"My name is John, I am {age}"
print(txt)

My name is John, I am 36
age = 36

#This will produce an error:


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

TypeError Traceback (most recent call last)


Cell In[26], line 3
1 age = 36
2 #This will produce an error:
----> 3 txt = "My name is John, I am " + age
4 print(txt)

TypeError: can only concatenate str (not "int") to str

price = 59
txt = f"The price is {price} dollars"
print(txt)
txt = f"The price is {price:.2f} dollars"
print(txt)
txt = f"The price is {20 * 59} dollars"
print(txt)

The price is 59 dollars


The price is 59.00 dollars
The price is 1180 dollars

txt = "We are the so-called "Vikings" from the north."


print(txt)
Cell In[41], line 1
txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax

txt = "We are the so-called \"Vikings\" from the north."


print(txt)

We are the so-called "Vikings" from the north.

txt = "Hello\nWorld!"
print(txt)
txt = "Hello\tWorld!"
print(txt)

Hello
World!
Hello World!
txt = "hello, and welcome to my world."
x = [Link]()
print (x)

Hello, and welcome to my world.

#Lists are used to store multiple items in a single variable.


list=["aaaa","bbbb","cccc"]
print(list)

['aaaa', 'bbbb', 'cccc']

#List items are ordered, changeable, and allow duplicate values.


#There are some list methods that will change the order,
#but in general: the order of the items will not change.

list=["aaaa","bbbb","cccc","aaaa"]
print(list)
print(len(list))

['aaaa', 'bbbb', 'cccc', 'aaaa']


4

#String, int and boolean data types


list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
#A list with strings, integers and boolean values
list4 = ["abc", 34, True, 40, "male"]
print(type(list1))
<class 'list'>

list1 = ["aaaa", "bbbb", "cccc", "dddd","eeee","ffff"]


print(list1[2])
print(list1[-2])
print(list1[2:5])
print(list1[-5:-2])
print(list1[:5])
print(list1[-1])
print(list1[:-1])

cccc
eeee
['cccc', 'dddd', 'eeee']
['bbbb', 'cccc', 'dddd']
['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee']
ffff
['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee']

list1 = ["aaaa", "bbbb", "cccc", "dddd","eeee","ffff"]


[Link]("gggg")
print(list1)
[Link](2)
print(list1)
[Link]("eeee")
print(list1)

['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg']


['aaaa', 'bbbb', 'dddd', 'eeee', 'ffff', 'gggg']
['aaaa', 'bbbb', 'dddd', 'ffff', 'gggg']

"""Instead of writing many if..else statements, you can use the match
statement.
The match statement selects one of many code blocks to be executed."""

day=int(input("Enter any number(1 to 7):"))

match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Invalid")

Enter any number(1 to 7):9


Invalid

day = 4
match day:
case 1 | 2 | 3 | 4 | 5:
print("Today is a weekday")
case 6 | 7:
print("I love weekends!")

Today is a weekday

#add if statements in the case evaluation


month = 5
day = 4
match day:
case 1 | 2 | 3 | 4 | 5 if month == 4:
print("A weekday in April")
case 1 | 2 | 3 | 4 | 5 if month == 5:
print("A weekday in May")
case _:
print("No match")

A weekday in May
# While loop
i=1
while i < 6:
print(i)
i += 1

1
2
3
4
5

#Break
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

1
2
3

#Continue
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

1
2
4
5
6
# else statement we can run a block of code once when the condition no longer is
true:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

1
2
3
4
5

i is no longer less than 6

# The range() function returns a sequence of numbers, starting from 0 by


default,
# and increments by 1 (by default), and ends at a specified number.

for x in range(6):
print(x)
0
1
2
3
4
5

list = ["aaa", "bbb", "ccc"]


for x in list:
print(list)

['aaa', 'bbb', 'ccc']


['aaa', 'bbb', 'ccc']
['aaa', 'bbb', 'ccc']
for x in "shabana":
print(x)
s
h
a
b
a
n
a

list = ["aaa", "bbb", "ccc"]


for x in list:
print(x)
if x == "bbb":
break

aaa
bbb

list = ["aaa", "bbb", "ccc"]


for x in list:
if x == "bbb":
break
print(x)
aaa

list = ["aaa", "bbb", "ccc"]


for x in list:
if x == "bbb":
continue
print(x)
aaa
ccc

for x in range(6):
print(x)
0
1
2
3
4
5

for x in range(2, 6):


print(x)
2
3
4
5

for x in range(2, 30, 5):


print(x)
2
7
12
17
22
27

for x in range(30, 10, -3):


print(x)
30
27
24
21
18
15
12

for x in range(6):
print(x)
else:
print("done")
0
1
2
3
4
5
done

for x in range(6):
if x == 3: break
print(x)
else:
print("done")
0
1
2

list1=[0,1,2]
list2=[0,1,2]
for x in list1:
for y in list2:
print(x, y)
00
01
02
10
11
12
20
21
22

#for loops cannot be empty, but if you for some reason have a for loop with no
content,
#put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass
#range(start, stop, step)

#greatest number among two numbers


a,b=map(int,input().split())
if a>b:
print(f"{a} is greater")
else:
print(f"{b} is greater")

20 10
20 is greater

#Greatest among 3 numbers


a,b,c=map(int,input().split())
if (a>b and a>c):
print(f"{a} is greater")
elif b>c:
print(f"{b} is greater")
else:
print(f"{c} is greater")

10 20 30
30 is greater
#Greatest among 4 numbers
a,b,c,d=map(int,input().split())
if (a>b and a>c and a>d):
print(f"{a} is greater")
elif (b>c and b>d):
print(f"{b} is greater")
elif c>d:
print(f"{c} is greater")
else:
print(f"{d} is greater")
10 20 30 40
40 is greater

for i in range(1,6):
print(i)
1
2
3
4
5

for i in range(1,11,2):
print(i)

1
3
5
7
9

for i in range(2,11,2):
print(i)
2
4
6
8
10

#to print even numbers between 1 to 10 and its count


count=0
for i in range(2,11,2):
print(i)
count=count+1
print("count:",count)
2
4
6
8
10
count: 5

#to print even numbers between 1 to 10 and its count &sum


sum=0
count=0
for i in range(2,11,2):
print(i)
count=count+1
sum=sum+i
print("count:",count)
print("Sum:", sum)
2
4
6
8
10
count: 5
Sum: 30
#Given number is prime or not
n=int(input("Enter a number:"))
count=0
for i in range(1,n+1):
if n%i==0:
count=count+1
if count==2:
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")

Enter a number:44
44 is not a prime number

#Given number is even or odd


n=int(input("Enter a number:"))
if n%2==0:
print(f"{n} is Even number")
else:
print(f"{n} is odd number")

Enter a number:23
23 is odd number

#Reverse of an integer
x=int(input("Enter a number:"))
sum=0
n=x
while n>0:
r=n%10
sum=sum*10+r
n=n//10
print(sum)
Enter a number:1234
4321

#Fibonocci sequence
a=0
b=1
n=10
print(a,b,end=" ")
for i in range(a,n):
c=a+b
print(c,end=" ")
a=b
b=c

0 1 1 2 3 5 8 13 21 34 55 89

#Factorial of a number
n = int(input("Enter number: "))
fact = 1
for i in range(1, n+1):
fact = fact * i
print("Factorial =", fact)

Enter number: 5
Factorial = 120

#Multiplication table
n=int(input("Enter a number:"))
for i in range(1,11):
print(f"{n}*{i}=",n*i)

Enter a number:3
3*1= 3
3*2= 6
3*3= 9
3*4= 12
3*5= 15
3*6= 18
3*7= 21
3*8= 24
3*9= 27
3*10= 30

# Generate a random number

import random
print(f"random number:{[Link](1,100)}")

random number:30

#Create a list & append values


n=eval(input("Enter a limit:"))
lst=[]
for i in range(1,n+1):
n=eval(input("Enter a value:"))
[Link](n)
print(lst)

Enter a limit:3

Enter a value:12
Enter a value:23
Enter a value:34
[12, 23, 34]
#Create a list , append values, count odd numbers in a list
n=int(input("Enter limit:"))
lst=[]
print("Enter values:")
for i in range(1,n+1):
a=int(input())
[Link](a)

count = 0

for num in lst:


if num % 2 != 0:
count += 1
print("List:", lst)
print("Count of odd Numbers:", count)

Enter limit:3
Enter values:
12
23
34
List: [12, 23, 34]
Count of odd Numbers: 1

#Create a list , append values, count odd & even numbers in a list

n=int(input("Enter limit:"))
lst=[]
lst1=[]
lst2=[]
print("Enter values:")
for i in range(1,n+1):
a=int(input())
[Link](a)
print("List:", lst)
count = 0
c=0

for num in lst:


if num % 2 != 0:
count += 1
[Link](num)
else:
c+=1
[Link](num)

print("Odd numbers list:", lst2)


print("Count of odd Numbers:", count)
print("Even numbers list:", lst1)
print("Count of even Numbers:", c)

Enter limit:4
Enter values:
12
23
3
45
List: [12, 23, 3, 45]
Odd numbers list: [23, 3, 45]
Count of odd Numbers: 3
Even numbers list: [12]
Count of even Numbers: 1

#sum of two numbers by using function


def add(a, b):
return a + b
# initializing numbers
a = 10
b=5
# calling function
res = add(a,b)
print(res)

#Built in functions
#print(), len(), type(), sum(), max()

numbers = [10, 20, 30, 40]

print("Length:", len(numbers))
print("Maximum:", max(numbers))
print("Sum:",sum(numbers))

Length: 4
Maximum: 40
sum:100
#funtions with no args & no return value
def display():
print ("Welcome")

display()

#function with args & no return value


def display(name):
print("Welcome", name)

display("shabana")

Welcome shabana

def display(name):
print("Welcome", name)

name=input("Enter your name:")


display(name)

Enter your name:shabana


Welcome shabana

def display(s):
print(type(s))

display(10)
display(10.5)
display("shabana")

<class 'int'>
<class 'float'>
<class 'str'>
#sum
def sum(a,b):
print("Sum=",a+b)

sum(10,20)

Sum= 30

#sum
def sum(a,b):
print("Sum=",a+b)

a,b=map(int,input("Enter 2 numbers:").split()) # to read integers


sum(a,b)
Enter 2 numbers:10 20

Sum= 30

#Split()
a, b = map(int, input("Enter 2 numbers: ").split(",")) # input is comma separated
print(a);print(b)

Enter 2 numbers: 10,20


10
20

a, b, c = input("Enter 3 words: ").split() # to read strings


print(a);print(b); print(c)

Enter 3 words: sha shaba shabana


sha
shaba
shabana

#function with arguments & return value


def sum(a,b):
c=a+b
return c

a,b=map(int,input("Enter 2 numbers:").split())
x=sum(a,b)
print("sum=", x)

Enter 2 numbers:20 30
sum= 50

# In python at a time a function can return more than one value


def sumdiff(a,b):
c=a+b
d=a-b
return c,d

x,y=sumdiff(40,25)
print("Sum=", x,"Diff=", y)

Sum= 65 Diff= 15

#Multiply
def multiply(a, b):
return a * b

result = multiply(4, 5)
print("Multiplication:", result)

#function with default paremeters


def display(a=1,b=1,c=1):
print("a=",a,"b=",b,"c=",c)

display()

a= 1 b= 1 c= 1
#Default Argument Function
#Function with default parameter values.
def greet(name="Student"):
print("Hello", name)

greet()
greet("Shabana")

Hello Student
Hello Shabana

#funtion with variable length args


def display(*arg):
print("All args=", arg)
print("1st arg=", arg[0])

display(10,20)
All args= (10, 20)
1st arg= 10

#*args – Non-keyword arguments


def total(*numbers):
print("Sum:", sum(numbers))

total(10, 20, 30)

#**kwargs – Keyword arguments


def details(**data):
print(data)

details(name="Shabana", age=20)
{'name': 'Shabana', 'age': 20}

#Anonymous Function (Lambda Function)


#Function without a name using lambda.
square = lambda x: x * x
print("Square:", square(6))

Square: 36
#Recursive Function
#A function that calls itself.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

print("Factorial:", factorial(5))

Factorial: 120

#Local variable
def my_function():
x = 10 # Local variable
print(x)
my_function()
#print(x) # Error! x is not accessible outside

10

# Global variable
x = 20 # Global variable
def my_function():
print(x) # Can access global x

my_function()
print(x)

20
20

#Change global variable


x = 10
def change_global():
global x
x = 50 # Modifies global x

change_global()
print(x) # Output: 50
50

#map() – Apply Function to Each Element


nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # Output: [1, 4, 9, 16]

#reduce() – Apply Function to Reduce to a Single Value


from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24

24

#Function Annotations (Type Hints)


#Python allows type hints to improve readability.
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3)) # Output: 5

#filter() – Filter Elements Based on Condition


from functools import reduce
nums = [1, 2, 3, 4, 5, 6]

even_nums = list(filter(lambda x: x % 2 == 0, nums))


odd_nums = list(filter(lambda x: x % 2 == 1, nums))
print("Even_nums=",even_nums)
print("odd_nums=",odd_nums)
product = reduce(lambda x, y: x * y, even_nums)
print("Product of even_nums=",product)

product = reduce(lambda x, y: x * y, odd_nums)


print("Product of odd_nums=",product)

sum = reduce(lambda x, y: x + y, nums)


print("sum of nums list=",sum)

Even_nums= [2, 4, 6]
odd_nums= [1, 3, 5]
Product of even_nums= 48
Product of odd_nums= 15
sum of nums list= 21

Python Star Pattern Programs (with Sample Outputs)

1. Square Star Pattern


def square(n):
for i in range(n):
print("* " * n)

square(3)
Output:
***
***
***

2. Right Triangle
def right_triangle(n):
for i in range(1, n+1):
print("* " * i)

right_triangle(4)
Output:
*
**
***
****

3. Inverted Right Triangle


def inv_right(n):
for i in range(n, 0, -1):
print("* " * i)

inv_right(4)
Output:
****
***
**
*

4. Pyramid
def pyramid(n):
for i in range(1, n+1):
print(" "*(n-i) + "* "*i)

pyramid(4)
Output:
*
**
***
****
5. Inverted Pyramid
def inv_pyramid(n):
for i in range(n, 0, -1):
print(" "*(n-i) + "* "*i)

inv_pyramid(4)
Output:
****
***
**
*

6. Diamond Pattern
def diamond(n):
for i in range(1, n+1):
print(" "*(n-i)+"*"*(2*i-1))
for i in range(n-1,0,-1):
print(" "*(n-i)+"*"*(2*i-1))

diamond(3)
Output:
*
***
*****
***
*

7. Hollow Square
def hollow_square(n):
for i in range(n):
if i==0 or i==n-1:
print("* "*n)
else:
print("* "+" "*(n-2)+"*")
hollow_square(4)
Output:
****
* *
* *
****

8. Left Triangle
def left_triangle(n):
for i in range(1,n+1):
print(" "*(n-i)+"*"*i)

left_triangle(4)
Output:
*
**
***
****

9. Hourglass Pattern
def hourglass(n):
for i in range(n,0,-1):
print("* "*i)
for i in range(2,n+1):
print("* "*i)

hourglass(3)
Output:
***
**
*
**
***
10. Floyd Star Pattern
def floyd(n):
for i in range(1,n+1):
print("*"*i)

floyd(5)
Output:
*
**
***
****
*****

11. Cross Pattern


def cross(n):
for i in range(n):
for j in range(n):
if i==j or i+j==n-1:
print("*",end="")
else:
print(" ",end="")
print()

cross(5)
Output:
* *
**
*
**
* *

12. X Pattern
def x_pattern(n):
cross(n)
x_pattern(5)
Output:
* *
**
*
**
* *

13. Checkerboard
def checker(n):
for i in range(n):
for j in range(n):
print("*" if (i+j)%2==0 else " ", end="")
print()

checker(4)
Output:
**
**
**
**

14. Vertical Line


def vertical(n):
for i in range(n):
print("*")

vertical(4)
Output:
*
*
*
*
15. Horizontal Line
def horizontal(n):
print("* "*n)

horizontal(5)
Output:
*****

Python Programs (Functions)

1. Add Two Numbers


def add(a, b):
return a + b

# Sample Run
print(add(5, 3))

Output:
8

2. Maximum of Two Numbers


def maximum(a, b):
return a if a > b else b

print(maximum(10, 7))

Output:
10

3. Factorial
def factorial(n):
fact = 1
for i in range(1, n+1):
fact *= i
return fact

print(factorial(5))

Output:
120

4. Simple Interest
def simple_interest(p, r, t):
return (p*r*t)/100

print(simple_interest(1000, 5, 2))

Output:
100.0

5. Compound Interest
def compound_interest(p, r, t):
amount = p*(1+r/100)**t
return amount - p

print(compound_interest(1000, 5, 2))

Output:
102.5

6. Armstrong Number
def is_armstrong(n):
power = len(str(n))
s = sum(int(d)**power for d in str(n))
return s == n

print(is_armstrong(153))
Output:
True

7. Area of Circle
def area_circle(r):
return 3.14159*r*r

print(area_circle(2))

Output:
12.56636

8. Prime Numbers in Interval


def primes(start, end):
result = []
for num in range(start, end+1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
[Link](num)
return result

print(primes(10, 20))

Output:
[11, 13, 17, 19]

9. Check Prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

print(is_prime(7))

Output:
True

10. Nth Fibonacci Number


def nth_fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a+b
return a

print(nth_fib(7))

Output:
13

11. Check Fibonacci


def is_fibonacci(num):
a, b = 0, 1
while a <= num:
if a == num:
return True
a, b = b, a+b
return False

print(is_fibonacci(21))

Output:
True
12. Nth Multiple in Fibonacci
def nth_multiple_fib(n, m):
a, b = 0, 1
count = 0
while True:
if a != 0 and a % m == 0:
count += 1
if count == n:
return a
a, b = b, a+b

print(nth_multiple_fib(2, 3))

Output:
21

13. ASCII Value


def ascii_val(ch):
return ord(ch)

print(ascii_val('A'))

Output:
65

14. Sum of Squares


def sum_squares(n):
return sum(i*i for i in range(1, n+1))

print(sum_squares(5))

Output:
55
15. Sum of Cubes
def sum_cubes(n):
return sum(i**3 for i in range(1, n+1))

print(sum_cubes(3))

Output:
36

#Python Filtering Programs

Question 1: Filter elements greater than 10 and less than 50


Program:
arr = [5, 12, 45, 60, 9, 30]
result = [x for x in arr if x > 10 and x < 50]
print(result)
Test Case 1 Output: [12, 45, 30]
Test Case 2:
arr = [10, 20, 50, 49, 11]
Output: [20, 49, 11]

Question 2: Get even numbers greater than 20


Program:
arr = [10, 22, 35, 44, 19, 60]
result = [x for x in arr if x > 20 and x % 2 == 0]
print(result)
Test Case 1 Output: [22, 44, 60]
Test Case 2:
arr = [18, 21, 24, 50, 13]
Output: [24, 50]

Question 3: Extract elements less than 15 or greater than 60


Program:
arr = [5, 14, 20, 61, 80]
result = [x for x in arr if x < 15 or x > 60]
print(result)
Test Case 1 Output: [5, 14, 61, 80]
Test Case 2:
arr = [15, 10, 70, 40, 2]
Output: [10, 70, 2]

Question 4: Numbers divisible by 3 but not by 2


Program:
arr = [3, 6, 9, 12, 15, 18]
result = [x for x in arr if x % 3 == 0 and x % 2 != 0]
print(result)
Test Case 1 Output: [3, 9, 15]
Test Case 2:
arr = [21, 24, 27, 30]
Output: [21, 27]

Question 5: Elements between 25 and 75 inclusive


Program:
arr = [10, 25, 50, 75, 80]
result = [x for x in arr if 25 <= x <= 75]
print(result)
Test Case 1 Output: [25, 50, 75]
Test Case 2:
arr = [30, 70, 76, 24]
Output: [30, 70]

Question 6: Numbers negative or zero


Program:
arr = [-5, 0, 3, -2, 7]
result = [x for x in arr if x <= 0]
print(result)
Test Case 1 Output: [-5, 0, -2]
Test Case 2:
arr = [0, -1, -10, 4]
Output: [0, -1, -10]

Question 7: Values either 10, 20, or 30


Program:
arr = [10, 15, 20, 25, 30]
result = [x for x in arr if x in (10,20,30)]
print(result)
Test Case 1 Output: [10, 20, 30]
Test Case 2:
arr = [5, 10, 40, 20]
Output: [10, 20]

Question 8: Elements greater than mean of array


Program:
arr = [10, 20, 30, 40]
mean = sum(arr)/len(arr)
result = [x for x in arr if x > mean]
print(result)
Test Case 1 Output: [30, 40]
Test Case 2:
arr = [5, 15, 25]
Output: [25]

Question 9: Filter non-zero elements


Program:
arr = [0, 5, 0, 8, 2]
result = [x for x in arr if x != 0]
print(result)
Test Case 1 Output: [5, 8, 2]
Test Case 2:
arr = [1, 0, 3, 0]
Output: [1, 3]

Question 10: Odd numbers less than 40


Program:
arr = [5, 12, 33, 41, 27]
result = [x for x in arr if x % 2 != 0 and x < 40]
print(result)
Test Case 1 Output: [5, 33, 27]
Test Case 2:
arr = [1, 3, 40, 55]
Output: [1, 3]

You might also like