- A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
- A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
Author: Saim Khalid
-
global and local scope?
-
Find the Factorial of a Number
Python Program to Find the Factorial of a Number
To understand this example, you should have the knowledge of the following Python programming topics:
The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is
1*2*3*4*5*6 = 720
. Factorial is not defined for negative numbers, and the factorial of zero is one,0! = 1
.Factorial of a Number using Loop
# 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):
print("The factorial of",num,"is",factorial)factorial = factorial*i
Output
The factorial of 7 is 5040
Note: To test the program for a different number, change the value of
num
.Here, the number whose factorial is to be found is stored in
num
, and we check if the number is negative, zero or positive usingif...elif...else
statement. If the number is positive, we usefor
loop and range() function to calculate the factorial.iteration factorial*i (returned value) i = 1 1 * 1 = 1 i = 2 1 * 2 = 2 i = 3 2 * 3 = 6 i = 4 6 * 4 = 24 i = 5 24 * 5 = 120 i = 6 120 * 6 = 720 i = 7 720 * 7 = 5040
Factorial of a Number using Recursion
# Python program to find the factorial of a number provided by the user # using recursion def factorial(x):
"""This is a recursive function to find the factorial of an integer"""
# change the value for a different result num = 7 # to take input from the user # num = int(input("Enter a number: ")) # call the factorial function result = factorial(num) print("The factorial of", num, "is", result)if x == 1 or x == 0: return 1 else: # recursive call to the function return (x * factorial(x-1))
In the above example,
factorial()
is a recursive function that calls itself. Here, the function will recursively call itself by decreasing the value of the x.
Also Read:
Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?
Challenge:
Write a function to calculate the factorial of a number.
- The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
- For example, for input
5
, the output should be120
- def factorial(n):
-
Check Prime Number
Python Program to Check Prime Number
To understand this example, you should have the knowledge of the following Python programming topics:
A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since,
2 x 3 = 6
.
Example 1: Using a flag variable
# 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 == 0 or num == 1:
elif num > 1:print(num, "is not a prime number")
# 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")</code></pre>
Output
29 is a prime number
In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.
We check if num is exactly divisible by any number from
2
tonum - 1
. If we find a factor in that range, the number is not prime, so we set flag toTrue
and break out of the loop.Outside the loop, we check if
flag
isTrue
orFalse
.- If it is
True
,num
is not a prime number. - If it is
False
,num
is a prime number.
Note: We can improve our program by decreasing the range of numbers where we look for factors.
In the above program, our search range is from 2 to
num - 1
.We could have used the range,
range(2,num//2)
orrange(2,math.floor(math.sqrt(num)+1))
. The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. Otherwise, the number is prime.You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.
In Python, we can also use the
for...else
statement to do this task without using an additionalflag
variable. - If it is
-
Check Leap Year
Python Program to Check Leap Year
To understand this example, you should have the knowledge of the following Python programming topics:
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):
# 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 a leap year".format(year))
print("{0} is not a leap year".format(year))</code></pre>
Output
2000 is a leap year
You can change the value of year in the source code and run it again to test this program.
-
Convert Celsius To Fahrenheit
Python Program to Convert Celsius To Fahrenheit
To understand this example, you should have the knowledge of the following Python programming topics:
In the program below, we take a temperature in degree Celsius and convert it into degree Fahrenheit. They are related by the formula:
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
We encourage you to create a Python program to convert Fahrenheit to Celsius on your own using the following formula
celsius = (fahrenheit - 32) / 1.8
-
Convert Kilometers to Miles
Python Program to Convert Kilometers to Miles
To understand this example, you should have the knowledge of the following Python programming topics:
Example: Kilometers to Miles
# 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
Here, the user is asked to enter kilometers. This value is stored in the kilometers variable.
Since 1 kilometer is equal to 0.621371 miles, we can get the equivalent miles by multiplying kilometers with this factor.
Your turn: Modify the above program to convert miles to kilometers using the following formula and run it.
kilometers = miles / conv_fac
-
Generate a Random Number
Python Program to Generate a Random Number
To understand this example, you should have the knowledge of the following Python programming topics:
To generate random number in Python,
randint()
function is used. This function is defined in random module.
Source Code
# Program to generate a random number between 0 and 9 # importing the random module import random print(random.randint(0,9))
Output
5
Note that we may get different output because this program generates random number in range 0 and 9. The syntax of this function is:
random.randint(a,b)
This returns a number N in the inclusive range
[a,b]
, meaninga <= N <= b
, where the endpoints are included in the range. -
Swap Two Variables
Python Program to Swap Two Variables
To understand this example, you should have the knowledge of the following Python programming topics:
Source Code: Using a temporary variable
Code Visualization: Want to see exactly how variable swapping works? Step through each line with our new code visualizer. Try it yourself!
# 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
In this program, we use the temp variable to hold the value of x temporarily. We then put the value of y in x and later temp in y. In this way, the values get exchanged.
Source Code: Without Using Temporary Variable
In Python, there is a simple construct to swap variables. The following code does the same as above but without the use of any temporary variable.
x = 5 y = 10 x, y = y, x print("x =", x) print("y =", y)
If the variables are both numbers, we can use arithmetic operations to do the same. It might not look intuitive at first sight. But if you think about it, it is pretty easy to figure it out. Here are a few examples
Addition and Subtraction
x = x + y y = x - y x = x - y
Multiplication and Division
x = x * y y = x / y x = x / y
XOR swap
This algorithm works for integers only
x = x ^ y y = x ^ y x = x ^ y
Also Read:
-
Solve Quadratic Equation
Python Program to Solve Quadratic Equation
To understand this example, you should have the knowledge of the following Python programming topics:
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
The solutions of this quadratic equation is given by:
(-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 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(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)
We have imported the
cmath
module to perform complex square root. First, we calculate the discriminant and then find the two solutions of the quadratic equation.You can change the value of a, b and c in the above program and test this program.
Also Read:
Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?
Challenge:
Write a function to solve a quadratic equation.
- Define a function that takes three integers as input representing the coefficients of a quadratic equation.
- Return the roots of the quadratic equation.
- Hint: The quadratic formula is
x = [-b ± sqrt(b^2 - 4ac)] / (2a)
. - The term inside the square root,
b^2 - 4ac
, is called the discriminant.
- If it’s positive, there are two real roots.
- If it’s zero, there’s one real root.
- If it’s negative, there are two complex roots.
- While returning the list, make sure the solution of [-b + sqrt(b^2 – 4ac)] / (2a) appears as the first solution.
- import math
2. def solve_quadratic(a, b, c):
-
Calculate the Area of a Triangle
Python Program to Calculate the Area of a Triangle
To understand this example, you should have the knowledge of the following Python programming topics:
If a, b and c are three sides of a triangle. Then,
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
In this program, area of the triangle is calculated when three sides are given using Heron’s formula.
If you need to calculate area of a triangle depending upon the input from the user, input() function can be used.
Also Read:
Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?
Challenge:
Write a function to find the area of a right angled triangle rounded off to two decimal places.
- For example, for inputs
3
and4
, the output should be6.0
. - Reason: The area of a right-angled triangle is given by
(1/2)*base*height
. So, for base = 3 and height = 4, it’s(1/2)*3*4 = 6.0
.
1 def triangle_area(base, height):
2
- For example, for inputs