1000+ Python programs

Best Software training institutes in Hyderabad - Ojango.org

1000+ Python programs

March 29, 2019 Interviews Python 0

1.Write a python program to print name without parameter

Program:

def wish():

    print(“Hi sush..Good Morning”)

wish()

wish()

wish()

wish()

wish()

Output:

Hi sush..Good Morning

Hi sush..Good Morning

Hi sush..Good Morning

Hi sush..Good Morning

Hi sush..Good Morning

2.Write a python program to print name with parameter

Program:

def wish(name):

    print(“Hi”,name,”Good Morning”)

wish(“sush”)

wish(“venky”)

wish(“naidu”)

wish(“vinay”)

wish(“sush”)

output:

Hi sush Good Morning

Hi venky Good Morning

Hi naidu Good Morning

Hi vinay Good Morning

Hi sush Good Morning

3.Write a python program to find square of a number

Program:

def sqr(num):

    print(“square of given”,num,”is:”,num*num)

sqr(4)

sqr(6)

Output:

square of given 4 is: 16

square of given 6 is: 36

4.Write a python program to return sum using functions

Program:

def add(x,y):

    return x+y

sum=add(10,20)

print(“sum of given num is:”,sum)

Output:

sum of given num is: 30

4.Write a python program to print given number is even or odd.

Program:

def num(a):

    if a%2==0:

        print(“given nm is even”)

    else:

        print(“give num is odd”)

num(10)

num(13)

num(26)

num(33)

Output:

given nm is even

give num is odd

given nm is even

give num is odd

5.Write a function to find factorial of given number

Program:

num=int(input(“enter num to find factorial”)

def fact(num):

               result=1

               while(num>=1):

                              result=result*num

                              num=num-1

               return resut

print(“factorial of given number:”,num,”:”,fact(num))

Output:

Enter number to find factorial:3

Fcatorial of a given number :3 is:6

6.Write a function to find given number is  divisible by 3 or not.

Program:

def division(num):

               if num%3==0

                              print(“given num is divisible”)

               else:

                              print(“given num is not divisible”)

divsion (9)

division(10)

Output:

given num is divisible

given num is not divisible

7.Write a program to  retrun multiple values from functions

program:

def sum_sub(a,b):

      sub=a-b

      sum1=a+b

      return sum1,sub

x,y=sum_sub(100,50)

print(“sum is:”,x)

print(“sub is:”,y)

Output:

Sum is:150

Sub is:150

8.Write a program to print addition a d subtraction based on positional arguments

Program:

def sub(a,b):

               print(a-b)

sub(100,300)

sub(300,100)

sub(20,13)

Output:

-200

200

7

9.Write a program to print name and message based on keyword argument

Program:

def wish(name,msg):

print(“Hello”,name,msg)

wish(name=”venky”,msg=”good morning”)

wish(name=”sush”,msg=”how are you?”)

wish=(msg=”what are you doing”,name=”naidu”)

wish=(“venky”,”how old are you?”)

wish=(“venky”,msg=”hi”)

wish(name=”nani”,”where are you”)

wish(“where are you”,name=”nani”)

Output:

Hello venky good morning

Hello sush how are you?

Hello naidu what are you doing

venky,how old are you?

Hello venky hi

Nani,Whre are you

10.Program to print default arguments

Program:

def wish(name=”venky”)

               print(“hello”,name,”good morning”)

wish(“nani”)

wish()

Output:

Hello nani good morning

Hello venky good morning

11.Print variable length of arguments

Program:

def sum(*n):

               total=0

               for x in n:

                              total=total + x

               print(“totsl:”,total)

sum(5)

sum(10)

sum(10,20,30)

sum()

Output:

total 5

t0tal 10

total 60

total 0

12.Program to declare a global variable

a=10

b=20

def fun1():

               print(a)

               print(b)

def fun(2):

               print(a)

               print(b)

fun1()

fun2()

Output:

10

20

10

20

13.Program to print local variable

def fun1():

               global a=20

               print(a)

def fun2():

               print(a)

func()

func()

14.Program to find factorial of a number using recursion

n=int(input(“enter a value to find fact:”))

def fact(n):

               if n=0

               result=1

else:

               result=n*fact(n-1)

               retuurn result

print(“fact of”,n”,is:”,fact(n))

Output:

Enter a value to find fact:3

fact of 3 is:6

15.Write a Python program to sort (ascending and descending) a dictionary by value.

import operator

d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

print(‘Original dictionary : ‘,d)

sorted_d = sorted(d.items(), key=operator.itemgetter(0))

print(‘Dictionary in ascending order by value : ‘,sorted_d)

sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)

print(‘Dictionary in descending order by value : ‘,sorted_d)

Output:

Original dictionary :  {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}                                                        

Dictionary in ascending order by value :  [(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]                           

Dictionary in descending order by value :  [(4, 3), (3, 4), (2, 1), (1, 2), (0, 0)] 

16.Write a Python program to add a key to a dictionary.

d = {0:10, 1:20}

print(d)

d.update({2:30})

print(d)

Output:

{0: 10, 1: 20}                                                                                                

{0: 10, 1: 20, 2: 30}

17.Write a Python program to concatenate following dictionaries to create a new one.

dic1={1:10, 2:20}

dic2={3:30, 4:40}

dic3={5:50,6:60}

dic4 = {}

for d in (dic1, dic2, dic3): dic4.update(d)

print(dic4)

Output:

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

18.Write a Python program to create a new empty set.

x = set()

print(x)

#Create a non empty set

n = set([0, 1, 2, 3, 4])

print(n)

Output:

set()                                                                                                        

{0, 1, 2, 3, 4} 

19.Write a Python program to print a poem in step-by-step

Pogram:

print(“Twinkle, twinkle,little star, \n\tHow I wonder what you are! \n\t\tup above the word so high,\n\t\tlike a diamond in the sky”)

Output:

Twinkle, twinkle,little star,

               How I wonder what you are!

                              up above the word so high,

                              like a diamond in the sky

20.Write a Python program to get the Python version you are using.

Program:

import sys

print(“Python version”)

print (sys.version)

print(“Version info.”)

print (sys.version_info)

 Output:

Python version                                                                                               

3.5.2 (default, Sep 10 2016, 08:21:44)                                                                       

[GCC 5.4.0 20160609]                                                                                         

Version info.                                                                                                 

sys.version_info(major=3, minor=5, micro=2, releaselevel=’final’, serial=0)

21.Write a Python program to display the current date and time.

Program:

import datetime

now=datetime.datetime.now()

print(“current date and time:”)

print(now.strftime(“%Y-%m-%d %H:%M:%S”))

Output

current date and time:

2019-03-20 16:34:06

22. Write a Python program which accepts the radius of a circle from the user and compute the area.

from math import pi

r = float(input (“Input the radius of the circle : “))

print (“The area of the circle with radius ” + str(r) + ” is: ” + str(pi * r**2))

Output:

Input the radius of the circle : 1.1                                                                         

The area of the circle with radius 1.1 is: 3.8013271108436504

23. Write a Python program which accepts the user’s first and last name and print them in reverse order with a space between them

Program:

fname=(“Input your First name: “)

lname=(“Input your Last name: “)

print(“hello ” + lname + ” “

      + fname)

output:

Input your First Name : Dany                                      

Input your Last Name : Boon                                       

Hello  Boon Dany   

24.Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.

Program:

values=input(“input of some numbers separated with commmas:”)

list=values.split(“,”)

tuple=tuple(list)

print(“list:”,list)

print(“tuple:”,tuple)

output:

input of some numbers separated with commmas:1,2,3,4,5

list: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

tuple: (‘1’, ‘2’, ‘3’, ‘4’, ‘5’)

25.Write a Python program to accept a filename from the user and print the extension of that.

Program:

filename=input(“input the file name:”)

f_extns=filename.split(“.”)

print(“the extension of the file is:”+repr(f_extns[-1]))

output:

input the file name:abc.java

the extension of the file is:’java’

26.Write a Python program to display the first and last colors from the following list.

color_list=[“blue”,”yellow”,”green”,”white”]

print(“%s %s”%(color_list[0],color_list[-1]))

output:

blue white

27.Write a Python program to display the examination schedule.

Program:

exam_st_date=(21,10,2019)

print(“the examination will start from:%i/%i/%i”%exam_st_date)

Output:

print(“the examination will start from: %i/%i/%i”%exam_st_date)

28.Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.

Program:

a=int(input(“input an integer:”))

n1=int(“%s”%a)

n2=int(“%s%s”%(a,a))

n3=int(“%s%s%s”%(a,a,a))

n4=int(“%s%s%s%s”%(a,a,a,a))

n5=int(“%s%s%s%s%s”%(a,a,a,a,a))

print(n1+n2+n3+n4+n5)

Output:

input an integer:5

61725

29.Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s).

Program:

print(abs.__doc__)

Return the absolute value of the argument

30.Write a Python program to print the calendar of a given month and year

Program:

import calender

y=int(input(“input the year:”))

m=int(input(“input the month:”))

print(calender.month(y,m))

Output:

Input the year : 2017                                                                                        

Input the month : 04                                                                                         

     April 2017                                                                                               

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

31.Write a Python program to calculate number of days between two dates.

Program:from datetime import date

fdate=date(2019,3,21)

ldate=date(2019,3,30)

delta=ldate-fdate

print(delta.days)

Output:

9

32.Write a Python program to get the the volume of a sphere with radius 6.

Program:pi=3.14159265359

r=6

v=4.0/3.0*pi*r**3

print(“the volume of the sphere is:”,v)

Output:

the volume of the sphere is: 904.77868423392

33.Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.

Program:

def difference(n):

    if n <= 17:

        return 17-n

    else:

        return(n-17)*2

print(difference(30))

print(difference(12))

Output:

26

5

34.Write a Python program to test whether a number is within 100 of 1000 or 2000

Program:

def near_thousand(n):

    return ((abs(1000-n) <= 100) or (abs(2000-n) <=100))

print(near_thousand(1000))

print(near_thousand(900))

print(near_thousand(800))

print(near_thousand(2200))

Output:

True

True

False

False

35.Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.

Program:

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

print(sum_thrice(2,2,2))

print(sum_thrice(4,4,4))

Output:

6

28

18

36

18

36.Write a Python program to get a new string from a given string where “Is” has been added to the front. If the given string already begins with “Is” then return the string unchanged.

Program:

def new_string(str):

    if len(str)>=2 and str[:2]==”Is”:

        return str

    return “Is”+str

print(new_string(“Array”))

print(new_string(“IsEmpty”))

Output:

IsArray

IsEmpty

37.Write a Python program to get a string which is n (non-negative integer) copies of a given string.

Program:

def larger_string(str,n):

    result=””

    for i in range(n):

        result=result+str

    return result

print(larger_string(‘abc’,2))

print(larger_string(‘.py’,3))

Output:

abcabc

.py.py.py

38.Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.

Program:

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

 Output:

Enter a number: 5                                                                                            

This is an odd number.

39.Write a Python program to count the number 4 in a given list

def list_count_4(nums):

  count = 0 

  for num in nums:

    if num == 4:

      count = count + 1

  return count

print(list_count_4([1, 4, 6, 7, 4]))

print(list_count_4([1, 4, 6, 4, 7, 4]))

Output:

2                                                                                                             

3

40.Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.

Program:

def substring_copy(str, n):

  flen = 2

  if flen > len(str):

    flen = len(str)

  substr = str[:flen]

  result = “”

  for i in range(n):

    result = result + substr

  return result

print(substring_copy(‘abcdef’, 2))

print(substring_copy(‘p’, 3));

output:

abab                                                                                                         

ppp

41.Write a Python program to test whether a passed letter is a vowel or not.

def is_vowel(char):

    all_vowels = ‘aeiou’

    return char in all_vowels

print(is_vowel(‘c’))

print(is_vowel(‘e’))

Output:

False

True

42.Write a Python program to check whether a specified value is contained in a group of values.

Program:

def is_group_member(group_data, n):

    for value in group_data:

        if n == value:

            return True

    return False

print(is_group_member([1, 5, 8, 3], 3))

print(is_group_member([5, 8, 3], -1))

Output:

True

False

43.Write a Python program to create a histogram from a given list of integers

def histogram(items):

    for n in items:

        output=”

        times=n

        while(times>0):

            output += ‘*’

            times=times-1

        print(output)

histogram([2,3,6,5])

Output:

**

***

******

*****

44.Write a Python program to concatenate all elements in a list into a string and return it.

Program:

def concatenate_list_data(list):

               result=”

               for elemet in list:

                   result += str(element)

               return result

>>> print(concatenate_list_data([1,5,12,2]))

Output:

15122

45.. Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.

program:

numbers = [   

    386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,

    399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,

    815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,

    958,743, 527

    ]

for x in numbers:

    if x==237:

        print(x)

        break;

    elif x%2==0:

        print(x)

Output:

386

462

418

344

236

566

978

328

162

758

918

237

46.Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2

Program:

l1=set([“white”,”black”,”red”])

l2=set([“white”,”black”,”yellow”])

print(l1.difference(l2))

print(l2.difference(l1))

Output:

{‘red’}

{‘yellow’}

47.Write a Python program that will accept the base and height of a triangle and compute the area.

program:

b=int(input(“enter the base of a triangle:”))

h=int(input(“enter the height of a triangle:”))

area=1/2 * b * h

print(“area is:”,area)

output:

 enter the base of a triangle:20

enter the height of a triangle:40

area is: 400.0

48.Write a Python program to compute the greatest common divisor (GCD) of two positive integers.

Program:

def gcd(x, y):

    gcd = 1

     if x % y == 0:

        return y

    for k in range(int(y / 2), 0, -1):

        if x % k == 0 and y % k == 0:

            gcd = k

            break 

    return gcd

print(gcd(12, 17))

print(gcd(4, 6))

Output:

1

2

49.Write a Python program to get the least common multiple (LCM) of two positive integers.

def lcm(x,y):

    if x>y:

        z=x

    else:

        z=y

 while(True):

        if ((z%x==0) and (z%y==0)):

            lcm = z

            break

        z += 1

        return lcm

print(lcm(4,6))

print(lcm(15,17))

Output:

12

255

50.Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.

Program:

def sum(x,y,z):

    if x==y or y==z or x==z:

        sum=0

    else:

        sum=x+y+z

    return sum

print(sum(2,4,4))

print(sum(4,5,6))

print(sum(5,5,5))

print(sum(7,8,9))

Output:

0

15

0

24

51.Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.

def sum(x,y):

    sum=x+y

    if sum in range(15,20):

        return 20

    else:

        return sum

print(sum(10,6))

print(sum(10,2))

print(sum(10,12))

Output:

20

12

22

52.Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5.

def test_number5(x,y):

    if x==y or abs(x-y)==5 or (x+y)==5:

        return True

    else:

        return False

print(test_number5(7,2))

print(test_number5(3,2))

print(test_number5(2,2))

print(test_number5(10,11))

print(test_number5(12,20))

Output:

True

True

True

False

False

53.Write a Python program to add two objects if both objects are an integer type.

Program:

def add_number(a,b):

    if not(isinstance(a,int) and isinstance(b,int)):

        raise TypeError(“input must be integers”)

    return a+b

print(add_numbers(10,20))

Output:30

54.Write a Python program to display your details like name, age, address in three different lines

program:

def personal_details():

    name, age = “Simon”, 19

    address = “Bangalore, Karnataka, India”

    print(“Name: {}\nAge: {}\nAddress: {}”.format(name, age, address))

personal_details()

Output:

Name: Simon                                                                                                   

Age: 19                                                                                                      

Address: Bangalore, Karnataka, India

55.Write a Python program to solve (x + y) * (x + y).

x, y = 4, 3

result = x * x + 2 * x * y + y * y

print(“({} + {}) ^ 2) = {}”.format(x, y, result))

 Output:

(4 + 3) ^ 2) = 49

56.Write a Python program to compute the future value of a specified principal amount, rate of interest, and a number of years.

Solution:-

amt = 10000

int = 3.5

years = 7

future_value  = amt*((1+(0.01*int)) ** years)

print(round(future_value,2))

 Output:

12722.79

57.Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).

Solution:-

import math

p1 = [4, 0]

p2 = [6, 6]

distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

print(distance)

Output:

6.324555320336759

58.Write a Python program to check whether a file exists.

Solution:-

import os.path

open(‘abc.txt’, ‘w’)

print(os.path.isfile(‘abc.txt’))

Output:

True

59.Write a Python program to determine if a Python shell is executing in 32bit or 64bit mode on OS?

Solution:

# For 32 bit it will return 32 and for 64 bit it will return 64

import struct

print(struct.calcsize(“P”) * 8)

Output:64

60. Write a Python program to get OS name, platform and release information.

Solution:-

import platform

import os

print(os.name)

print(platform.system())

print(platform.release())

Output:

posix                                                                                                        

Linux                                                                                                         

4.4.0-47-generic

61.Write a Python program to locate Python site-packages.

Solution:-

import site;

print(site.getsitepackages())

Output:

[‘/usr/local/lib/python3.5/dist-packages’, ‘/usr/lib/python3/dist-packages’, ‘/usr/lib/python3.5/dist-packages

‘]

62.Write a python program to call an external command in Python.

Solution:-

from subprocess import call

call([“ls”, “-l”])

Output:

drwxrwxr-x 2 students  students    4096 Sep 15  2016 c48d5200-7b43-11e6-b7e4-2516b8e1f7f8                     

drwxrwxr-x 2 students  students    4096 Sep 21  2016 c4a96850-7fdf-11e6-a2b3-172481646809                    

drwxrwxr-x 2 students  students    4096 Sep  7  2016 c4d98410-74de-11e6-ac36-65f2f75d0c7b                    

drwxrwxr-x 2 students  students    4096 Sep  6  2016 c4fa6e10-7424-11e6-812c-5574d751e2d7                    

drwxrwxr-x 2 prashanta prashanta   4096 Feb 20 18:24 c5216400-f76b-11e6-8ad1-9b7f6e755728  

——-

-rw-rw-r– 1 students  students      27 Sep 28  2016 temp.txt                                                

-rw-rw-r– 1 students  students      27 Sep 28  2016 test.txt 

63.Write a python program to get the path and name of the file that is currently executing.

Solution:-

import os

print(“Current File Name : “,os.path.realpath(__file__))

Output:

Current File Name :  /home/students/fb6e28e0-2425-11e7-807b-bd9de91b1602.py

64.Write a Python program to find out the number of CPUs using.

Solution:-

import multiprocessing

print(multiprocessing.cpu_count())Output:4

65.Write a Python program to parse a string to Float or Integer.

Solution:-

n = “246.2458”

print(float(n))

print(int(float(n)))

Output:246.2458                                                                                                      

246

66.Write a Python program to list all files in a directory in Python.

Solution:-

from os import listdir

from os.path import isfile, join

files_list = [f for f in listdir(‘/home/students’) if isfile(join(‘/home/students’, f))]

print(files_list);

Output:

[‘3ff44d80-2423-11e7-807b-bd9de91b1602.py’, ‘f5272c90-2423-11e7-807b-bd9de91b1602.py’, ‘test.txt’, ‘f34e26d0-2

423-11e7-807b-bd9de91b1602.py’, ‘f6a62b70-2423-11e7-807b-bd9de91b1602.py’, ‘.mysql_history’, ‘.bash_logout’, ‘

037db660-240b-11e7-807b-bd9de91b1602.py’, ‘3d299190-241f-11e7-807b-bd9de91b1602.py’, ‘8e7e22f0-240f-11e7-807b-

bd9de91b1602.py’, ‘.bash_history’, ‘276b1dd0-2404-11e7-807b-bd9de91b1602.py’, ‘7e2f05d0-241a-11e7-807b-bd9de91

b1602.py’, ‘6956ba40-2429-11e7-807b-bd9de91b1602.py’, ‘.profile’, ‘abc.py’, ‘f69a4490-2423-11e7-807b-bd9de91b1

602.py’, ‘.viminfo’, ‘mynewtest.txt’, ‘myfile.txt’, ‘logging_example.out’, ‘.web-term.json’, ‘d2c942f0-2423-11

e7-807b-bd9de91b1602.py’, ‘ca7c2750-242a-11e7-807b-bd9de91b1602.py’, ‘abc.txt’, ‘exercise.cs’, ‘.bashrc’, ‘Exa

mple.cs’, ‘2f5aa190-2428-11e7-807b-bd9de91b1602.py’, ‘2d5d6540-2418-11e7-807b-bd9de91b1602.py’, ‘5bfc84e0-240d

-11e7-807b-bd9de91b1602.py’, ‘940ca5b0-2406-11e7-807b-bd9de91b1602.py’, ‘myfig.png’, ‘file.out’, ‘a7af6660-241

6-11e7-807b-bd9de91b1602.py’, ‘4a690da0-2428-11e7-807b-bd9de91b1602.py’, ‘line.gif’, ‘mmm.txt\n’, ‘temp.txt’,

‘fb6e28e0-2425-11e7-807b-bd9de91b1602.py’, ‘f0896180-2423-11e7-807b-bd9de91b1602.py’, ‘dddd.txt\n’, ‘700da350-

2413-11e7-807b-bd9de91b1602.py’, ‘sss.dat\n’, ’05f2fa20-2421-11e7-807b-bd9de91b1602.py’, ‘result.txt’, ’68c38d

e0-241c-11e7-807b-bd9de91b1602.py’, ‘output.jpg’, ‘c930d080-2407-11e7-807b-bd9de91b1602.py’, ‘2e8ace70-2428-11

e7-807b-bd9de91b1602.py’, ‘26492-1274250701.png’, ‘mytest.txt’, ’07fd1540-2411-11e7-807b-bd9de91b1602.py’]

67.Write a Python program to print without newline or space?

Solution:-

for i in range(0, 10):

    print(‘*’, end=””)

print(“\n”)

Output:

**********

68.Write a Python program to determine profiling of Python programs.

Note: A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.

Solution:-

import cProfile

def sum():

    print(1+2)

cProfile.run(‘sum()’)

Output:3                                                                                                            

         5 function calls in 0.000 seconds                                                                   

    Ordered by: standard name                                                                                                                                                                                             

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)                                      

        1    0.000    0.000    0.000    0.000 7aa14930-2430-11e7-807b-bd9de91b1602.py:2(sum)                 

        1    0.000    0.000    0.000    0.000 <string>:1(<module>)                                            

        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}                                

        1    0.000    0.000    0.000    0.000 {built-in method builtins.print}                               

        1    0.000    0.000    0.000    0.000 {method ‘disable’ of ‘_lsprof.Profiler’ objects} 

69.Write a Python program to print to stderr.

Solution:-

from __future__ import print_function

import sys

def eprint(*args, **kwargs):

    print(*args, file=sys.stderr, **kwargs)

eprint(“abc”, “efg”, “xyz”, sep=”–“)

Output:

abc–efg–xyz

70.Write a python program to access environment variables.

Solution:-

import os

# Access all environment variables

print(‘*———————————-*’)

print(os.environ)

print(‘*———————————-*’)

# Access a particular environment variable

print(os.environ[‘HOME’])

print(‘*———————————-*’)

print(os.environ[‘PATH’])

print(‘*———————————-*’)

Output:

*———————————-*                                                                         

environ({‘LESSOPEN’: ‘| /usr/bin/lesspipe %s’, ‘_’: ‘/usr/bin/timeout’, ‘LIBVIRT_DEFAULT_URI’: ‘qemu:///system

‘, ‘HOME’: ‘/home/students’, ‘TERM’: ‘xterm-256color’, ‘SHELL’: ‘/bin/bash’, ‘SHLVL’: ‘2’, ‘USER’: ‘students’,

 ‘MAIL’: ‘/var/mail/students’, ‘COMP_WORDBREAKS’: ‘ \t\n”\’><;|&(:’, ‘PATH’: ‘/usr/local/bin:/usr/bin:/bin:/us

r/local/games:/usr/games’, ‘LANG’: ‘en_US.UTF-8’, ‘LOGNAME’: ‘students’, ‘LS_COLORS’: ‘rs=0:di=01;34:ln=01;36:

mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42

:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;3

1:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.d

z=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;

31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:

*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.

bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.p

ng=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.m

kv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wm

v=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01

;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36

:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:

*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:’, ‘JAVA_HOME’: ‘/usr/lib/jvm/java-7-openjdk-amd

64/jre/bin/java’, ‘LESSCLOSE’: ‘/usr/bin/lesspipe %s %s’, ‘PWD’: ‘/home/students’})                          

*———————————-*                                                                         

/home/students                                                                                                

*———————————-*                                                                         

/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games                                                     

*———————————-* 

71.Write a Python program to get the current username

Solution:-

import getpass

print(getpass.getuser())

Output:

students

72.Write a Python to find local IP addresses using Python’s stdlib.

Solution:-

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

Output:

192.168.0.200

73.Write a Python program to get height and the width of console window.

Solution:-

def terminal_size():

    import fcntl, termios, struct

    th, tw, hp, wp = struct.unpack(‘HHHH’,

        fcntl.ioctl(0, termios.TIOCGWINSZ,

        struct.pack(‘HHHH’, 0, 0, 0, 0)))

    return tw, th

print(‘Number of columns and Rows: ‘,terminal_size())

Output:

Number of columns and Rows:  (110, 21)

74.Write a program to get execution time (in seconds) for a Python method

Solution:-

import time

def sum_of_n_numbers(n):

    start_time = time.time()

    s = 0

    for i in range(1,n+1):

        s = s + i

    end_time = time.time()

    return s,end_time-start_time

n = 5

print(“\nTime to sum of 1 to “,n,” and required time to calculate is :”,sum_of_n_numbers(n))

Output:

Time to sum of 1 to  5  and required time to calculate is : (15, 2.384185791015625e-06)

75.Write a python program to sum of the first n positive integers.

Solution:-

n = int(input(“Input a number: “))

sum_num = (n * (n + 1)) / 2

print(sum_num)

Output:

Input a number: 2                                                                                            

3.0

76.Write a Python program to convert height (in feet and inches) to centimeters.

Convert height (in feet and inches) to centimeters

Sample Solution:-

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)

Output:

Input your height:                                                                                           

Feet: 5                                                                                                      

Inches: 3                                                                                                     

Your height is : 160 cm.

77.Write a Python program to calculate the hypotenuse of a right angled triangle.

Calculate the hypotenuse of a right angled triangle

Solution :-

from math import sqrt

print(“Input lengths of shorter triangle sides:”)

a = float(input(“a: “))

b = float(input(“b: “))

c = sqrt(a**2 + b**2)

print(“The length of the hypotenuse is”, c )

Output:

Input lengths of shorter triangle sides:                                                                      

a: 3                                                                                                         

b: 4                                                                                                          

The length of the hypotenuse is 5.0 

78.Write a Python program to convert the distance (in feet) to inches, yards, and miles.

Convert the distance (in feet) to inches, yards, and miles

Sample Solution :-

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)

Output:

Input distance in feet: 100                                                                                  

The distance in inches is 1200 inches.                                                                       

The distance in yards is 33.33 yards.                                                                        

The distance in miles is 0.02 miles.

79.Write a Python program to convert all units of time into seconds.

Convert all units of time into seconds

Solution:-

days = int(input(“Input days: “)) * 3600 * 24

hours = int(input(“Input hours: “)) * 3600

minutes = int(input(“Input minutes: “)) * 60

seconds = int(input(“Input seconds: “))

time = days + hours + minutes + seconds

print(“The  amounts of seconds”, time)

Output:

Input days: 4                                                                                                 

Input hours: 5                                                                                               

Input minutes: 20                                                                                             

Input seconds: 10                                                                                            

The  amounts of seconds 364810

80.Write a Python program to convert all units of time into seconds.

Convert all units of time into seconds

Solution:-

days = int(input(“Input days: “)) * 3600 * 24

hours = int(input(“Input hours: “)) * 3600

minutes = int(input(“Input minutes: “)) * 60

seconds = int(input(“Input seconds: “))

time = days + hours + minutes + seconds

print(“The  amounts of seconds”, time)

Output:

Input days: 4                                                                                                

Input hours: 5                                                                                                

Input minutes: 20                                                                                            

Input seconds: 10                                                                                             

The  amounts of seconds 364810

81.Write a Python program to get an absolute file path.

Solution:-

def absolute_file_path(path_fname):

        import os

        return os.path.abspath(‘path_fname’)       

print(“Absolute file path: “,absolute_file_path(“test.txt”))

Output:

Absolute file path:  /home/students/path_fname

82.Write a Python program to get file creation and modification date/times.

Solution :

import os.path, time

print(“Last modified: %s” % time.ctime(os.path.getmtime(“test.txt”)))

print(“Created: %s” % time.ctime(os.path.getctime(“test.txt”)))

Output:

Last modified: Wed Apr 19 11:36:23 2017                                                                      

Created: Wed Apr 19 11:36:23 2017

Flowchart:

83.Write a Python program to convert seconds to day, hour, minutes and seconds.

Convert seconds to day, hour, minutes and seconds

Solution:-

time = float(input(“Input time in seconds: “))

day = time // (24 * 3600)

time = time % (24 * 3600)

hour = time // 3600

time %= 3600

minutes = time // 60

time %= 60

seconds = time

print(“d:h:m:s-> %d:%d:%d:%d” % (day, hour, minutes, seconds))

Output:

Input time in seconds: 1234565                                                                               

d:h:m:s-> 14:6:56:5

84.Write a Python program to calculate body mass index.

Calculate body mass index

Solution:-

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

Output:

Input your height in meters: 5.8                                                                             

Input your weight in kilogram: 85                                                                             

Your body mass index is:  2.53

85.Write a Python program to convert pressure in kilopascals to pounds per square inch,a millimeter of mercury (mmHg) and atmosphere pressure.

Convert pressure in kilopascals to pounds

Solution:-

kpa = float(input(“Input pressure in in kilopascals> “))

psi = kpa / 6.89475729

mmhg = kpa * 760 / 101.325

atm = kpa / 101.325

print(“The pressure in pounds per square inch: %.2f psi”  % (psi))

print(“The pressure in millimeter of mercury: %.2f mmHg” % (mmhg))

print(“Atmosphere pressure: %.2f atm.” % (atm))

Output:

Input pressure in in kilopascals> 12.35                                                                      

The pressure in pounds per square inch: 1.79 psi                                                              

The pressure in millimeter of mercury: 92.63 mmHg                                                            

Atmosphere pressure: 0.12 atm.

86.Write a Python program to calculate the sum of the digits in an integer.

Calculate the sum of the digits in an intege

Solution:-

num = int(input(“Input a four digit numbers: “))

x  = num //1000

x1 = (num – x*1000)//100

x2 = (num – x*1000 – x1*100)//10

x3 = num – x*1000 – x1*100 – x2*10

print(“The sum of digits in the number is”, x+x1+x2+x3)

Output:

Input a four digit numbers: 5245                                                                             

The sum of digits in the number is 16

87.Write a Python program to sort three integers without using conditional statements and loops.

Sort three integers without using conditional statements and loops

Solution:-

x = int(input(“Input first number: “))

y = int(input(“Input second number: “))

z = int(input(“Input third number: “))

a1 = min(x, y, z)

a3 = max(x, y, z)

a2 = (x + y + z) – a1 – a3

print(“Numbers in sorted order: “, a1, a2, a3)

Output:

Input first number: 2                                                                                        

Input second number: 4                                                                                        

Input third number: 5                                                                                        

Numbers in sorted order:  2 4 5

88.Write a Python program to sort files by date.

Solution:-

import glob

import os

files = glob.glob(“*.txt”)

files.sort(key=os.path.getmtime)

print(“\n”.join(files))

Output:

result.txt                                                                                                   

temp.txt                                                                                                      

myfile.txt                                                                                                   

mynewtest.txt                                                                                                 

mytest.txt                                                                                                   

abc.txt                                                                                                       

test.txt

89.Write a Python program to get a directory listing, sorted by creation date.

Solution:-

from stat import S_ISREG, ST_CTIME, ST_MODE

import os, sys, time

#Relative or absolute path to the directory

dir_path = sys.argv[1] if len(sys.argv) == 2 else r’.’

#all entries in the directory w/ stats

data = (os.path.join(dir_path, fn) for fn in os.listdir(dir_path))

data = ((os.stat(path), path) for path in data)

# regular files, insert creation date

data = ((stat[ST_CTIME], path)

           for stat, path in data if S_ISREG(stat[ST_MODE]))

for cdate, path in sorted(data):

    print(time.ctime(cdate), os.path.basename(path))

Output:

Mon Feb 22 16:11:49 2016 .bash_logout                                                                         

Mon Feb 22 16:11:49 2016 .bashrc                                                                             

Mon Feb 22 16:11:49 2016 .profile                                                                            

Mon May 30 11:45:34 2016 .mysql_history                                                                      

Sat Aug 13 11:37:48 2016 logging_example.out                                                                 

Tue Sep 13 10:56:31 2016 result.txt                                                                          

Tue Sep 20 18:00:14 2016 dddd.txt       

——-

Tue Apr 18 15:06:27 2017 abc.txt                                                                             

Wed Apr 19 13:46:47 2017 .bash_history                                                                       

Wed Apr 19 15:15:52 2017 test.txt                                                                            

Wed Apr 19 16:58:20 2017 4ab8fe20-24f3-11e7-afe4-85767fd0ee52.py 

90.Write a Python program to get the details of math module.

Program:

import math

math_Is=dir(math)

print(math_Is)

Output:

[‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘pi’, ‘pow’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’]

91.Write a Python program to calculate midpoints of a line.

Program:

print(‘\ncalculate the midpoint of a line:’)

x1=float(input(“the value of x(the first endpoint)”))

y1=float(input(“the value of y(the first endpoint)”))

x2=float(input(“the value of x(the first endpoint)”))

y2=float(input(“the value of y(the first endpoint)”))

x_m_point=(x1+x2)/2

y_m_point=(y1+y1)/2

print();

print(“the midpoint of linee is:”)

print(“the midpoint’s x value is:”,x_m_point)

print(“the midpoint’s y value is:”,y_m_point)

print();

Output:

calculate the midpoint of a line:

the value of x(the first endpoint)4

the value of y(the first endpoint)6

the value of x(the first endpoint)8

the value of y(the first endpoint)2

the midpoint of linee is:

the midpoint’s x value is: 6.0

the midpoint’s y value is: 6.0

92.Write a Python program to hash a word.

Program:

soundex=[0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2]

word=input(“input the word be hashed:”)

word=word.upper()

coded=word[0]

for a in word[1:len(word)]:

    i=65-ord(a)

    coded=coded+str(soundex[i])

print()

print(“the coded word is:”+coded)

print()

Output:

input the word be hashed:w3r

the coded word is:W02

input the word be hashed:w4r

the coded word is:W52

input the word be hashed:w9r

the coded word is:W02

input the word be hashed:wr

the coded word is:W2

93.Write a Python program to get the copyright information.

Program:

import sys

print(“\npython copyright information”)

print(sys.copyright)

print()

OUTPUT:

python copyright information

Copyright (c) 2001-2018 Python Software Foundation.

All Rights Reserved.

Copyright (c) 2000 BeOpen.com.

All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.

All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.

All Rights Reserved.

94.Write a Python program to get the command-line arguments (name of the script, the number of arguments, arguments) passed to a script.

Program:

import sys

print(“this is the name/path of the script:”),sys.argv[0]

print(“number of arguments:”,len(sys.argv))

print(“argument list:”,str(sys.argv))

Output:

This is the name/path of the script: test.py

(‘Number of arguments:’, 4)

(‘Argument List:’, “[‘test.py’, ‘arg1’, ‘arg2’, ‘arg3’]”)

95.Write a Python program to test whether the system is a big-endian platform or little-endian platform.

Program:

import sys

print()

if sys.byteorder == “little”:

    #intel, alpha

    print(“Little-endian platform.”)

else:

    #motorola, sparc

    print(“Big-endian platform.”)

print()

Output:

Little-endian platform

96.Write a Python program to find the available built-in modules.

Program:

import sys

import textwrap

module_name=’,’.join(sorted(sys.builtin_module_names))

print(textwrap.fill(module_name,width=70))

Output:

abc,_ast,_bisect,_blake2,_codecs,_codecs_cn,_codecs_hk,_codecs_iso202

2,_codecs_jp,_codecs_kr,_codecs_tw,_collections,_csv,_datetime,_functo

ols,_heapq,_imp,_io,_json,_locale,_lsprof,_md5,_multibytecodec,_opcode

,_operator,_pickle,_random,_sha1,_sha256,_sha3,_sha512,_signal,_sre,_s

tat,_string,_struct,_symtable,_thread,_tracemalloc,_warnings,_weakref,

_winapi,array,atexit,audioop,binascii,builtins,cmath,errno,faulthandle

r,gc,itertools,marshal,math,mmap,msvcrt,nt,parser,sys,time,winreg,xxsu

btype,zipimport,zlib

97.Write a Python program to get the size of an object in bytes

Program:

import sys

str1=”one”

str2=”two”

str3=”three”

print()

print(“memory size of ‘”+str1+”‘ = “+str(sys.getsizeof(str1))+ “bytes”)

print(“memory size of ‘”+str2+”‘ = “+str(sys.getsizeof(str2))+ “bytes”)

print(“memory size of ‘”+str3+”‘ = “+str(sys.getsizeof(str3))+ “bytes”)

print()

output:

memory size of ‘one’ = 28bytes

memory size of ‘two’ = 28bytes

memory size of ‘three’ = 30bytes

98.Write a Python program to get the current value of the recursion limit.

Program:

import sys

print()

print(“current value of the recursion limit:”)

print(sys.getrecursionlimit())

print()

Output:

current value of the recursion limit:1000

99.Write a Python program to concatenate N strings.

Program:

list_of_colors=[‘red’,’white’,’black’]

colors=’-‘.join(list_of_colors)

print()

print(“all colors:”+colors)

print()

output:

all colors:red-white-black

100.Write a Python program to calculate the sum over a container

program:

s=sum([10,20,30])

print(“\nsum of the container:”,s)

print()

Output:

sum of the container: 60

Leave a Reply

Your email address will not be published. Required fields are marked *

RSS
Follow by Email
Facebook
Facebook
Google+
http://ojango.org/1000-python-programs">
Twitter