Home | | Problem Solving and Python Programming | Example Python Programs on Control Flow, Functions

Problem Solving and Python Programming - Example Python Programs on Control Flow, Functions | Problem Solving and Python Programming : Control Flow, Functions

Chapter: Problem Solving and Python Programming : Control Flow, Functions

Example Python Programs on Control Flow, Functions

Problem Solving and Python Programming : Control Flow, Functions

Program

 

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

 

#change the value for a different result num = 7

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

 

2. Python program to find the factorial of a number using recursion.

 

def recur_factorial(n):

"""Function to return the factorial of a number using recursion"""

if n == 1:

return n

else:

return n*recur_factorial(n-1)

#Change this value for a different result num = 7

#uncomment to take input from the user #num = int(input("Enter a number: "))

#check is the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of",num,"is",recur_factorial(num))

 

3. 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 between", num1, ",", num2, "and", num3, "is",largest)

 

4. Python program to find the sum of natural numbers up to n where n is provided by user

 

# change this value for a different result

num = 16

 

# uncomment to take input from the user #num = int(input("Enter a number: "))

 

if num < 0:

print("Enter a positive number")

else:

sum = 0

 

# use while loop to iterate un till zero

while(num > 0):

sum += num

num -= 1

print("The sum is",sum)

 

5. Python program to check if the input number is prime or not


num = 407

 

# take input from the user

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

 

# prime numbers are greater than 1

if num > 1:

# check for factors for i in range(2,num):

if (num % i) == 0:

print(num,"is not a prime number")

print(i,"times",num//i,"is",num)

break

else:

print(num,"is a prime number")

# if input number is less than

# or equal to 1, it is not prime

else:

print(num,"is not a prime number")

 

6. Program to display the Fibonacci sequence up to n-th term where n is provided by the user

 

# change this value for a different result

nterms = 10

 

# uncomment to take input from the user #nterms = int(input("How many terms? "))

 

# first two terms

n1 = 0

n2 = 1

count = 0

 

# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

else:

print("Fibonacci sequence upto",nterms,":")

while count < nterms:

print(n1,end=' , ')

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1

 

7. Python Program to Check Armstrong Number


num = 1634

# Changed num variable to string,

# and calculated the length (number of digits)

order = len(str(num))

 

# initialize sum

sum = 0

 

# find the sum of the cube of each digit

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** order

temp //= 10

 

# display the result

if num == sum:

print(num,"is an Armstrong number")

else:

print(num,"is not an Armstrong number")

 

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


# A number is even if division by 2 give a remainder of 0.

# If remainder is 1, it is 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))

 

9. 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)

 

10. 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)

 

11. Program to transpose a matrix using 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)

 

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

 

# change this value for a different result

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

# uncomment to take input from the user

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

# breakdown the string into a list of words

words = my_str.split()

 

# sort the list

words.sort()

 

# display the sorted words

print("The sorted words are:")

for word in words:

print(word)

 

13. Python program to find the H.C.F of two input number

 

# define a function

def computeHCF(x, y):

 

# choose the smaller number

if x > y:

smaller = y else:

smaller = x

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

if((x % i == 0) and (y % i == 0)):

hcf = i

 

return hcf

 

num1 = 54

num2 = 24

 

# take input from the user

# num1 = int(input("Enter first number: "))

# num2 = int(input("Enter second number: "))

 

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

 

14. Linear search

 

list = [4,1,2,5,3] #set up array

search = int(input("Enter search number"))

 

# ask for a number

 

for i in range(0,len(list)):

 

# repeat for each item in list

if search==list[i]:

 

#if item at position i is search time

print(str(search) + " found at position " + str(i))

#report find

 

15. Binary search

 

def binary_search(item_list,item):

first = 0

last = len(item_list)-1

found = False

 

while( first<=last and not found):

mid = (first + last)//2

if item_list[mid] == item :

found = True

else:

if item < item_list[mid]:

last = mid - 1

else:

first = mid + 1

return found

print(binary_search([1,2,3,5,8], 6))

print(binary_search([1,2,3,5,8], 5))

 

16. Program to find Fibonacci series upto n

 

>>>        def fib(n): # write Fibonacci series up to n

... """Print a Fibonacci series up to n."""

... a, b = 0, 1

... while a < n:

... print(a)

... a, b = b, a+b

...

>>>        # Now call the function we just defined:

... fib(2000)

 

 

Tags : Problem Solving and Python Programming , Problem Solving and Python Programming : Control Flow, Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : Example Python Programs on Control Flow, Functions | Problem Solving and Python Programming


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.