# Python3 program to add two numbers
num1 = 15
num2 = 12
# Adding two nos
sum = num1 + num2
# printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum))
Output:
Sum of 15 and 12 is 27
Example 2: Adding two number provided by user input
number1 = input("First number: ")
number2 = input("\nSecond number: ")
# Adding two numbers
# User might also enter float numbers
sum = float(number1) + float(number2)
# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1,number2,sum))
Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Python Program for factorial of a number
Factorial of a non-negative integer, is multiplication of all integers
smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1
which is 720.
Recursive Solution:
Factorial can be calculated using following recursive formula.
n! = n * (n-1)!
n! = 1 if n = 0 or n = 1
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num = 5;
print("Factorial of", num, "is",factorial(num))
Iterative Solution:
Factorial can also be calculated iteratively as
recursion can be costly for large numbers. Here we have shown
the iterative approach using both for and while loop.
Using For loop
def factorial(n):
res = 1
for i in range(2, n+1):
res *= i
return res
num = 5;
print("Factorial of", num, "is",factorial(num))
# This code is contributed by Smitha Dinesh Semwal
Output :
Factorial of 5 is 120
Using While loop
# Function to find factorial of given number
def factorial(n):
if(n == 0):
return 1
i = n
fact = 1
while(n / i != n):
fact = fact * i
i -= 1
return fact
# Driver Code
num = 5;
print("Factorial of", num, "is",factorial(num))
Output :
Factorial of 5 is 120
Time complexity of the above iterative solutions is O(n).
One line Solution (Using Ternary operator):
def factorial(n):
# single line to find factorial
return 1 if (n == 1 or n == 0) else n * factorial(n - 1)
# Driver Code
num = 5
print ("Factorial of", num, "is", factorial(num))
Output:
Factorial of 5 is 120
The above solutions cause overflow for small numbers. Please refer factorial of large
number for a solution that works for large numbers.