Python Program
Python Program
year = 2000
# 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
lower = 900
upper = 1000
Output
factorial = 1
Output
num = 12
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
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): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
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
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:
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:
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
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
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
Case - (2):
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:
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
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.
60.6M
1.1K
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.)
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:
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:
Explanation-
Play Video
x
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:
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.
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:
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.
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.
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".
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.