Phyton Progas Proz
Phyton Progas Proz
Phyton Progas Proz
print('Hello, world!')
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
a = 1
b = 5
c = 6
Enter a: 1
Enter b: 5
Enter c: 6
Source Code: Using a temporary variable
# Python program to swap two variables
x = 5
y = 10
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)
Run Code
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
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
A number is even if it is perfectly divisible by 2. When the number is divided by 2, we
use the remainder operator % to compute the remainder. If the remainder is not zero, the
number is odd.
Source Code
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
Enter a number: 43
43 is Odd
Output 2
Enter a number: 18
18 is Even
In this program, we ask the user for the input and check if the number is odd or even.
Please note that { } is a replacement field for num.
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,
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
You can change the value of year in the source code and run it again to test this
program.
# 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
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
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# 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
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 to num - 1. If we find a
factor in that range, the number is not prime, so we set flag to True and break out of
the loop.
Outside the loop, we check if flag is True or False.
If it is True, num is not a prime number.
If it is False, num is a prime number.
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):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Run Code
Output
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
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
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding
two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source Code
# Program to display the Fibonacci sequence up to n-th term
Here, we store the number of terms in nterms. We initialize the first term to 0 and the
second term to 1.
If the number of terms is more than 2, we use a while loop to find the next term in the
sequence by adding the preceding two terms. We then interchange the variables
(update it) and continue on with the process.
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
Output 2
Note: To test for different number of terms, change the value of terms variable.
In the program below, we have used anonymous (lambda) function inside
the filter() built-in function to find all the numbers divisible by 13 in the list.
Source Code
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
Source Code
# Python program to convert decimal into other number systems
dec = 344
Note: To test the program for other decimal numbers, change the value of dec in the
program.
In this program, we have used built-in functions bin(), oct() and hex() to convert the
given decimal number into respective number systems.
These functions take an integer (in decimal) and return a string.
The highest common factor (H.C.F) or greatest common divisor (G.C.D) of two numbers
is the largest positive integer that perfectly divides the two given numbers. For example,
the H.C.F of 12 and 14 is 2.
Source Code: Using Loops
# Python program to find H.C.F of two numbers
# define a function
def compute_hcf(x, y):
num1 = 54
num2 = 24
print("The H.C.F. is", compute_hcf(num1, num2))
Run Code
Output
The H.C.F. is 6
Here, two integers stored in variables num1 and num2 are passed to
the compute_hcf() function. The function computes the H.C.F. these two numbers and
returns it.
In the function, we first determine the smaller of the two numbers since the H.C.F can
only be less than or equal to the smallest number. We then use a for loop to go from 1
to that number.
In each iteration, we check if our number perfectly divides both the input numbers. If so,
we store the number as H.C.F. At the completion of the loop, we end up with the largest
number that perfectly divides both the numbers.
The least common multiple (L.C.M.) of two numbers is the smallest positive integer that
is perfectly divisible by the two given numbers.
For example, the L.C.M. of 12 and 14 is 84.
Program to Compute LCM
# Python Program to find the L.C.M. of two input number
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 54
num2 = 24
Note: To test this program, change the values of num1 and num2.
This program stores two number in num1 and num2 respectively. These numbers are
passed to the compute_lcm() function. The function returns the L.C.M of two numbers.
In the function, we first determine the greater of the two numbers since the L.C.M. can
only be greater than or equal to the largest number. We then use an infinite while loop
to go from that number and beyond.
In each iteration, we check if both the numbers perfectly divide our number. If so, we
store the number as L.C.M. and break from the loop. Otherwise, the number is
incremented by 1 and the loop continues.
Example: Simple Calculator by Using Functions
# This function adds two numbers
def add(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): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
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
In this program, we ask the user to choose an operation. Options 1, 2, 3, and 4 are
valid. If any other input is given, Invalid Input is displayed and the loop continues
until a valid option is selected.
Two numbers are taken and an if...elif...else branching is used to execute a
particular section. User-defined
functions add(), subtract(), multiply() and divide() evaluate respective
operations and display the output.
In the program below, we import the calendar module. The built-in
function month() inside the module takes in the year and the month and displays the
calendar for that month of the year.
Source Code
# Program to display calendar of the given month and year
yy = 2014 # year
mm = 11 # month
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
You can change the value of variables yy and mm and run it to test this program for
other dates.
Python Program to Display Fibonacci Sequence Using Recursion
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding
two terms.This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source Code
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Run Code
Output
Note: To test the program for another number, change the value of num.
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
Note: To find the factorial of another number, change the value of num.
Here, the number is stored in num. The number is passed to
the recur_factorial() function to compute the factorial of the number.
# 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]]
for r in result:
print(r)
Run Code
Output
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
In this program we have used nested for loops to iterate through each row and each
column. At each point, we add the corresponding elements in the two matrices and
store it in the result.
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for r in result:
print(r)
Run Code
Output
[12, 4, 3]
[7, 5, 8]
In this program, we have used nested for loops to iterate through each row and each
column. At each point we place the X[i][j] element into result[j][i].
# 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]]
for r in result:
print(r)
Run Code
Output
my_str = 'aIbohPhoBiA'
Note: To test the program, change the value of my_str in the program.
In this program, we have taken a string stored in my_str.
Using the method casefold() we make it suitable for caseless comparisons. Basically,
this method returns a lowercased version of the string.
We reverse the string using the built-in function reversed(). Since this function returns a
reversed object, we use the list() function to convert them into a list before comparing.
Python Program to Remove Punctuations From a String
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
In this program, we first define a string of punctuations. Then, we iterate over the
provided string using a for loop.
In each iteration, we check if the character is a punctuation mark or not using the
membership test. We have an empty string to which we add (concatenate) the character
if it is not punctuation. Finally, we display the cleaned up string.
# Program to sort alphabetically the words form a string provided by
the user
In this program, we store the string to be sorted in my_str. Using the split() method the
string is converted into a list of words. The split() method splits the string at
whitespaces.
The list of words is then sorted using the sort() method, and all the words are displayed.
JPEG (pronounced "jay-peg") stands for Joint Photographic Experts Group. It is one of
the most widely used compression techniques for image compression.
Most of the file formats have headers (initial few bytes) which contain useful information
about the file.
For example, jpeg headers contain information like height, width, number of color
(grayscale or RGB) etc. In this program, we find the resolution of a jpeg image reading
these headers, without using any external library.
Source Code of Find Resolution of JPEG Image
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file
passed into it"""
# calculate height
height = (a[0] << 8) + a[1]
# calculate width
width = (a[0] << 8) + a[1]
jpeg_res("img1.jpg")
Output
In this program, we opened the image in binary mode. Non-text files must be open in
this mode. The height of the image is at 164th position followed by width of the image.
Both are 2 bytes long.
Python Program to Print Output Without a Newline
Using end keyword
# print each statement on a new line
print("Python")
print("is easy to learn.")
# new line
print()
Python
is easy to learn.
Using the end keyword, you can append a string at the end of the print text. In the
above example, we have passed a space with end, which adds a space at the end of
the line and concatenates the content of the next print statement.
Python Program to Delete an Element From a Dictionary
Example 1: Using del keyword
my_dict = {31: 'a', 21: 'b', 14: 'c'}
del my_dict[31]
print(my_dict)
Run Code
Output
In the code above, the key:value pair with key as 31 is deleted using del keyword. del
keyword gives a KeyError if the key is not present in the dictionary.
Example 2: Using pop()
my_dict = {31: 'a', 21: 'b', 14: 'c'}
print(my_dict.pop(31))
print(my_dict)
Run Code
Output
a
{21: 'b', 14: 'c'}
Pass the key 31 as an argument to the pop() method. It deletes the key:value pair with
key as 31 as shown in the output.
pop() also returns the value of the key passed.
Python Program to Trim Whitespace From a String
Example 1: Using strip()
my_string = " Python "
print(my_string.strip())
Run Code
Output
Python
strip() removes the leading and trailing characters including the whitespaces from a
string.
However, if you have characters in the string like '\n' and you want to remove only the
whitespaces, you need to specify it explicitly on the strip() method as shown in the
following code.
my_string = " \nPython "
print(my_string.strip(" "))
Run Code
Output
Python
result = 1
while exponent != 0:
result *= base
exponent-=1
print(list(set(list_1)))
Run Code
Output
[1, 2, 4, 6]
In the above example, we first convert the list into a set, then we again convert it into a
list. Set cannot have a duplicate item in it, so set() keeps only an instance of the item.
Example 2: Remove the items that are duplicated in two lists
list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]
print(list(set(list_1) ^ set(list_2)))
Run Code
Output
[4, 6, 7, 8]
In the above example, the items that are present in both lists are removed.
Firstly, both lists are converted to two sets to remove the duplicate items from each list.
Then, ^ gets the symmetric difference of two lists (excludes the overlapping elements of
two sets).
Countdown time in Python
import time
def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)