Python programs
Python programs
# 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!
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(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)
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
Enter a number:2
Square of a given number: 1.4142135623730951
perimeter s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))"""
import math
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)
import cmath
t=(b*b)-(4*a*c)
sol1= (-b+[Link](t))/(2*a)
sol2= (-[Link](t))/(2*a)
print("Before swapping:")
print("a=", a, "b=", b)
temp=a
a=b
b=temp
print("After swapping:")
print("a=", a, "b=", b)
print("After swapping:")
print("a=", a, "b=", b)
Before swapping:
a= 24 b= 50
After swapping:
a= 50 b= 24
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
random number:57
#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
[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: "))
#Divisible by 5 and 11
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
#Valid Triangle
Enter side1: 1
Enter side2: 2
Enter side3: 3
Invalid Triangle
#Simple Calculator
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")
#Voting Eligibility
#Type of Triangle
if a == b == c:
print("Equilateral")
elif a == b or b == c or a == c:
print("Isosceles")
else:
print("Scalene")
#Character Type
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
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")
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
#Armstrong Number
if sum == n:
print("Armstrong Number")
else:
print("Not Armstrong")
if [Link]():
print("Alphabet")
elif [Link]():
print("Digit")
else:
print("Special Symbol")
print("Oldest:", max(a,b,c))
print("Youngest:", min(a,b,c))
#Bonus Calculation
if exp > 5:
bonus = salary * 0.05
print("Bonus:", bonus)
else:
print("No bonus")
#Century Year
if year % 100 == 0:
print("Century Year")
else:
print("Not a Century Year")
#Profit or Loss
if sp > cp:
print("Profit:", sp-cp)
elif cp > sp:
print("Loss:", cp-sp)
else:
print("No Profit No Loss")
#Square or Rectangle
if l == b:
print("Square")
else:
print("Rectangle")
try:
val = int(x)
print("Integer")
except:
try:
val = float(x)
print("Float")
except:
print("String")
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
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.
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
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
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)
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)
list=["aaaa","bbbb","cccc","aaaa"]
print(list)
print(len(list))
cccc
eeee
['cccc', 'dddd', 'eeee']
['bbbb', 'cccc', 'dddd']
['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee']
ffff
['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee']
"""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."""
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")
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
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
for x in range(6):
print(x)
0
1
2
3
4
5
aaa
bbb
for x in range(6):
print(x)
0
1
2
3
4
5
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)
20 10
20 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
Enter a number:44
44 is not a prime 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
import random
print(f"random number:{[Link](1,100)}")
random number:30
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
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
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
#Built in functions
#print(), len(), type(), sum(), max()
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()
display("shabana")
Welcome shabana
def display(name):
print("Welcome", name)
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)
Sum= 30
#Split()
a, b = map(int, input("Enter 2 numbers: ").split(",")) # input is comma separated
print(a);print(b)
a,b=map(int,input("Enter 2 numbers:").split())
x=sum(a,b)
print("sum=", x)
Enter 2 numbers:20 30
sum= 50
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)
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
display(10,20)
All args= (10, 20)
1st arg= 10
details(name="Shabana", age=20)
{'name': 'Shabana', 'age': 20}
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()
print(x) # Output: 50
50
24
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
square(3)
Output:
***
***
***
2. Right Triangle
def right_triangle(n):
for i in range(1, n+1):
print("* " * i)
right_triangle(4)
Output:
*
**
***
****
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:
*
**
***
****
*****
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:
**
**
**
**
vertical(4)
Output:
*
*
*
*
15. Horizontal Line
def horizontal(n):
print("* "*n)
horizontal(5)
Output:
*****
# Sample Run
print(add(5, 3))
Output:
8
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
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
print(nth_fib(7))
Output:
13
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
print(ascii_val('A'))
Output:
65
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