Sample Python Codes

¡Supera tus tareas y exámenes ahora con Quizwiz!

Profile

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.

Write a Python program to compute the product of a list of integers (without using for loop).

from functools import reduce nums = [10, 20, 30,] nums_product = reduce( (lambda x, y: x * y), nums) print("Product of the numbers : ",nums_product)

Write a Python program to access and print a URL's content to the console.

from http.client import HTTPConnection conn = HTTPConnection("example.com") conn.request("GET", "/") result = conn.getresponse() # retrieves the entire contents. contents = result.read() print(contents)

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

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

Write a Python program to calculate body mass index.

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 get the current username.

import getpass print(getpass.getuser())

Write a Python program to make file lists from current directory using a wildcard.

import glob file_list = glob.glob('*.*') print(file_list)

Write a Python program to sort files by date.

import glob import os files = glob.glob("*.txt") files.sort(key=os.path.getmtime) print("\n".join(files))

Write a Python program to clear the screen or terminal.

import os import time # for windows # os.system('cls') os.system("ls") time.sleep(2) # Ubuntu version 10.10 os.system('clear')

Write a Python program to get the effective group id, effective user id, real group id, a list of supplemental group ids associated with the current process.

import os print("\nEffective group id: ",os.getegid()) print("Effective user id: ",os.geteuid()) print("Real group id: ",os.getgid()) print("List of supplemental group ids: ",os.getgroups()) print()

Write a Python program to get the users environment.

import os print() print(os.environ) print()

Write a Python program to extract the filename from a given path.

import os print() print(os.path.basename('/users/system1/student1/homework-1.py')) print()

Write a Python program to concatenate N strings.

list_of_colors = ['Red', 'White', 'Black'] colors = '-'.join(list_of_colors) print() print("All Colors: "+colors) print()

Write a Python program to count the number occurrence of a specific character in a string.

s = "The quick brown fox jumps over the lazy dog." print() print(s.count("q")) print()

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

s = sum([10,20,30]) print("\nSum of the container: ", s) print()

Write a Python program to list the special variables used within the language.

s_var_names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print() print( '\n'.join(' '.join(s_var_names[i:i+8]) for i in range(0, len(s_var_names), 8)) ) print()

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

# Imports the math module import math #Sets everything to a list of math module math_ls = dir(math) # print(math_ls)

Python Docstrings

1. A Docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a Docstring becomes the __doc__ special attribute of that object. 2. All modules should normally have Docstrings, and all functions and classes exported by a module should also have docstrings. Public methods, such as __init__, should have Docstrings.

Write a Python program to create a histogram from a list of values.

1. Code - f histogram( items ): for n in items: output = '' times = n while( times > 0 ): output += '*' times = times - 1 print(output) histogram([2, 3, 6, 5])

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

1. Code - from subprocess import call call(["ls", "-l"])

Write a Python program to determine profiling of Python programs.

1. Code - import cProfile def sum(): print(1+2) cProfile.run('sum()')

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

1. Code - import datetime now = datetime.datetime.now() print (now.strftime("%Y-%m-%d %H:%M:%S")) 2. Additional Information - The datetime module supplies classes for manipulating dates and times in both simple and complex ways. datetime.now(tz=None) returns the current date and time. If the optional argument tz is none, then it displays the date and time of today. date.strftime(format) returns a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values.

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

1. Code - import multiprocessing print(multiprocessing.cpu_count())

Write a python program to access environment variables.

1. Code - 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('*----------------------------------*')1

Write a Python program to check whether a file exists.

1. Code - import os.path open('abc.txt', 'w') print(os.path.isfile('abc.txt'))

Write a Python program to empty a variable without destroying it

1. Sample data: n=20 d = {"x":200} Expected Output: 0 {} 2. n = 20 d = {"x":200} l = [1,3,5] t= (5,7,8) print(type(n)()) print(type(d)()) print(type(l)()) print(type(t)())

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

1. Sample function - abs() 2. Code - print(abs.__doc__)

Python str.rsplit(sep=None, maxsplit=-1) function

1. The function returns a list of the words of a given string using a separator as the delimiter string. If maxsplit is given, the list will have at most maxsplit+1 terms. if maxsplit is not given or -1, then there is no limit on the number of splits. If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings. The sep argument may consist of multiple characters. Splitting an empty string with a specified separator returns ['']. 2. Code - filename = input("Input the Filename: ") f_extns = filename.split(".") print ("The extension of the file is : " + repr(f_extns[-1]))

Python - Swapping two variables

1. The simplest way to swap two variables is to use a third temporary variable. define swap(a, b) temp := a a := b b := temp

ASCII

American Standard Code for Information Interchange, is a character encoding standard. ASCII codes represent text in computers, telecommunications equipment, and other devices. Most modern character-encoding schemes are based on ASCII, although they support many additional characters.

raw_input()

Used for Python 2.x

input()

Used for Python 3.x

Write a Python program to swap two variables.

a = 30 b = 20 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 remove the first item from a specified list.

color = ["Red", "Black", "Green", "White", "Orange"] print("\nOriginal Color: ",color) del color[0] print("After removing the first color: ",color) print()

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

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

Write a Python program to display the examination schedule.

exam_st_date = (11,12,2014) print( "The examination will start from : %i / %i / %i"%exam_st_date

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

fname = input("Input your First Name : ") lname = input("Input your Last Name : ") print ("Hello" + lname + " " + fname)

Write a Python program to get the size of a file.

import os file_size = os.path.getsize("abc.txt") print("\nThe size of abc.txt is :",file_size,"Bytes") print()

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

import sys str1 = "one" str2 = "four" 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()

Get the system time.

import time print() print(time.ctime()) print()

Write a Python program to get the identity of an object.

obj1 = object() obj1_address = id(obj1) print() print(obj1_address) print()

Write a Python program to display a floating number in specified numbers.

order_amt = 212.374 print('\nThe total order amount comes to %f' % order_amt) print('The total order amount comes to %.2f' % order_amt) print()

Write a Python program to hash a word.

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

Write a Python program to check if a string is numeric.

str = 'a123' #str = '123' try: i = float(str) except (ValueError, TypeError): print('\nNot numeric') print()

Write a Python program to print Unicode characters

str = u'\u0050\u0079\u0074\u0068\u006f\u006e \u0045\u0078\u0065\u0072\u0063\u0069\u0073\u0065\u0073 \u002d \u0077\u0033\u0072\u0065\u0073\u006f\u0075\u0072\u0063\u0065' print() print(str) print()

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

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)

Write a Python program to determine if variable is defined or not.

try: x = 1 except NameError: print("Variable is not defined....!") else: print("Variable is defined.") try: y except NameError: print("Variable is not defined....!") else: print("Variable is defined.")

Write a Python code to generate a list or tuple from a set of numbers

values = input("Input some comma separated numbers: ") list = values.split(",") tuple = tuple(list) print('List : ',list) print('Tuple : ',tuple)

Write a Python program to input a number, if it is not a number generate an error message.

while True: try: a = int(input("Input a number: ")) break except ValueError: print("\nThis is not a number. Try again...") print()

Given variables x=30 and y=20, write a Python program to print "30+20=50."

x = 30 y = 20 print("\n%d+%d=%d" % (x, y, x+y)) print()

Write a Python program to convert a byte string to a list of integers.

x = b'Abc' print() print(list(x)) print()

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

1. Code - def add_numbers(a, b): if not (isinstance(a, int) and isinstance(b, int)): raise TypeError("Inputs must be integers") return a + b print(add_numbers(10, 20))

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

1. Code - def concatenate_list_data(list): result= '' for element in list: result += str(element) return result print(concatenate_list_data([1, 5, 12, 2]))

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

1. Code - 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))

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

1. Code - 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))

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.

1. Code - 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"))

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

1. Code - def personal_details(): name, age = "Simon", 19 address = "Bangalore, Karnataka, India" print("Name: {}\nAge: {}\nAddress: {}".format(name, age, address)) personal_details()

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.

1. Code - 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));

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

1. Code - 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, 1, 2)) print(sum(3, 2, 2)) print(sum(2, 2, 2)) print(sum(1, 2, 3))

Write a Python program to print without newline or space.

1. Code - for i in range(0, 10): print('*', end="") print("\n")

Write a Python program to print to stderr

1. Code - from __future__ import print_function import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) eprint("abc", "efg", "xyz", sep="--")

Write a Python program that calculates the number of days between two dates.

1. Code - from datetime import date f_date = date(2014, 7, 2) l_date = date(2014, 7, 11) delta = l_date - f_date print(delta.days)

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

1. Code - 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);

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

1. Code - import platform import os print(os.name) print(platform.system()) print(platform.release())

Write a Python program to locate Python site-packages.

1. Code - import site; print(site.getsitepackages())

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

1. Code - import struct print(struct.calcsize("P") * 8)

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

1. Code - import sys print(sys.version) print(sys.version_info) 2. This will print a string containing the version number of Python. It will also print a tuple containing the five components of this version number.

Write a Python program to parse a string to float or integer.

1. Code - n = "246.2458" print(float(n)) print(int(float(n)))

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

1. Code - import os print("Current File Name : ",os.path.realpath(__file__))

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

1. Use the calendar module, calendar.month(theyear, themonth, w=0, l=0). 2. The function returns a month's calendar in a multi-line string using the formatmonth() of the TextCalendar class. l specifies the number of lines that each week will use. 3. import calendar y = int(input("Input the year : ")) m = int(input("Input the month : ")) print(calendar.month(y, m))

Write a Python program to print the following here document.

1. a string that you "don't" have to escape This is a ....... multi-line heredoc string --------> example 2. print(""" a string that you "don't" have to escape This is a ....... multi-line heredoc string --------> example """)

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

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 to convert all units of time into seconds.

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)

Write a Python program to check if a file path is a file or a directory.

import os path="abc.txt" if os.path.isdir(path): print("\nIt is a directory") elif os.path.isfile(path): print("\nIt is a normal file") else: print("It is a special file (socket, FIFO, device file)" ) print()

Write a Python program to find path refers to a file or directory when you encounter a path name.

import os.path for file in [ __file__, os.path.dirname(__file__), '/', './broken_link']: print('File :', file) print('Absolute :', os.path.isabs(file)) print('Is File? :', os.path.isfile(file)) print('Is Dir? :', os.path.isdir(file)) print('Is Link? :', os.path.islink(file)) print('Exists? :', os.path.exists(file)) print('Link Exists?:', os.path.lexists(file))

Write a Python program to divide a path on the extension separator.

import os.path for path in [ 'test.txt', 'filename', '/user/system/test.txt', '/', '' ]: print('"%s" :' % path, os.path.splitext(path))

Write a Python program to retrieve file properties.

import os.path import time print('File :', __file__) print('Access time :', time.ctime(os.path.getatime(__file__))) print('Modified time:', time.ctime(os.path.getmtime(__file__))) print('Change time :', time.ctime(os.path.getctime(__file__))) print('Size :', os.path.getsize(__file__))

Write a Python program to get the name of the host on which the routine is running.

import socket host_name = socket.gethostname() print() print("Host name:", host_name) print()

Write a Python to find local IP addresses using Python's stdlib

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 get system command output.

import subprocess # file and directory listing returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True) print("dir command to list file and directory") print(returned_text)

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

import sys import textwrap module_name = ', '.join(sorted(sys.builtin_module_names)) print(textwrap.fill(module_name, width=70))

Write a Python program to determine the largest and smallest integers, longs, floats.

import sys print("Float value information: ",sys.float_info) print("\nInteger value information: ",sys.int_info) print("\nMaximum size of an integer: ",sys.maxsize)

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

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)) prashanta@server:~$ python test.py arg1 arg2 arg3

Write a Python program to get the copyright information.

import sys print("\nPython Copyright Information") print(sys.copyright) print()

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

import sys print() if sys.byteorder == "little": #intel, alpha print("Little-endian platform.") else: #motorola, sparc print("Big-endian platform.") print()

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

import sys print() print("Current value of the recursion limit:") print(sys.getrecursionlimit()) print()

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

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

Write a Python program to print the current call stack.

import traceback print() def f1():return abc() def abc():traceback.print_stack() f1() print()

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

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

Write a Python program to perform an action if a condition is true.

n=1 if n == 1: print("\nFirst day of a month") print()

Write a Python program to test whether all numbers of a list is greater than a certain number.

num = [2,3,4] print() print(all(x > 1 for x in num)) print(all(x > 4 for x in num)) print()

Write a Python program to get numbers divisible by fifteen from a list using an anonymous function.

num_list = [45, 55, 60, 37, 100, 105, 220] # use anonymous function to filter result = list(filter(lambda x: (x % 15 == 0), num_list)) print("Numbers divisible by 15 are",result)

Write a Python program to filter the positive numbers from a list

nums = [34, 1, 0, -23] print("Original numbers in the list: ",nums) new_nums = list(filter(lambda x: x >0, nums)) print("Positive numbers in the list: ",new_nums)

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

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 create a bytearray from a list.

print() nums = [10, 20, 56, 35, 17, 99] # Create bytearray from list of integers. values = bytearray(nums) for x in values: print(x) print()

Write a Python program to define a string containing special characters in various forms.

print() print("\#{'}${\"}@/") print("\#{'}${"'"'"}@/") print(r"""\#{'}${"}@/""") print('\#{\'}${"}@/') print('\#{'"'"'}${"}@/') print(r'''\#{'}${"}@/''') print()

Write a Python program to create a copy of its own source code.

print() print((lambda str='print(lambda str=%r: (str %% str))()': (str % str))()) print()

Write a Python program to get the ASCII value of a character.

print() print(ord('a')) print(ord('A')) print(ord('1')) print(ord('@')) print()

Write a Python program to prove that two string variables of same value point same memory location.

str1 = "Python" str2 = "Python" print("\nMemory location of str1 =", hex(id(str1))) print("Memory location of str2 =", hex(id(str2))) print()

Write a Python program to format a specified string to limit the number of characters to 6.

str_num = "1234567890" print() print('%.6s' % str_num) print()


Conjuntos de estudio relacionados

Apply It: Chapter 08 Persuasive Messages

View Set

Chapter 13: Direct Participation Programs

View Set

Live Virtual Machine Lab 6.1: Module 06 Securing an Environment using Mitigating Techniques

View Set

Chapter 16 objectives: cardiovascular emergencies

View Set