Using arithmetic operator in python. Operators in python.
Operator meaning example output
+ it is used for print(8+3) 11 a =5
addition b = 10
- it is used for print(8-3) 5 print(a==b)
print(a!=b)
subtraction
print(a>b)
* it is used for print(8*3) 24
print(a<b)
multiplication print(a>=b)
/ it is used for print(8/3) 2.66667 print(a<=b)
division 1. Write a python program to swap to given
% it is used for print(8%3) 2 number.
modulus x=int(input("enter the first number"))
** it is used for print(8**3) 512 y=int(input("enter the second number"))
exponentials x, y = y, x
a=8 print("x:", x)
b=3 print("y:", y)
sum=a+b
differene=a-b 2. Write a Python program to print "Hello,
product= a*b World!".
division=a/b Solution
modulus=a%b print("Hello World")
exp=a**b 3. Write a Python program to create a simple
print ("the sum of two number is",sum) calculator that can perform addition,
print ("the difference of two number is",differene)
subtraction, multiplication, and division.
print ("the product of two number is",product)
Solution
print ("the division of two number is",division)
a=input("enter what you want(+,-,*,/) ")
print ("the modulus of two number is",modulus)
b=int(input("enter first number"))
print ("the expontial of two number is",exp)
c=int(input("enter second number"))
Relational operator used in python
Name operator description example output
if(a == "+"):
Equal to == Two things 5==5 sum = b+c
are exactly print("sum is ",sum)
the same
Not equal to != Two things 3!=5
elif(a =="-"):
are not the dif =b-c
same print("difference is ",dif)
Greater than > one is 7>5
greater than
elif(a =="*"):
the other mul =b*c
Less than < One is less 3<9 print("multiplication is",mul)
than the
other
else:
Greater than >= Is greater or 8>=8 div =b/c
or equal to equal to print("division is",div)
another
Less than or <= Is less or 4<=6
equal to equal to 4. Write a python program to print a person is
another voter or not.
age = int(input("enter the age"))
if age >= 18:
print("you are voter")
else:
print ("you are not voter")
5. Write a python program a number is print(f"your name is {name}")
positive, negative or zero. print(f"you are {age} year old")
number = int (input("enter the number"))
if number > 0: 11. Write a Python program to convert a given
print("The number is positive.") string to uppercase and lowercase
elif number < 0: Solution
print("The number is negative.") text=input("enter a string")
else: uppercase=[Link]()
print("The number is zero.") lowercase=[Link]()
print("string in uppercase",uppercase)
6. Write a Python program to convert a print("string in lowercase",lowercase)
temperature from Celsius to Fahrenheit 12. Write a python program to input your name
and Kelvin. for 5 times.
Solution name=str(input("enter the name"))
celsius = float(input("Enter temperature in Celsius: ")) for i in range(5):
fahrenheit = (celsius * 9/5) + 32 print("the name of person is ",name)
kelvin = celsius + 273.15
print("temperature in Fahrenheit",fahrenheit) 13. Write a Python program to count the
print("temperature in Kelvin",kelvin) number of times a specified value appears
7. Write a python program to input 3 side of in a string.
triangle and print area. Solution
a = float(input('Enter first side: ')) text=input("enter a string")
b = float(input('Enter second side: ')) value=input("enter a value to count")
c = float(input('Enter third side: ')) count=[Link](value)
s = (a + b + c) / 2 print(f"the value appare {count} time")
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is',area) 14. Write a Python program to check if a
8. Write a python program to calculate area number is even or odd.
and circumference of circle. Solution
radius=int(input("enter the radius")) num=int(input("enter a number "))
area=(22/7)*radius*radius if(num%2==0):
circumference=2*(22/7)*radius print("number is even")
print("the area of circle is",area) else:
print("the circumference is ",circumference) print("number is odd")
9. Write a python program to calculate sum,
difference and average of given two numbers. 15. Write a Python program to check if a year
a=int(input("enter the first number")) is a leap year.
b=int(input("enter the second number"))
Solution
sum=a+b
year=int(input("enter year"))
difference=a-b
if(year%4==0):
average=((a+b)/2)
print("the year is leap year")
print("the sum is",sum)
else:
print("the difference is",difference)
print("the year is not leap year")
print("the average is",average)
16. Write a Python program to find the largest
10. Write a Python program using f-strings to
of three numbers using nested if-else
display a person's name and age.
statements.
Solution
Solution
name = input("Enter your name: ")
age = input("Enter your age: ")
num1=int(input("enter first number"))
num2=int(input("enter second number")) print("number is in range of 10 to 20")
num3=int(input("enter third number")) else:
if(num1>num2): print("number is not in range of 10 to 20")
if(num1>num3): 20. Write a Python program to print numbers
print("number first is grater ie.",num1) from 1 to 10 using a for loop.
else: Solution
print("number third is grater ie.",num3) for i in range(1, 11):
else: print(i)
21. Write a Python program to print numbers
if(num2>num3):
from 1 to 10 even number using a for loop.
print("number second is grater ie.",num2)
for i in range(1, 11,2):
else:
print(i)
print("number third is grater ie.",num3)
22. Write a Python program to print all even
17. Write a Python program to find the greatest
numbers from 1 to 100 using a for loop.
number among n numbers.
Solution
Solution
for i in range(2, 101, 2):
n = int(input("Enter the number of elements: print(i)
"))
greatest = None 23. Write a Python program to print the sum
for i in range(n): of all odd numbers from 1 to 50 using a
num = float(input(f" Enter number {i+1}: ")) while loop.
if greatest is None or num > greatest: Solution
greatest = num i=1
print(f "The greatest number is: {greatest}" total = 0
while i <= 50:
18. Write a Python program to assign a letter if i % 2!= 0:
grade (A, B, C, D, F) based on a student's total += i
score. i += 1
Solution print("Sum of all odd numbers from 1 to 50 is:", total)
score = float(input("Enter the student's score (0 to
100): ")) 24. Write a Python program to print the
if score >= 90: multiplication table of a given number
grade = 'A' using a for loop.
elif score >= 80: Solution
grade = 'B' num = int(input("Enter a number to print its multiplication
elif score >= 70: table: "))
grade = 'C' print("multiplication Table of {num}:")
elif score >= 60: for i in range(1, 11):
grade = 'D' print(f"{num} x {i} = {num * i}")
else:
grade = 'F' 25. Write a Python program to find the
print("The student's grade is:", grade) factorial of a number using a for loop.
Solution
19. Write a Python program to check if a
num = int(input("Enter a number to
number is within a specific range. find its factorial: "))
Solution factorial = 1
num=int(input("enter a number:")) if num < 0:
if(num>=10 and num<=20):
print("Factorial is not defined print(a)
for negative numbers.") a, b = b, a + b
else: count += 1
for i in range(1, num + 1):
factorial *= i 29. Write a Python program to check if a
print(f"The factorial of {num} is number is an Armstrong number using a
{factorial}") while loop.
Solution
26. Write a Python program to print the num = int(input("Enter a number: "))
reverse of a given number using a while original_num = num
loop. result = 0
Solution num_digits = len(str(num))
num = int(input("Enter a number to reverse: while num > 0:
")) digit = num % 10
reversed_num = 0 result += digit ** num_digits
original_num = num num = num // 10
while num > 0: if result == original_num:
print(f"{original_num} is an Armstrong number.")
digit = num % 10
else:
reversed_num = reversed_num * 10 + digit
print(f"{original_num} is not an Armstrong number.")
num = num // 10
print(f"The reverse of {original_num} is 30. Write a Python program to print the sum of
{reversed_num}") the digits of a given number using a while
loop.
27. Write a Python program to print all prime Solution
numbers between 1 and 100 using nested num = int(input("Enter a number: "))
loops. original_num = num
Solution digit_sum = 0
print("Prime numbers between 1 and 100:") while num > 0:
for num in range(2, 101): digit = num % 10
is_prime = True digit_sum += digit
for i in range(2, int(num ** 0.5) + 1): num = num // 10
if num % i == 0: print(f"The sum of the digits of {original_num} is
is_prime = False {digit_sum}")
break
if is_prime: 31. Write a Python program to print the first
print(num) 10 multiples of a given number using a for
loop.
28. Write a Python program to print the Solution
Fibonacci series up to a specified number of num = int(input("Enter a number: "))
terms using a while loop. print(f"The first 10 multiples of {num} are:")
Solution for i in range(1, 11):
n_terms = int(input("Enter the number of terms: ")) print(f"{num} x {i} = {num * i}")
a, b = 0, 1 32. Write a Python program to find the sum of
count = 0 all elements in a list using a for loop.
if n_terms <= 0: Solution
print("Please enter a positive integer.")
numbers = [10, 20, 30, 40, 50]
else:
total_sum = 0
print("Fibonacci series:")
for num in numbers:
while count < n_terms:
total_sum += num
print("The sum of all elements in the list is:", total_sum) list1 = [1, 2, 3]
list2 = [4, 5, 6]
33. Write a Python program to print a merged_list = list1 + list2
multiplication table using nested loops. print("Merged list:", merged_list)
Solution
num = int(input("Enter a number to print its 32. Find common elements between two lists
multiplication table: ")) Solution
print(f"Multiplication Table of {num}:") ist1 = [1, 2, 3, 4]
for i in range(1, 11): list2 = [3, 4, 5, 6]
common = list(set(list1) & set(list2))
for j in range(1, 11):
print("Common elements:", common)
print(f"{num} x {j} = {num * j}", end="\t")
33. Create a dictionary, add key-value pairs, and
print()
print it
34. 26. Write a Python program to create a list,
Solution
add elements to it, and print the list.
my_dict = {}
Solution my_dict["name"] = "Alice"
my_list = [] my_dict["age"] = 25
my_list.append("apple") my_dict["city"] = "New York"
my_list.append("banana") print("Dictionary:", my_dict)
my_list.append("cherry")
my_list.append("mango")
34. Calculate square root using sqrt() from math
print("The list contains:", my_list)
module
27. Find the sum of all elements in a list
Solution
numbers = [5, 10, 15, 20]
import math
total = sum(numbers)
number = 25
print("Sum of elements:", total)
sqrt_value = [Link](number)
print(f"Square root of {number} is {sqrt_value}")
28. Find the maximum and minimum elements in
a list
35. Implicit and Explicit Type Casting
Solution
Solution
numbers = [4, 9, 2, 15, 6]
a = 10
maximum = max(numbers)
b = 3.5
minimum = min(numbers)
print("Maximum:", maximum) c=a+b
print("Minimum:", minimum) print("Implicit casting result:", c, type(c))
x = "100"
29. Remove duplicates from a list y = int(x) + 20
Solution print("Explicit casting result:", y, type(y))
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers)) 36. Verify user credentials (username and
print("List without duplicates:", unique_numbers) password)
Solution
30. Sort a list in ascending order username = input("Enter username: ")
Solution password = input("Enter password: ")
numbers = [5, 2, 9, 1, 7] if username == "admin" and password == "1234":
[Link]() print("Login successful!")
print("Sorted list:", numbers) else:
print("Invalid credentials.")
31. Merge two lists
37. Reverse a string
Solution
Solution while count < terms:
string = "hello" print(a, end=" ")
reversed_string = string[::-1] a, b = b, a + b
print("Reversed string:", reversed_string) count += 1
44. Check if a number is a palindrome
38. Count the number of vowels in a string Solution
Solution num = int(input("Enter a number: "))
string = "programming" if str(num) == str(num)[::-1]:
vowels = "aeiouAEIOU" print("Number is a palindrome")
count = sum(1 for char in string if char in vowels) else:
print("Number of vowels:", count) print("Number is not a palindrome")
39. Find the length of a string 45. Check if a number is Armstrong or not
Solution Solution
string = "OpenWe" num = int(input("Enter a number: "))
length = len(string) sum_of_powers = sum(int(digit) ** len(str(num)) for digit in
print("Length of string:", length) str(num))
if num == sum_of_powers:
40. Check if a string is a palindrome print("Armstrong number")
Solution else:
print("Not an Armstrong number")
string = "madam"
if string == string[::-1]:
print("Palindrome") 46. Print all prime numbers up to a specified
else: number using nested loops
print("Not a palindrome") Solution
n = int(input("Enter upper limit: "))
41. Calculate simple interest print("Prime numbers up to", n, ":")
Solution for num in range(2, n+1):
P = float(input("Enter principal: ")) for i in range(2, num):
R = float(input("Enter rate of interest: ")) if num % i == 0:
T = float(input("Enter time (years): ")) break
SI = (P * R * T) / 100 else:
print("Simple Interest:", SI) print(num, end=" ")
42. Calculate factorial using a while loop [Link] a Python program to print a right-angled
Solution triangle of numbers. The height of the triangle
num = int(input("Enter a number: ")) should be taken as input from the user.
factorial = 1 Solution
i=1 height = int(input("Enter the height of the triangle: "))
while i <= num: for i in range(1, height + 1):
factorial *= i for j in range(1, i + 1):
i += 1 print(j, end=" ")
print("Factorial:", factorial) print() # Newline after each row
48. Write a Python program to print an inverted
43. Generate Fibonacci sequence up to a number right-angled triangle of stars. The height of the
of terms triangle should be taken as input from the user.
Solution Solution
terms = int(input("Enter number of terms: ")) height = int(input("Enter the height of the triangle: "))
a, b = 0, 1 for i in range(height, 0, -1):
count = 0 print('*' * i)
49. Write a python program to display calendar. rows=5
import calendar for i in range (1,rows+1):
year = int (input("enter the year")) print ('*'*i)
month = int (input("enter the months")) *****
calendar= [Link](year,month) ****
print("calender",calendar)
50. Write a python program to calculate sum of given
***
number. **
def NNS (n): *
if n <= 1: rows=5
return n for i in range (rows,0,-1):
else: print ('*'*i)
return (n)+NNS(n-1)
n=int(input("enter the number")) *
if n<=0: ***
print("enter a positive number")
else:
*****
print ("the sum of natural number of given * ******
numbers",NNS(n)) *********
rows=5
51. Write a python program to print first 10 natural for i in range(1,rows+1):
number. print(' '*(rows-i)+'*'*(2*i-1))
a=1
while a < 11 : Write a program to count the words in
print(a) sentence.
a= a+1
words="hello my name is Pradip Bhusal"
def count_words(sentences):
52. Write a python program to print middle number. return len([Link]())
a=int(input("enter the first number")) print(count_words(words))
b=int(input("enter the second number"))
c=int(input("enter the third number"))
if a>b and a<c or a<b and a>c:
print("the middle number is a")
elif b>a and b<c or b<a and b>c:
print("the middle number is b")
else:
print("the middle number is c ")
Write a program to display today , year, months and day.
from datetime import date
today=[Link]()
print("today:",today)
print("year:",[Link])
print("month:",[Link])
print("day:",[Link])
Display series.
*
**
***
****
*****