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

Python Class Work Problems

The document provides a series of Python example problems, each illustrating a specific programming concept or task. Examples include printing 'Hello, world!', adding numbers, calculating square roots, solving quadratic equations, and working with matrices. Each example includes source code, a brief explanation, and the expected output.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Python Class Work Problems

The document provides a series of Python example problems, each illustrating a specific programming concept or task. Examples include printing 'Hello, world!', adding numbers, calculating square roots, solving quadratic equations, and working with matrices. Each example includes source code, a brief explanation, and the expected output.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON EXAMPLE PROBLEMS

1. Python program to print hello world:

Source code:

# This program prints Hello, world!

print('Hello, world!')

Output:

Hello, world!

2. Python program to add two numbers:

Source code:

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

Output:

The sum of 1.5 and 6.3 is 7.8

3. Python program add two numbers with user input:

Source code:

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

Output:

Enter first number: 1.5


Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8

4. Python program to calculate the square root of a number:

Source code:

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

Output:

The square root of 8.000 is 2.828

5. Python program to find the square root of a real or complex numbers:

Source code:

# Find square root of real or complex numbers


# Importing the complex math module
import cmath

num = 1+2j

# To take input from the user


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

num_sqrt = [Link](num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num
,num_sqrt.real,num_sqrt.imag))

Output:

The square root of (1+2j) is 1.272+0.786j

6. Python program to find the area of a triangle:

If a, b, c are the three sides of a triagle,

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)

Output:

The area of the triangle is 14.70

7. Python program to solve quadratic equation:

The standard form of a quadratic equation is:

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

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

Source code:

# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath

a = 1
b = 5
c = 6

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-[Link](d))/(2*a)
sol2 = (-b+[Link](d))/(2*a)

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

Output:

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

8. Python program to swap two variables:

Source code:

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

Output:

The value of x after swapping: 10


The value of y after swapping: 5
9. Python program to convert kilometers to miles:

Source code:

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

Output:

Enter value in kilometers: 3.5


3.50 kilometers is equal to 2.17 miles

10. Python program to convert temperature from Celsius to Fahrenheit:

fahrenheit = celsius * 1.8 + 32

Source code:

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

Output:
37.5 degree Celsius is equal to 99.5 degree Fahrenheit

11. Python program to check if a number is positive, negative or 0:

Source code: using if…elif..else

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


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Source code: 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")

Output:

Enter a number: 2
Positive number

12. Python program to check if a number is odd or even:

Source code:

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

Output:

Enter a number: 43
43 is Odd

13. Python program to check if a year is leap year or not:

A leap year is exactly divisible by 4 except for century years (years ending with 00). The century
year is a leap year only if it is perfectly divisible by 400. For example,

2017 is not a leap year


1900 is a not leap year
2012 is a leap year
2000 is a leap year

Source code:

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

year = 2000

# To get year (integer input) from the user


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

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


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

# not divided by 100 means not a century year


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

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))

Output:

2000 is a leap year

14. Python program to find the largest among three numbers:

In the program below, the three numbers are stored in num1, num2 and num3 respectively.
We've used the if...elif...else ladder to find the largest among the three and display it.

Source code:

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


Output:

The largest number is 14.0

15. Python program to check if a number is prime or not:

Source code:

# Program to check if a number is prime or not

num = 29

# To take input from the user


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

# define a flag variable


flag = False

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

# check if flag is True


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

Output:
29 is a prime number

16. Python program to find the factorial of a number:

Source code:

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

# change the value for a different result


num = 7

# To take input from the user


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

factorial = 1

# check if the number is negative, positive or zero


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

Output:

The factorial of 7 is 5040

17. Python program to print the Fibonacci sequence:

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....


The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.
This means to say the nth term is the sum of (n-1)th and (n-2)th term.

Source code:
# Program to display the Fibonacci sequence up to n-th term

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

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:

How many terms? 7


Fibonacci sequence:
0
1
1
2
3
5
8

18. Python program to find the sum of natural numbers:


Source code:

# Sum of natural numbers up to num

num = 16

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

Output:

The sum is 136

19. Python program to find the factors of a number:

Source code:

# Python Program to find the factors of a number

# This function computes the factor of the argument passed


def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)

num = 320

print_factors(num)

Output:
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320

20. Python program to display the calendar of a given month and year:

In the program below, we import the calendar module. The built-in function month() inside the
module takes in the year and the month and displays the calendar for that month of the year.

Source code:

# Program to display calendar of the given month and year

# importing calendar module


import calendar

yy = 2014 # year
mm = 11 # month

# To take month and year input from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar


print([Link](yy, mm))

Output:
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

21. Python program to add two matrices:

Source code:

# Program to add two matrices using nested loop

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

# Program to add two matrices using list comprehension

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]

for r in result:
print(r)

Output:

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

22. Python program to multiply two matrices:

Source code:

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]

# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row
in X]

for r in result:
print(r)

Output:

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

23. Python program to sort words in alphabetic order:

Source code:

Program to sort alphabetically the words form a string provided by the user

my_str = "Hello this Is an Example With cased letters"

# To take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = [[Link]() for word in my_str.split()]

# sort the list


[Link]()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

Output:

The sorted words are:


an
cased
example
hello
is
letters
this
with

24. Python program to calculate the power of a number:

Source code:

base = 3
exponent = 4

result = 1

while exponent != 0:
result *= base
exponent-=1
print("Answer = " + str(result))

Output:

Answer = 81

25. Python program to transpose a matrix:

Source code:

# Program to transpose a matrix using a nested loop

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)

'' Program to transpose a matrix using list comprehension'''

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]

for r in result:
print(r)
Output:

[12, 4, 3]
[7, 5, 8]

26. Python program to check whether a string is palindrome or not:

A palindrome is a string that is the same read forward or backward.


For example, "dad" is the same in forward or reverse direction. Another example is
"aibohphobia", which literally means, an irritable fear of palindromes.

Source code:
# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


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

Output:

The string is a palindrome.

You might also like