Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
185 views

Python Program

The document discusses various Python programming concepts including: 1. Working with numbers through examples of sorting arrays in ascending and descending order and finding the factorial of a number recursively. 2. Implementing simple calculator operations like addition, subtraction, multiplication and division through functions. 3. Taking user input to select an operation and enter numbers, then printing the result. The programs provide code samples to demonstrate common Python tasks like string operations, file handling, object oriented programming and more.

Uploaded by

CS BCA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
185 views

Python Program

The document discusses various Python programming concepts including: 1. Working with numbers through examples of sorting arrays in ascending and descending order and finding the factorial of a number recursively. 2. Implementing simple calculator operations like addition, subtraction, multiplication and division through functions. 3. Taking user input to select an operation and enter numbers, then printing the result. The programs provide code samples to demonstrate common Python tasks like string operations, file handling, object oriented programming and more.

Uploaded by

CS BCA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

PROGRAMMING USING PYTHON

1. Working with numbers


2. Implementing String operations
3. Working with Tuples and Set
4. Implementation of Dictionaries
5. Demonstrating List Operations.
6. Flow Control and Functions
7. Modules and Packages
8. File handling
9. Object Oriented Programming
10. Exception Handling and Regular Expressions

Program 5-2 Write a program to display values of


variables in Python.
#Program 5-2
#To display values of variables
message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)
Output:
Keep Smiling
User Number is 101

Program 5-3 Write a Python program to find the area


of a rectangle given that its length is 10
units and breadth is 20 units.
#Program 5-3
#To find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)
Output:
200

Program 5-4 Write a Python program to find the sum of


two numbers.
#Program 5-4
#To find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)
Output:
30

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

Output
2000 is a leap year

# Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Run Code

Output

Prime numbers between 900 and 1000 are:


907
911
919
929
937
941
947
953
967
971
977
983
991
997

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

Output

The factorial of 7 is 5040

# Multiplication table (from 1 to 10) in Python

num = 12

# To take input from the user


# num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Run Code

Output

12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

# Program make a simple calculator

# This function adds two numbers


def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break

else:
print("Invalid Input")

Output

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
1. Working with numbers

Python program to sort the elements of an array in


ascending order
In this program, we need to sort the given array in ascending order such that elements will be
arranged from smallest to largest. 

ALGORITHM:
o STEP 1: Declare and initialize an array.
o STEP 2: Loop through the array and select an element.
o STEP 3: The inner loop will be used to compare the selected element from the outer
loop with the rest of the elements of the array.
o STEP 4: If any element is less than the selected element then swap the values.
o STEP 5: Continue this process till entire array is sorted in ascending order.

PROGRAM:
1. #Initialize array     
2. arr = [5, 2, 8, 7, 1];     
3. temp = 0;    
4.      
5. #Displaying elements of original array    
6. print("Elements of original array: ");    
7. for i in range(0, len(arr)):    
8.     print(arr[i], end=" ");    
9.      
10. #Sort the array in ascending order    
11. for i in range(0, len(arr)):    
12.     for j in range(i+1, len(arr)):    
13.         if(arr[i] > arr[j]):    
14.             temp = arr[i];    
15.             arr[i] = arr[j];    
16.             arr[j] = temp;    
17.      
18. print();    
19.      
20. #Displaying elements of the array after sorting    
21.     
22. print("Elements of array sorted in ascending order: ");    
23. for i in range(0, len(arr)):    
24.     print(arr[i], end=" ");    

Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8

PROGRAM:
1. #Initialize array     
2. arr = [5, 2, 8, 7, 1];     
3. temp = 0;    
4.      
5. #Displaying elements of original array    
6. print("Elements of original array: ");    
7. for i in range(0, len(arr)):     
8.     print(arr[i]),    
9.      
10. #Sort the array in descending order    
11. for i in range(0, len(arr)):    
12.     for j in range(i+1, len(arr)):    
13.         if(arr[i] < arr[j]):    
14.             temp = arr[i];    
15.             arr[i] = arr[j];    
16.             arr[j] = temp;    
17.      
18. print();    
19.      
20. #Displaying elements of array after sorting    
21. print("Elements of array sorted in descending order: ");    
22. for i in range(0, len(arr)):     
23.     print(arr[i]),   

Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in descending order:
8 7 5 2 1

Python Program to Find Factorial of Number


Using Recursion
Factorial: Factorial of a number specifies a product of all integers from 1 to that
number. It is defined by the symbol explanation mark (!).

For example: The factorial of 5 is denoted as 5! = 1*2*3*4*5 = 120.

See this example:

def recur_factorial(n):  
if n == 1:  
       return n  
   else:  
       return n*recur_factorial(n-1)  
# 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))  

Output:

9M

158

Elon Musk Set to Collect $23B Tesla Bonus

Next

Stay
Python Program to Make a Simple Calculator
In Python, we can create a simple calculator for performing the different arithmetical
operations, such as addition, subtraction, multiplication, and division.

Approach:
o We can choose the desired operation from the option of a, b, c, and d.
o We can take two numbers, and if… elif… else, branching is used for executing the
particular operation.
o We will use add(), subtract(), multiply() and divide() function for evaluation the respective
operation in the calculator.

Example:

1. Please select operation -  
2. a. Add  
3. b. Subtract  
4. c. Multiply  
5. d. Divide  
6. Select operations form a, b, c, d: "c"    
7. Please enter first number: 11  
8. Please enter second number: 4  
9. 11 * 4 = 44  

Code: for Simple Calculator

def add(P, Q):    
   # This function is used for adding two numbers   
   return P + Q   
def subtract(P, Q):   
   # This function is used for subtracting two numbers   
   return P - Q   
def multiply(P, Q):   
   # This function is used for multiplying two numbers   
   return P * Q   
def divide(P, Q):   
   # This function is used for dividing two numbers    
   return P / Q    
# Now we will take inputs from the user    
print ("Please select the operation.")    
print ("a. Add")    
print ("b. Subtract")    
print ("c. Multiply")    
print ("d. Divide")    
    
choice = input("Please enter choice (a/ b/ c/ d): ")    
    
num_1 = int (input ("Please enter the first number: "))    
num_2 = int (input ("Please enter the second number: "))    
    
if choice == 'a':    
   print (num_1, " + ", num_2, " = ", add(num_1, num_2))    
    
elif choice == 'b':    
   print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))    
    
elif choice == 'c':    
   print (num1, " * ", num2, " = ", multiply(num1, num2))    
elif choice == 'd':    
   print (num_1, " / ", num_2, " = ", divide(num_1, num_2))    
else:    
   print ("This is an invalid input")    

Output:

46.4M

822

Prime Ministers of India | List of Prime Minister of India (1947-2020)


Case - (1):

Please select the operation.


a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): d
Please enter the first number: 1
Please enter the second number: 2
1 / 2 = 0.5

Case - (2):

Please select the operation.


a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): b
Please enter the first number: 12
Please enter the second number: 11
12 - 11 = 1

Python Program to Find Armstrong Number


between an Interval
We have already read the concept of Armstrong numbers in the previous program.
Here, we print the Armstrong numbers within a specific given interval.

See this example:

lower = int(input("Enter lower range: "))  
upper = int(input("Enter upper range: "))  
  
for num in range(lower,upper + 1):  
   sum = 0  
   temp = num  
   while temp > 0:  
       digit = temp % 10  
       sum += digit ** 3  
       temp //= 10  
       if num == sum:  
            print(num)  

This example shows all Armstrong numbers between 100 and 500.

Output:

Python Program to Print the Fibonacci


sequence
In this tutorial, we will discuss how the user can print the Fibonacci sequence of numbers in
Python.

Fibonacci sequence:

Fibonacci sequence specifies a series of numbers where the next number is found by adding up
the two numbers just before it.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … and so on.

Example:

n_terms = int(input ("How many terms the user wants to print? "))  
  
# First two terms  
n_1 = 0  
n_2 = 1  
count = 0  
  
# Now, we will check if the number of terms is valid or not  
if n_terms <= 0:  
    print ("Please enter a positive integer, the given number is not valid")  
# if there is only one term, it will return n_1  
elif n_terms == 1:  
    print ("The Fibonacci sequence of the numbers up to", n_terms, ": ")  
    print(n_1)  
# Then we will generate Fibonacci sequence of number  
else:  
    print ("The fibonacci sequence of the numbers is:")  
    while count < n_terms:  
        print(n_1)  
        nth = n_1 + n_2  
       # At last, we will update values  
        n_1 = n_2  
        n_2 = nth  
        count += 1  

Output:
How many terms the user wants to print? 13
The Fibonacci sequence of the numbers is:
0
1
1
2
3
5
8
13
21
34
55
89
144

2. Implementing String operations


Python Program to Remove Punctuation from a
String
Punctuation:

The practice, action, or system of inserting points or other small marks into texts, in
order to aid interpretation; division of text into sentences, clauses, etc., is called
punctuation. -Wikipedia

Punctuation are very powerful. They can change the entire meaning of a sentence.

See this example:

60.6M

1.1K

Difference between JDK, JRE, and JVM

o "Woman, without her man, is nothing" (the sentence boasting about men's importance.)
o "Woman: without her, man is nothing" (the sentence boasting about women's
importance.)

This program is written to remove punctuation from a statement.


See this example:

1. # define punctuation  
2. punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''  
3. # take input from the user  
4. my_str = input("Enter a string: ")  
5. # remove punctuation from the string  
6. no_punct = ""  
7. for char in my_str:  
8.    if char not in punctuation:  
9.        no_punct = no_punct + char  
10. # display the unpunctuated string  
11. print(no_punct)  

Output:

How to reverse a string in Python?


Python String is the collection of the Unicode character. Python has numerous functions
for string manipulation, but Python string library doesn't support the in-
built "reverse()" function. But there are various ways to reverse the string. We are
defining the following method to reverse the Python String.

o Using for loop


o Using while loop
o Using the recursion

Using for loop


Here, we will reverse the given string using for loop.

1. def reverse_string(str):  
2.     str1 = ""   # Declaring empty string to store the reversed string  
3.     for i in str:  
4.         str1 = i + str1  
5.     return str1    # It will return the reverse string to the caller function  
6.      
7. str = "JavaTpoint"    # Given String       
8. print("The original string is: ",str)  
9. print("The reverse string is",reverse_string(str)) # Function call  

Output:

('The original string is: ', 'JavaTpoint')


('The reverse string is', 'tniopTavaJ')

Explanation-

Play Video
x

In the above code, we have declared the reverse_string() function and passed


the str argument. In the function body, we have declared empty string variable str1 that
will hold the reversed string.

Next, the for loop iterated every element of the given string, join each character in the
beginning and store in the str1 variable.

After the complete iteration, it returned the reverse order string str1 to the caller
function. It printed the result to the screen.
Using while loop
We can also reverse a string using a while loop. Let's understand the following example.

Example -

1. # Reverse string  
2. # Using a while loop  
3.   
4. str = "JavaTpoint" #  string variable  
5. print ("The original string  is : ",str)   
6. reverse_String = ""  # Empty String  
7. count = len(str) # Find length of a string and save in count variable  
8. while count > 0:   
9.     reverse_String += str[ count - 1 ] # save the value of str[count-1] in reverseString  
10.     count = count - 1 # decrement index  
11. print ("The reversed string using a while loop is : ",reverse_String)# reversed string  

Output:

('The original string is : ', 'JavaTpoint')


('The reversed string using a while loop is : ', 'tniopTavaJ')

Explanation:

In the above code, we have declared a str variable that holds string value. We initialized
a while loop with a value of the string.

In each iteration, the value of str[count - 1] concatenated to the reverse_String and


decremented the count value. A while completed its iteration and returned the reverse
order string.

Using recursion()
The string can also be reversed using the recursion. Recursion is a process where function calls
itself. Consider the following example.

Example -

1. # reverse a string    
2. # using recursion   
3.     
4. def reverse(str):   
5.     if len(str) == 0: # Checking the lenght of string  
6.         return str   
7.     else:   
8.         return reverse(str[1:]) + str[0]   
9.     
10. str = "Devansh Sharma"   
11. print ("The original string  is : ", str)     
12. print ("The reversed string(using recursion) is : ", reverse(str))  

Output:

('The original string is : ', 'JavaTpoint')


('The reversed string(using reversed) is : ', 'tniopTavaJ')

Explanation:

In the above code, we have defined a function that accepts the string as an argument.

In the function body, we defined the base condition of recursion, if a length of a string is
0, then the string is returned, and if not then we called the function recursively.

How to concatenate two strings in Python


Python string is a collection of Unicode characters. Python provides many built-in
functions for string manipulation. String concatenation is a process when one string is
merged with another string. It can be done in the following ways.

o Using + operators
o Using join() method
o Using % method
o Using format() function
Let's understand the following string concatenation methods.

Using + operator
This is an easy way to combine the two strings. The + operator adds the multiple strings
together. Strings must be assigned to the different variables because strings are
immutable. Let's understand the following example.

Example -

1. # Python program to show  
2. # string concatenation  
3.   
4. # Defining strings  
5. str1 = "Hello "  
6. str2 = "Devansh"  
7.   
8. # + Operator is used to strings concatenation  
9. str3 = str1 + str2  
10. print(str3)   # Printing the new combined string  

Output:

Hello Devansh

Explanation:

In the above example, the variable str1 stores the string "Hello", and variable str2 stores
the "Devansh". We used the + operator to combine these two string variables and
stored in str3.

Using join() method


The join() method is used to join the string in which the str separator has joined the
sequence elements. Let's understand the following example.

Example -

1. # Python program to  
2. # string concatenation  
3.   
4. str1 = "Hello"  
5. str2 = "JavaTpoint"  
6.   
7. # join() method is used to combine the strings  
8. print("".join([str1, str2]))  
9.   
10. # join() method is used to combine  
11. # the string with a separator Space(" ")  
12. str3 = " ".join([str1, str2])  
13.   
14. print(str3)  

Output:

HelloJavaTpoint
Hello JavaTpoint

Explanation:

In the above code, the variable str1 stores the string "Hello" and variable str2 stores the
"JavaTpoint". The join() method returns the combined string that is stored in the str1
and str2. The join() method takes only list as an argument.

Using % Operator
The % operator is used for string formatting. It can also be used for string
concatenation. Let's understand the following example.

Example -

1. # Python program to demonstrate  
2. # string concatenation  
3.   
4. str1 = "Hello"  
5. str2 = "JavaTpoint"  
6.   
7. # % Operator is used here to combine the string  
8. print("% s % s" % (str1, str2))  

Output:

Hello JavaTpoint

Explanation -

In the above code, the %s represents the string data-type. We passed both variables's
value to the %s that combined the strings and returned the "Hello JavaTpoint".

Using format() function


Python provides the str.format() function, which allows use of multiple substitutions
and value formatting. It accepts the positional arguments and concatenates the string
through positional formatting. Let's understand the following example.

Example -

1. # Python program to show   
2. # string concatenation   
3.   
4. str1 = "Hello"  
5. str2 = "JavaTpoint"  
6.   
7. # format function is used here to   
8. # concatenate the string   
9. print("{} {}".format(str1, str2))   
10.   
11. # store the result in another variable   
12. str3 = "{} {}".format(str1, str2)   
13.   
14. print(str3)   

Output:

Hello JavaTpoint
Hello JavaTpoint
Explanation:

In the above code, the format() function combines both strings and stores into the str3
variable. The curly braces {} are used as the position of the strings.

3. Working with Tuples and Set

You might also like