The best way to learn Python is by practicing examples. The page contains examples on basic concepts of Python. You are advised to take the references from these examples and try them on your own.
All the programs on this page are tested and should work on all platforms.
Python Basic Programs with Examples for Beginners
Write a Python program to display the current date and time.
1 2 3 4 5 6 |
import datetime now = datetime.datetime.now() print ("Current date and time : ") print (now.strftime("%Y-%m-%d %H:%M:%S")) |
Write a Python program which accepts the radius of a circle from the user and compute the area.
1 2 3 4 5 |
from math import pi radius = float(input ("Input the radius of the circle : ")) print ("The area of the circle with radius " + str(radius) + " is: " + str(pi * radius**2)) |
Write a Python program which accepts the user’s first and last name and print them in reverse order.
1 2 3 4 5 |
firstname = input("Input your First Name : ") lastname = input("Input your Last Name : ") print ("Hello " + lastname + " " + firstname) |
Write a Python program to accept a filename from the user and print the extension of that file.
1 2 3 4 5 |
filename = input("Input the Filename: ") f_extns = filename.split(".") print ("The extension of the file is : " + repr(f_extns[-1])) |
Write a Python program to display the examination schedule.
1 2 3 4 |
exam_start_date = (12,10,2018) print( "The examination will start from : %i / %i / %i"%exam_start_date) |
Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
1 2 3 4 5 6 7 |
a = int(input("Input an integer : ")) num1 = int( "%s" % a ) num2 = int( "%s%s" % (a,a) ) num3 = int( "%s%s%s" % (a,a,a) ) print (num1+num2+num3) |
Write a Python program to print the calendar of a given month and year.
1 2 3 4 5 6 |
import calendar year = int(input("Input the year : ")) month = int(input("Input the month : ")) print(calendar.month(year, month)) |
Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.
1 2 3 4 5 6 7 8 9 10 11 12 |
def sum_thrice(x, y, z): sum = x + y + z if x == y == z: sum = sum * 3 return sum print(sum_thrice(1, 2, 3)) print(sum_thrice(3, 3, 3)) |
Write a Python program to find whether a given number is even or odd.
1 2 3 4 5 6 7 8 |
num = int(input("Enter a number: ")) mod = num % 2 if mod > 0: print("This is an odd number.") else: print("This is an even number.") |
Write a Python program to check whether a file exists.
1 2 3 4 5 |
import os.path open('tech.txt', 'w') print(os.path.isfile('tech.txt')) |
Write a Python program to solve (x + y) * (x + y).
1 2 3 4 5 |
x, y = 5, 4 result = x * x + 2 * x * y + y * y print("({} + {}) ^ 2) = {}".format(x, y, result)) |
Write a Python program to display your details like name, age, address.
1 2 3 4 5 6 7 8 |
def personal_details(): name, age = "Rohit", 25 address = "Mumbai, Maharashtra, India" print("Name: {}\nAge: {}\nAddress: {}".format(name, age, address)) personal_details() |
Write a Python program to add two objects if both objects are an integer type.
1 2 3 4 5 6 7 8 |
def add_numbers(x, y): if not (isinstance(x, int) and isinstance(y, int)): raise TypeError("Inputs must be integers") return x + y print(add_numbers(30, 20)) |
Write a Python program to compute the greatest common divisor (GCD).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def gcd(a, b): gcd = 1 if a % b == 0: return y for k in range(int(b / 2), 0, -1): if a % k == 0 and b % k == 0: gcd = k break return gcd print(gcd(20, 60)) print(gcd(10, 40)) |
Write a Python program to get the least common multiple (LCM).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def lcm(a, b): if a > b: z = a else: z = b while(True): if((z % a == 0) and (z % b == 0)): lcm = z break z += 1 return lcm print(lcm(10, 20)) print(lcm(15, 17)) |
Write a Python program that will accept the base and height of a triangle and compute the area.
1 2 3 4 5 6 7 8 |
base = int(input("Input the base : ")) height = int(input("Input the height : ")) area = base*height/2 print("area = ", area) |
Write a Python program to concatenate all elements in a list into a string and return it.
1 2 3 4 5 6 7 8 9 |
def concatenate_list_data(list): result= '' for element in list: result += str(element) return result print(concatenate_list_data([2, 10, 22, 21])) |
Write a Python program to test whether a passed letter is a vowel or not.
1 2 3 4 5 6 7 |
def is_vowel(char): all_vowels = 'aeiou' return char in all_vowels print(is_vowel('e')) print(is_vowel('z')) |
Write a Python to find local IP addresses using Pythons stdlib.
1 2 3 4 5 6 7 |
import socket print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]) |
Write a python program to sum of the first n positive integers.
1 2 3 4 5 |
num = int(input("Input a number: ")) sum_num = (num * (num + 1)) / 2 print(sum_num) |
Write a Python program to convert height (in feet and inches) to centimeters.
1 2 3 4 5 6 7 8 9 10 |
print("Input your height: ") h_ft = int(input("Feet: ")) h_inch = int(input("Inches: ")) h_inch += h_ft * 12 h_cm = round(h_inch * 2.54, 1) print("Your height is : %d cm." % h_cm) |
Write a Python program to convert the distance (in feet) to inches, yards, and miles.
1 2 3 4 5 6 7 8 9 10 |
d_ft = int(input("Input distance in feet: ")) d_inches = d_ft * 12 d_yards = d_ft / 3.0 d_miles = d_ft / 5280.0 print("The distance in inches is %i inches." % d_inches) print("The distance in yards is %.2f yards." % d_yards) print("The distance in miles is %.2f miles." % d_miles) |
Write a Python program Convert all units of time into seconds.
1 2 3 4 5 6 7 8 9 10 |
days = int(input("Input days: ")) * 3600 * 24 hours = int(input("Input hours: ")) * 3600 minutes = int(input("Input minutes: ")) * 60 seconds = int(input("Input seconds: ")) Totaltime = days + hours + minutes + seconds print("The amounts of seconds", Totaltime) |
Write a Python program to Calculate body mass index.
1 2 3 4 5 |
height = float(input("Input your height in meters: ")) weight = float(input("Input your weight in kilogram: ")) print("Your body mass index is: ", round(weight / (height * height), 2)) |
Write a Python program to Calculate the sum of the digits in an integer.
1 2 3 4 5 6 7 8 |
num = int(input("Input a four digit numbers: ")) a = num //1000 a1 = (num - a*1000)//100 a2 = (num - a*1000 - a1*100)//10 a3 = num - a*1000 - a1*100 - a2*10 print("The sum of digits in the number is", a+a1+a2+a3) |
Write a Python program to Concatenate N strings.
1 2 3 4 5 6 7 |
list_of_numbers = ['one', 'two', 'three'] numbers = '-'.join(list_of_numbers) print() print("All Numbers: "+numbers) print() |
Write a Python program to Get the ASCII value of a character.
1 2 3 4 5 6 7 8 |
print() print("c>>",ord('c')) print("A>>",ord('A')) print("5>>",ord('5')) print("#>>",ord('#')) print() |
Write a Python program to Swap two variables.
1 2 3 4 5 6 7 8 |
a = 50 b = 30 print("\nBefore swap a = %d and b = %d" %(a, b)) a, b = b, a print("\nAfter swaping a = %d and b = %d" %(a, b)) print() |
Write a Python program to get the name of the host on which the routine is running.
1 2 3 4 5 6 7 |
import socket host_name = socket.gethostname() print() print("Host name:", host_name) print() |
Write a Python program to find postive or negative number
1 2 3 4 5 6 7 8 9 |
num = float(input("Input a number: ")) if num > 0: print("It is positive number") elif num == 0: print("It is Zero") else: print("It is a negative number") |
Write a Python program to remove the first item from a specified list.
1 2 3 4 5 6 7 |
Car = ["AUDI", "FERRARI", "HONDA", "Bentley", "Bugatti"] print("\nOriginal Car: ",Car) del Car[0] print("After removing the first Car: ",Car) print() |
Write a Python program to input a number, if it is not a number generate an error message.
1 2 3 4 5 6 7 8 9 |
while True: try: a = int(input("Input a number: ")) break except ValueError: print("\nThis is not a number. Try again...") print() |
Write a Python program to filter the positive numbers from a list.
1 2 3 4 5 6 |
nums = [-10, 10, 15, -56] print("Original numbers in the list: ",nums) Pos_nums = list(filter(lambda x: x >0, nums)) print("Positive numbers in the list: ",Pos_nums) |
Write a Python program to sum of all counts in a collections.
1 2 3 4 5 |
import collections num = [1,2,3,4,5,6] print(sum(collections.Counter(num).values())) |
Write a Python program to convert true to 1 and false to 0.
1 2 3 4 5 6 7 8 |
x = 'true' x = int(x == 'true') print(x) x = 'xyz' x = int(x == 'true') print(x) |
Write a Python program to remove and print every third number from a list of numbers until the list becomes empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def remove_nums(int_list): #list starts with 0 index position = 3 - 1 idx = 0 len_list = (len(int_list)) while len_list>0: idx = (position+idx)%len_list print(int_list.pop(idx)) len_list -= 1 nums = [10,20,30,40,50,60] remove_nums(nums) |
Write a Python program to create the combinations of 3 digit combo.
1 2 3 4 5 6 7 |
numbers = [] for num in range(1000): num=str(num).zfill(3) print(num) numbers.append(num) |
Write a Python program to add two positive integers without using the ‘+’ operator.
1 2 3 4 5 6 7 8 9 10 11 |
def add_without_plus_operator(x, y): while y != 0: data = x & y x = x ^ y y = data << 1 return x print(add_without_plus_operator(2, 10)) print(add_without_plus_operator(-20, 10)) print(add_without_plus_operator(-10, -20)) |
Write a Python program to find the median among three given numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
a = input("Input the first number: ") y = input("Input the second number: ") z = input("Input the third number: ") print("Median of the above 3 numbers is: ") if y < a and a < z: print(a) elif z < a and a < y: print(a) elif z < y and y < a: print(y) elif a < y and y < z: print(y) elif y < z and z < a: print(z) elif a < z and z < y: print(z) |
Write a Python program to find the number of notes (Sample of notes: 10, 20, 50, 100, 200 and 500 ).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def no_notes(a): Q = [500, 200, 100, 50, 20, 10] x = 0 for i in range(6): q = Q[i] x += int(a / q) a = int(a % q) if a > 0: x = -1 return x print(no_notes(500)) print(no_notes(560)) |