Phyton Progas Proz

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

# This program prints Hello, world!

print('Hello, world!')

# This program adds two numbers


num1 = 1.5
num2 = 6.3

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
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))

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

The area of the triangle is 14.70


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)

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


Run Code
Output

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

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

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
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.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Run Code
Output 1

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,

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):
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

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

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)


Run Code
Output

The largest number is 14.0

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 == 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

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
Run Code
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 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

 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
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

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Run Code
Output
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

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.

Source Code: Check Armstrong number (for 3 digits)


# Python program to check if the number is an Armstrong number or not

# take input from the user


num = int(input("Enter a 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

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Run Code
Output 1

Enter a number: 663


663 is not an Armstrong number

Output 2

Enter a number: 407


407 is an Armstrong number

In the program below, we have used an anonymous (lambda) function inside


the map() built-in function to find the powers of 2.
Source Code
# Display the powers of 2 using anonymous function
terms = 10

# Uncomment code below to take input from the user


# terms = int(input("How many terms? "))

# use anonymous function


result = list(map(lambda x: 2 ** x, range(terms)))

print("The total terms are:",terms)


for i in range(terms):
print("2 raised to power",i,"is",result[i])
Run Code
Output

The total terms are: 10


2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512

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,]

# use anonymous function to filter


result = list(filter(lambda x: (x % 13 == 0), my_list))

# display the result


print("Numbers divisible by 13 are",result)
Run Code
Output

Numbers divisible by 13 are [65, 39, 221]


The decimal system is the most widely used number system. However, computers only
understand binary. Binary, octal and hexadecimal number systems are closely related,
and we may require to convert decimal into these systems.
The decimal system is base 10 (ten symbols, 0-9, are used to represent a number) and
similarly, binary is base 2, octal is base 8 and hexadecimal is base 16.
A number with the prefix 0b is considered binary, 0o is considered octal and 0x as
hexadecimal. For example:

60 = 0b11100 = 0o74 = 0x3c

Source Code
# Python program to convert decimal into other number systems
dec = 344

print("The decimal value of", dec, "is:")


print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
Run Code
Output

The decimal value of 344 is:


0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

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):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

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

def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = 54
num2 = 24

print("The L.C.M. is", compute_lcm(num1, num2))


Run Code
Output

The L.C.M. is 216

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

# 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'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

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

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

# importing calendar module


import calendar

yy = 2014 # year
mm = 11 # month

# To take month and year input from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))
Run Code
Output

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

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Run Code
Output

Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Note: To test the program, change the value of nterms.


In this program, we store the number of terms to be displayed in nterms.
A recursive function recur_fibo() is used to calculate the nth term of the sequence.
We use a for loop to iterate and calculate each term recursively.
# Python program to find the sum of natural using recursive function
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)

# change this value for a different result


num = 16

if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Run Code
Output

The sum is 136

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

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

The factorial of 7 is 5040

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]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

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]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

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]]

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)
Run Code
Output

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]
# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Run Code
Output

The string is a palindrome.

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 = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user


# my_str = input("Enter a string: ")

# remove punctuation from the string


no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

# display the unpunctuated string


print(no_punct)
Run Code
Output

Hello he said and went

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

my_str = "Hello this Is an Example With cased letters"

# To take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in my_str.split()]

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)
Run Code
Output

The sorted words are:


an
cased
example
hello
is
letters
this
with

Note: To test the program, change the value of my_str.

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"""

# open image for reading in binary mode


with open(filename,'rb') as img_file:

# height of image (in 2 bytes) is at 164th position


img_file.seek(163)

# read the 2 bytes


a = img_file.read(2)

# calculate height
height = (a[0] << 8) + a[1]

# next 2 bytes is width


a = img_file.read(2)

# calculate width
width = (a[0] << 8) + a[1]

print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg")

Output

The resolution of the image is 280 x 280

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()

# print both the statements on a single line


print("Python", end=" ")
print("is easy to learn.")
Run Code
Output

Python
is easy to learn.

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

{21: 'b', 14: 'c'}

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

To learn more, visit Python String strip().


Example 1: Calculate power of a number using a while loop
base = 3
exponent = 4

result = 1

while exponent != 0:
result *= base
exponent-=1

print("Answer = " + str(result))


Python Program to Remove Duplicate Element From a List
Example 1: Using set()
list_1 = [1, 2, 1, 4, 6]

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)

You might also like