Python Examples Set 1

Example 1

@pytohn1.py

# comment1 # Guido has tweeted about multiline comments, # Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-) ''' This is a comment. ''' """ This is also a COMMENT. """ print "# This is not a comment" print "an Ashish Ranjan presentation" ash = "an Ashish Ranjan pesentation" print 'This is ', ash print ash variable1 = 12 variable2 = 4 variable3 = 12 / 4 variable4 = 12 % 4 print variable1, variable2 print variable3, variable4 var5, var6 = "India", 99 print var5, var6 var7, var8 = 10, 20 print "var7 = ", var7, "var8: ", var8 var7, var8 = var8, var7 + var8 print "var7 = ", var7, "var8: ", var8 # same as var9 = 10 var10 = 20 print "var9 = ", var9, "var10: ", var10 temp = var9 var9 = var10 var10 = temp + var10 print "var9 = ", var9, "var10: ", var10

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================ RESTART: F:\Python Programs\set 1\pytohn1.py ================ # This is not a comment an Ashish Ranjan presentation This is an Ashish Ranjan pesentation an Ashish Ranjan pesentation 12 4 3 0 India 99 var7 = 10 var8: 20 var7 = 20 var8: 30 var9 = 10 var10: 20 var9 = 20 var10: 30 >>>

Example2

@example2.py

# Fibonacci series: a1, b1 = 0, 1 while b1 < 1000: print b1, a1, b1 = b1, a1 + b1 print "\nAgain" a2, b2 = 0, 1 while b2 < 1000: print b2, temp = a2 a2 = b2 b2 = temp + b2

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example2.py =============== 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Again 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>>

Example 3

@example3.py

# input-output if-else random function-method import random number = 0 randomNumber = random.randint(0,5) while True: try: number = input("Please, guess a positive number (0,5): ") except: print "I asked for an number." continue break def checkGuess(theGuess): if theGuess == randomNumber: print 'You guessed it right' else: print 'You guessed it wrong. It\'s ', randomNumber if number < 0: print 'You entered a negative number: ', number print 'Think positive and be optimistic' checkGuess(number) elif number == 0: print 'Zero itself is nothing but can bring value when combined with others. Strength in unity.' checkGuess(number) elif number == 1: print 'You are always first.' checkGuess(number) else: checkGuess(number)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example3.py =============== Please, guess a positive number (0,5): 8 You guessed it wrong. It's 1 >>>

Example 3

@example3.py

# for loop, length var = ['an', 'Ashish Ranjan', 'presentation'] for each in var: print each, len(each)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example4.py =============== an 2 Ashish Ranjan 13 presentation 12 >>>

Example 4

@example4.py

# range function print range(10) print range(5, 10) print range(0, 10, 3) var = ['an', 'Ashish', 'Ranjan', 'presentation'] for each in range(len(var)): print each, var[each]

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example5.py =============== [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [5, 6, 7, 8, 9] [0, 3, 6, 9] 0 an 1 Ashish 2 Ranjan 3 presentation >>>

Example 6

@example6.py

# prime numbers, break for-else # It's a strange construct even to seasoned Python coders. # When used in conjunction with for-loops it basically means # "find some item in the iterable, else if none was found do ...". for each1 in range(2, 30): for each2 in range(2, each1): if each1 % each2 == 0: print each1, ' = ', each2, ' * ', each1/each2 break else: # loop fell through without finding a factor print each1, 'is a prime number'

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example6.py =============== 2 is a prime number 3 is a prime number 4 = 2 * 2 5 is a prime number 6 = 2 * 3 7 is a prime number 8 = 2 * 4 9 = 3 * 3 10 = 2 * 5 11 is a prime number 12 = 2 * 6 13 is a prime number 14 = 2 * 7 15 = 3 * 5 16 = 2 * 8 17 is a prime number 18 = 2 * 9 19 is a prime number 20 = 2 * 10 21 = 3 * 7 22 = 2 * 11 23 is a prime number 24 = 2 * 12 25 = 5 * 5 26 = 2 * 13 27 = 3 * 9 28 = 2 * 14 29 is a prime number >>>

Eaxmple 7

@example7.py

#pass statement does nothing. var1 = 7 var2 = 0 try: var1 / var2 except: pass try: var1 / var2 except: print "Something went wrong." print var1 / var2

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example7.py =============== Something went wrong. Traceback (most recent call last): File "F:/Python Programs/set 1/example7.py", line 16, in <module> print var1 / var2 ZeroDivisionError: integer division or modulo by zero >>>

Example 8

@example8.py

# functions output as user input def fib(last): """Print a Fibonacci series up to given term.""" first, second = 0, 1 print "Fibonacci series upto {} is:".format(last) while second <= last: print second, first, second = second, first + second print "Fibonacci series upto a specific number" while True: try: getInput = input("Please, enter last number: ") break except: print "A number required" continue fib(getInput)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example8.py =============== Fibonacci series upto a specific number Please, enter last number: 145 Fibonacci series upto 145 is: 1 1 2 3 5 8 13 21 34 55 89 144 >>>

Example 9

@example9.py

# python list storing numbers and function returning value result = [] def fib(last): """Print a Fibonacci series up to given term.""" first, second = 0, 1 print "Fibonacci series upto {} is:".format(last) while second <= last: result.append(second) first, second = second, first + second return result print "Fibonacci series upto a specific number" while True: try: getInput = input("Please, enter last number: ") break except: print "A number required" continue theList = fib(getInput) print theList

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example9.py =============== Fibonacci series upto a specific number Please, enter last number: t A number required Please, enter last number: 145 Fibonacci series upto 145 is: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] >>>

Example 10

@example10.py

# strings # concatenating strings word1 = 'Ashish' + 'Ranjan' print "word1: ", word1 print 'word1*5: <' + word1*5 + '>' word2 = 'Ashish' 'Ranjan' print "word2: ", word2 word3 = ' Ashish '.strip() + 'Ranjan' print "word3: ", word3 # accessing strings with index print "\nword1[4]: ", word1[4] print "word1[0:2]: ", word1[0:2] print "word1[2:4]: ", word1[2:4] print "\nword1[:2]: ", word1[:2] # The first two characters print "word1[2:]: ", word1[2:] # All but the first two characters # Python strings cannot be changed. Assigning to an indexed position in the string results in an error: # However, creating a new string with the combined content is easy and efficient: print "\n'an ' + word1[1:]: ", 'an ' + word1[1:] print "'OKAY' + word1[4]: ", 'OKAY' + word1[4] # string slice operations: s[:i] + s[i:] equals s. print "\nword1[:2] + word1[2:]: ", word1[:2] + word1[2:] print "word1[:3] + word1[3:]: ", word1[:3] + word1[3:] # Degenerate slice indices are handled gracefully: an index that is too large is replaced # by the string size, an upper bound smaller than the lower bound returns an empty string. print "\nword1[1:100]: ", word1[1:100] print "word1[10:]: ", word1[10:] print "word1[2:1]: ", word1[2:1] # Indices may be negative numbers, to start counting from the right. For example: print "\nword1[-1]: ", word1[-1] # The last character print "word1[-2]: ", word1[-2] # The last-but-one character print "word1[-2:]: ", word1[-2:] # The last two characters print "word1[:-2]: ", word1[:-2] # All but the last two characters # -0 is really the same as 0, so it does not count from the right! print "\nword1[-0]: ", word1[-0] # (since -0 equals 0) # Out-of-range negative slice indices are truncated, but don't try this for single-element (non-slice) indices: print "\nword1[-100:]: ", word1[-100:] print "Index Error" try: print word1[-10] # error except Exception as ex: print ex string = 'floccinaucinihilipilification' # the action or habit of estimating something as worthless print string print len(string)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example10.py =============== word1: AshishRanjan word1*5: <AshishRanjanAshishRanjanAshishRanjanAshishRanjanAshishRanjan> word2: AshishRanjan word3: AshishRanjan word1[4]: s word1[0:2]: As word1[2:4]: hi word1[:2]: As word1[2:]: hishRanjan 'an ' + word1[1:]: an shishRanjan 'OKAY' + word1[4]: OKAYs word1[:2] + word1[2:]: AshishRanjan word1[:3] + word1[3:]: AshishRanjan word1[1:100]: shishRanjan word1[10:]: an word1[2:1]: word1[-1]: n word1[-2]: a word1[-2:]: an word1[:-2]: AshishRanj word1[-0]: A word1[-100:]: AshishRanjan Index Error h floccinaucinihilipilification 29 >>>

Example 11

@example.py

# Default Argument def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries &l; 0: raise IOError('refusenik user') print complaint ask_ok('Do you really want to quit?') ask_ok('OK to overwrite the file?', 2) ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example11.py =============== Do you really want to quit?yes OK to overwrite the file?yes OK to overwrite the file?k Come on, only yes or no! OK to overwrite the file?l Come on, only yes or no! OK to overwrite the file?l Traceback (most recent call last): File "F:\Python Programs\set 1\example11.py", line 17, in <module> ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!') File "F:\Python Programs\set 1\example11.py", line 12, in ask_ok raise IOError('refusenik user') IOError: refusenik user >>>

Example 12

@example.py

# The default values are evaluated at the point of function definition in the defining scope i = 5 def f(arg=i): print(arg) i = 6 f() print i

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example12.py =============== 5 6 >>>

Example 13

@example13.py

# The default value is evaluated only once. This makes a difference when the default is a mutable object # such as a list, dictionary, or instances of most classes. def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3))

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example13.py =============== [1] [1, 2] [1, 2, 3] >>>

Example 14

@example14.py

# Lambda Forms def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) print f(0) print f(1) print f(15)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example14.py =============== 42 43 57 >>>

Example 15

example15.py

# speed test import time last = 9999999 i = 0 t0 = time.time() print "Loop started at: ", t0 while i<last: i = i + 1 t1 = time.time() print "Loop ended at: ", t1 total = t1-t0 print "Toal time taken for processing: ", total seconds = total hours = seconds / 3600 hoursRemain = hours % 60 minutes = hoursRemain / 60 secondsRemain = minutes % 60 print "i.e. %2.5f seconds" % (seconds)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example15.py =============== Loop started at: 1461492972.89 Loop ended at: 1461492974.81 Toal time taken for processing: 1.92100000381 i.e. 1.92100 seconds >>>

Example 16

@example16.py

import math # Both values are limited in precision only by the platform’s floating point C library. print 'Pi: %.30f' % math.pi print 'e: %.30f' % math.e # Floating point calculations can result in two types of exceptional values. # INF (infinity) appears when the double used to hold a floating point value overflows from a value with a large absolute value. print '\n{:^3} {:6} {:6} {:6}'.format('e', 'x', 'x**2', 'isinf') print '{:-^3} {:-^6} {:-^6} {:-^6}'.format('', '', '', '') # When the exponent in this example grows large enough, the square of x no longer fits inside a double, and the value is recorded as infinite. for e in range(0, 201, 20): x = 10.0 ** e y = x*x print '{:3d} {!s:6} {!s:6} {!s:6}'.format(e, x, y, math.isinf(y)) # Not all floating point overflows result in INF values, however. # Calculating an exponent with floating point values, in particular, raises OverflowError instead of preserving the INF result. x = 10.0 ** 200 print '\nx =', x print 'x*x =', x*x try: print 'x**2 =', x**2 except OverflowError, err: print err # Division operations using infinite values are undefined. The result of dividing a number by infinity is NaN ("not a number"). # NaN does not compare as equal to any value, even itself, so to check for NaN we must use isnan(). x = (10.0 ** 200) * (10.0 ** 200) y = x/x print '\nx =', x print 'isnan(x) =', math.isnan(x) print 'y = x / x =', x/x print 'y == nan =', y == float('nan') print 'isnan(y) =', math.isnan(y) # trunc() is equivalent to converting to int directly. print '\n{:^5} {:^5} {:^5} {:^5} {:^5}'.format('i', 'int', 'trunk', 'floor', 'ceil') print '{:-^5} {:-^5} {:-^5} {:-^5} {:-^5}'.format('', '', '', '', '') fmt = ' '.join(['{:5.1f}'] * 5) for i in [ -1.5, -0.8, -0.5, -0.2, 0, 0.2, 0.5, 0.8, 1 ]: print fmt.format(i, int(i), math.trunc(i), math.floor(i), math.ceil(i)) # modf() takes a single floating point number and returns a tuple containing the fractional and whole number parts of the input value. print for i in range(6): print '{}/2 = {}'.format(i, math.modf(i/2.0)) # frexp() returns the mantissa and exponent of a floating point number, and can be used to create a more portable representation of the value. # frexp() uses the formula x = m * 2**e, and returns the values m and e. print '\n{:^7} {:^7} {:^7}'.format('x', 'm', 'e') print '{:-^7} {:-^7} {:-^7}'.format('', '', '') for x in [ 0.1, 0.5, 4.0 ]: m, e = math.frexp(x) print '{:7.2f} {:7.2f} {:7d}'.format(x, m, e) # ldexp() is the inverse of frexp(). # Using the same formula as frexp(), ldexp() takes the mantissa and exponent values as arguments and returns a floating point number. print '\n{:^7} {:^7} {:^7}'.format('m', 'e', 'x') print '{:-^7} {:-^7} {:-^7}'.format('', '', '') for m, e in [(0.8, -3), (0.5, 0), (0.5, 3),]: x = math.ldexp(m, e) print '{:7.2f} {:7d} {:7.2f}'.format(m, e, x) # The absolute value of number is its value without a sign. Use fabs() to calculate the absolute value of a floating point number. # In practical terms, the absolute value of a float is represented as a positive value. print math.fabs(-1.1) print math.fabs(-0.0) print math.fabs(0.0) print math.fabs(1.1) # To determine the sign of a value, either to give a set of values the same sign or simply for comparison, use copysign() to set the sign of a known good value. print print '{:^5} {:^5} {:^5} {:^5} {:^5}'.format('f', 's', '< 0', '> 0', '= 0') print '{:-^5} {:-^5} {:-^5} {:-^5} {:-^5}'.format('', '', '', '', '') for f in [ -1.0, 0.0, 1.0, float('-inf'), float('inf'), float('-nan'), float('nan'), ]: s = int(math.copysign(1, f)) print '{:5.1f} {:5d} {!s:5} {!s:5} {!s:5}'.format(f, s, f < 0, f > 0, f==0) # Representing precise values in binary floating point memory is challenging. # Some values cannot be represented exactly, and the more often a value is manipulated through repeated calculations, # the more likely a representation error will be introduced. math includes a function for computing the sum of a series of floating point numbers # using an efficient algorithm that minimize such errors. # Given a sequence of ten values each equal to 0.1, the expected value for the sum of the sequence is 1.0. # Since 0.1 cannot be represented exactly as a floating point value, however, errors are introduced into the sum unless it is calculated with fsum(). values = [ 0.1 ] * 10 print '\nInput values:', values print 'sum() : {:.20f}'.format(sum(values)) s = 0.0 for i in values: s += i print 'for-loop : {:.20f}'.format(s) print 'math.fsum() : {:.20f}'.format(math.fsum(values)) print # factorial() is commonly used to calculate the number of permutations and combinations of a series of objects. # The factorial of a positive integer n, expressed n!, is defined recursively as (n-1)! * n and stops with 0! == 1. # factorial() only works with whole numbers, but does accept float arguments as long as they can be converted to an integer without losing value. for i in [ 0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.1 ]: try: print '{:2.0f} {:6.0f}'.format(i, math.factorial(i)) except ValueError, err: print '\nError computing factorial(%s):' % i, err # gamma() is like factorial(), except it works with real numbers and the value is shifted down one (gamma is equal to (n - 1)!). # Since zero causes the start value to be negative, it is not allowed. for i in [ 0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 ]: try: print '{:2.1f} {:6.2f}'.format(i, math.gamma(i)) except ValueError, err: print '\nError computing gamma(%s):' % i, err print # lgamma() returns the natural logarithm of the absolute value of Gamma for the input value. # Using lgamma() retains more precision than calculating the logarithm separately using the results of gamma(). for i in [ 0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 ]: try: print '{:2.1f} {:.20f} {:.20f}'.format(i, math.lgamma(i), math.log(math.gamma(i))) except ValueError, err: print 'Error computing lgamma(%s):' % i, err # The modulo operator (%) computes the remainder of a division expression (i.e., 5 % 2 = 1). # The operator built into the language works well with integers but, # as with so many other floating point operations, intermediate calculations cause representational issues that result in a loss of data. # fmod() provides a more accurate implementation for floating point values. # A potentially more frequent source of confusion is the fact that the algorithm used by fmod for computing modulo is also different from that used by %, # so the sign of the result is different. mixed-sign inputs. print '\n{:^4} {:^4} {:^5} {:^5}'.format('x', 'y', '%', 'fmod') print '---- ---- ----- -----' for x, y in [ (5, 2), (5, -2), (-5, 2),]: print '{:4.1f} {:4.1f} {:5.2f} {:5.2f}'.format(x, y, x % y, math.fmod(x, y)) # Exponential growth curves appear in economics, physics, and other sciences. # Python has a built-in exponentiation operator ("**"), but pow() can be useful when you need to pass a callable function as an argument. # Raising 1 to any power always returns 1.0, as does raising any value to a power of 0.0. # Most operations on the not-a-number value nan return nan. If the exponent is less than 1, pow() computes a root. print for x, y in [ # Typical uses (2, 3), (2.1, 3.2), # Always 1 (1.0, 5), (2.0, 0), # Not-a-number (2, float('nan')), # Roots (9.0, 0.5), (27.0, 1.0/3), ]: print '{:5.1f} ** {:5.3f} = {:6.3f}'.format(x, y, math.pow(x, y)) # Since square roots (exponent of 1/2) are used so frequently, there is a separate function for computing them. print print math.sqrt(9.0) print math.sqrt(3) try: print math.sqrt(-1) except ValueError, err: print 'Cannot compute sqrt(-1):', err # The logarithm function finds y where x = b ** y. By default, log() computes the natural logarithm (the base is e). # If a second argument is provided, that value is used as the base. # Logarithms where x is less than one yield negative results. print print math.log(8) print math.log(8, 2) print math.log(0.5, 2) # There are two variations of log(). Given floating point representation and rounding errors the computed value produced by log(x, b) has limited accuracy, # especially for some bases. log10() computes log(x, 10), using a more accurate algorithm than log(). # The lines in the output with trailing * highlight the inaccurate values. print '\n{:2} {:^12} {:^20} {:^20} {:8}'.format('i', 'x', 'accurate', 'inaccurate', 'mismatch') print '{:-^2} {:-^12} {:-^20} {:-^20} {:-^8}'.format('', '', '', '', '') for i in range(0, 10): x = math.pow(10, i) accurate = math.log10(x) inaccurate = math.log(x, 10) match = '' if int(inaccurate) == i else '*' print '{:2d} {:12.1f} {:20.18f} {:20.18f} {:^5}'.format(i, x, accurate, inaccurate, match) # log1p() calculates the Newton-Mercator series (the natural logarithm of 1+x). # log1p() is more accurate for values of x very close to zero because it uses an algorithm that compensates for round-off errors from the initial addition. print x = 0.0000000000000000000000001 print 'x :', x print '1 + x :', 1+x print 'log(1+x):', math.log(1+x) print 'log1p(x):', math.log1p(x) # exp() computes the exponential function (e**x). # As with other special-case functions, it uses an algorithm that produces more accurate results than the general-purpose equivalent math.pow(math.e, x). print x = 2 fmt = '%.20f' print fmt % (math.e ** 2) print fmt % math.pow(math.e, 2) print fmt % math.exp(2) # expm1() is the inverse of log1p(), and calculates e**x - 1. # As with log1p(), small values of x lose precision when the subtraction is performed separately. x = 0.0000000000000000000000001 print print x print math.exp(x) - 1 print math.expm1(x) # To convert from degrees to radians, use radians(). # The formula for the conversion is rad = deg * Pi / 180. print print '{:^7} {:^7} {:^7}'.format('Degrees', 'Radians', 'Expected') print '{:-^7} {:-^7} {:-^7}'.format('', '', '') for deg, expected in [ ( 0, 0), ( 30, math.pi/6), ( 45, math.pi/4), ( 60, math.pi/3), ( 90, math.pi/2), (180, math.pi), (270, 3/2.0 * math.pi), (360, 2 * math.pi), ]: print '{:7d} {:7.2f} {:7.2f}'.format(deg, math.radians(deg), expected) # To convert from radians to degrees, use degrees(). # The formula is deg = rad * 180 / Pi. print print '{:^8} {:^8} {:^8}'.format('Radians', 'Degrees', 'Expected') print '{:-^8} {:-^8} {:-^8}'.format('', '', '') for rad, expected in [ (0, 0), (math.pi/6, 30), (math.pi/4, 45), (math.pi/3, 60), (math.pi/2, 90), (math.pi, 180), (3 * math.pi / 2, 270), (2 * math.pi, 360), ]: print '{:8.2f} {:8.2f} {:8.2f}'.format(rad, math.degrees(rad), expected) # Trigonometric functions relate angles in a triangle to the lengths of its sides. # They show up in formulas with periodic properties such as harmonics, circular motion, or when dealing with angles. # Note All of the trigonometric functions in the standard library take angles expressed as radians. # The tangent can also be defined as the ratio of the sine of the angle to its cosine, # and since the cosine is 0 for Pi/2 and 3Pi/2 radians, the tangent is infinite. print print 'Degrees Radians Sine Cosine Tangent' print '------- ------- ------- -------- -------' fmt = ' '.join(['%7.2f'] * 5) for deg in range(0, 361, 30): rad = math.radians(deg) if deg in (90, 270): t = float('inf') else: t = math.tan(rad) print fmt % (deg, rad, math.sin(rad), math.cos(rad), t) # Given a point (x, y), the length of the hypotenuse for the triangle between the points [(0, 0), (x, 0), (x, y)] is (x**2 + y**2) ** 1/2, # and can be computed with hypot(). # Points on the circle always have hypotenuse == 1. print print '{:^7} {:^7} {:^10}'.format('X', 'Y', 'Hypotenuse') print '{:-^7} {:-^7} {:-^10}'.format('', '', '') for x, y in [ # simple points (1, 1), (-1, -1), (math.sqrt(2), math.sqrt(2)), (3, 4), # 3-4-5 triangle # on the circle (math.sqrt(2)/2, math.sqrt(2)/2), # pi/4 rads (0.5, math.sqrt(3)/2), # pi/3 rads ]: h = math.hypot(x, y) print '{:7.2f} {:7.2f} {:7.2f}'.format(x, y, h) # The same function can be used to find the distance between two points. # Use the difference in the x and y values to move one endpoint to the origin, and then pass the results to hypot(). print '\n{:^8} {:^8} {:^8} {:^8} {:^8}'.format('X1', 'Y1', 'X2', 'Y2', 'Distance') print '{:-^8} {:-^8} {:-^8} {:-^8} {:-^8}'.format('', '', '', '', '') for (x1, y1), (x2, y2) in [ ((5, 5), (6, 6)), ((-6, -6), (-5, -5)), ((0, 0), (3, 4)), # 3-4-5 triangle ((-1, -1), (2, 3)), # 3-4-5 triangle ]: x = x1 - x2 y = y1 - y2 h = math.hypot(x, y) print '{:8.2f} {:8.2f} {:8.2f} {:8.2f} {:8.2f}'.format(x1, y1, x2, y2, h) # math also defines inverse trigonometric functions. # 1.57 is roughly equal to Pi/2, or 90 degrees, the angle at which the sine is 1 and the cosine is 0. print for r in [ 0, 0.5, 1 ]: print 'arcsine(%.1f) = %5.2f' % (r, math.asin(r)) print 'arccosine(%.1f) = %5.2f' % (r, math.acos(r)) print 'arctangent(%.1f) = %5.2f' % (r, math.atan(r)) print # Hyperbolic functions appear in linear differential equations and are used when working with electromagnetic fields, fluid dynamics, special relativity, # and other advanced physics and mathematics. # Whereas the cosine and sine functions enscribe a circle, the hyperbolic cosine and hyperbolic sine form half of a hyperbola. # Inverse hyperbolic functions acosh(), asinh(), and atanh() are also available. print '\n{:^6} {:^6} {:^6} {:^6}'.format('X', 'sinh', 'cosh', 'tanh') print '{:-^6} {:-^6} {:-^6} {:-^6}'.format('', '', '', '') fmt = ' '.join(['{:6.4f}'] * 4) for i in range(0, 11, 2): x = i/10.0 print fmt.format(x, math.sinh(x), math.cosh(x), math.tanh(x)) # The Gauss Error function is used in statistics. # Notice that erf(-x) == -erf(x). print '\n{:^5} {:7}'.format('x', 'erf(x)') print '{:-^5} {:-^7}'.format('', '') for x in [ -3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3 ]: print '{:5.2f} {:7.4f}'.format(x, math.erf(x)) # The complimentary error function is 1 - erf(x). print print '{:^5} {:7}'.format('x', 'erfc(x)') print '{:-^5} {:-^7}'.format('', '') for x in [ -3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3 ]: print '{:5.2f} {:7.4f}'.format(x, math.erfc(x))

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example16.py =============== Pi: 3.141592653589793115997963468544 e: 2.718281828459045090795598298428 e x x**2 isinf --- ------ ------ ------ 0 1.0 1.0 False 20 1e+20 1e+40 False 40 1e+40 1e+80 False 60 1e+60 1e+120 False 80 1e+80 1e+160 False 100 1e+100 1e+200 False 120 1e+120 1e+240 False 140 1e+140 1e+280 False 160 1e+160 inf True 180 1e+180 inf True 200 1e+200 inf True x = 1e+200 x*x = inf x**2 = (34, 'Result too large') x = inf isnan(x) = False y = x / x = nan y == nan = False isnan(y) = True i int trunk floor ceil ----- ----- ----- ----- ----- -1.5 -1.0 -1.0 -2.0 -1.0 -0.8 0.0 0.0 -1.0 -0.0 -0.5 0.0 0.0 -1.0 -0.0 -0.2 0.0 0.0 -1.0 -0.0 0.0 0.0 0.0 0.0 0.0 0.2 0.0 0.0 0.0 1.0 0.5 0.0 0.0 0.0 1.0 0.8 0.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 0/2 = (0.0, 0.0) 1/2 = (0.5, 0.0) 2/2 = (0.0, 1.0) 3/2 = (0.5, 1.0) 4/2 = (0.0, 2.0) 5/2 = (0.5, 2.0) x m e ------- ------- ------- 0.10 0.80 -3 0.50 0.50 0 4.00 0.50 3 m e x ------- ------- ------- 0.80 -3 0.10 0.50 0 0.50 0.50 3 4.00 1.1 0.0 0.0 1.1 f s < 0 > 0 = 0 ----- ----- ----- ----- ----- -1.0 -1 True False False 0.0 1 False False True 1.0 1 False True False -inf -1 True False False inf 1 False True False nan 1 False False False nan -1 False False False Input values: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] sum() : 0.99999999999999988898 for-loop : 0.99999999999999988898 math.fsum() : 1.00000000000000000000 0 1 1 1 2 2 3 6 4 24 5 120 Error computing factorial(6.1): factorial() only accepts integral values Error computing gamma(0): math domain error 1.1 0.95 2.2 1.10 3.3 2.68 4.4 10.14 5.5 52.34 6.6 344.70 Error computing lgamma(0): math domain error 1.1 -0.04987244125984036103 -0.04987244125983997245 2.2 0.09694746679063825923 0.09694746679063866168 3.3 0.98709857789473387513 0.98709857789473409717 4.4 2.31610349142485727469 2.31610349142485727469 5.5 3.95781396761871651080 3.95781396761871606671 6.6 5.84268005527463252236 5.84268005527463252236 x y % fmod ---- ---- ----- ----- 5.0 2.0 1.00 1.00 5.0 -2.0 -1.00 1.00 -5.0 2.0 1.00 -1.00 2.0 ** 3.000 = 8.000 2.1 ** 3.200 = 10.742 1.0 ** 5.000 = 1.000 2.0 ** 0.000 = 1.000 2.0 ** nan = nan 9.0 ** 0.500 = 3.000 27.0 ** 0.333 = 3.000 3.0 1.73205080757 Cannot compute sqrt(-1): math domain error 2.07944154168 3.0 -1.0 i x accurate inaccurate mismatch -- ------------ -------------------- -------------------- -------- 0 1.0 0.000000000000000000 0.000000000000000000 1 10.0 1.000000000000000000 1.000000000000000000 2 100.0 2.000000000000000000 2.000000000000000000 3 1000.0 3.000000000000000000 2.999999999999999556 * 4 10000.0 4.000000000000000000 4.000000000000000000 5 100000.0 5.000000000000000000 5.000000000000000000 6 1000000.0 6.000000000000000000 5.999999999999999112 * 7 10000000.0 7.000000000000000000 7.000000000000000000 8 100000000.0 8.000000000000000000 8.000000000000000000 9 1000000000.0 9.000000000000000000 8.999999999999998224 * x : 1e-25 1 + x : 1.0 log(1+x): 0.0 log1p(x): 1e-25 7.38905609893064951876 7.38905609893064951876 7.38905609893065040694 1e-25 0.0 1e-25 Degrees Radians Expected ------- ------- ------- 0 0.00 0.00 30 0.52 0.52 45 0.79 0.79 60 1.05 1.05 90 1.57 1.57 180 3.14 3.14 270 4.71 4.71 360 6.28 6.28 Radians Degrees Expected -------- -------- -------- 0.00 0.00 0.00 0.52 30.00 30.00 0.79 45.00 45.00 1.05 60.00 60.00 1.57 90.00 90.00 3.14 180.00 180.00 4.71 270.00 270.00 6.28 360.00 360.00 Degrees Radians Sine Cosine Tangent ------- ------- ------- -------- ------- 0.00 0.00 0.00 1.00 0.00 30.00 0.52 0.50 0.87 0.58 60.00 1.05 0.87 0.50 1.73 90.00 1.57 1.00 0.00 inf 120.00 2.09 0.87 -0.50 -1.73 150.00 2.62 0.50 -0.87 -0.58 180.00 3.14 0.00 -1.00 -0.00 210.00 3.67 -0.50 -0.87 0.58 240.00 4.19 -0.87 -0.50 1.73 270.00 4.71 -1.00 -0.00 inf 300.00 5.24 -0.87 0.50 -1.73 330.00 5.76 -0.50 0.87 -0.58 360.00 6.28 -0.00 1.00 -0.00 X Y Hypotenuse ------- ------- ---------- 1.00 1.00 1.41 -1.00 -1.00 1.41 1.41 1.41 2.00 3.00 4.00 5.00 0.71 0.71 1.00 0.50 0.87 1.00 X1 Y1 X2 Y2 Distance -------- -------- -------- -------- -------- 5.00 5.00 6.00 6.00 1.41 -6.00 -6.00 -5.00 -5.00 1.41 0.00 0.00 3.00 4.00 5.00 -1.00 -1.00 2.00 3.00 5.00 arcsine(0.0) = 0.00 arccosine(0.0) = 1.57 arctangent(0.0) = 0.00 arcsine(0.5) = 0.52 arccosine(0.5) = 1.05 arctangent(0.5) = 0.46 arcsine(1.0) = 1.57 arccosine(1.0) = 0.00 arctangent(1.0) = 0.79 X sinh cosh tanh ------ ------ ------ ------ 0.0000 0.0000 1.0000 0.0000 0.2000 0.2013 1.0201 0.1974 0.4000 0.4108 1.0811 0.3799 0.6000 0.6367 1.1855 0.5370 0.8000 0.8881 1.3374 0.6640 1.0000 1.1752 1.5431 0.7616 x erf(x) ----- ------- -3.00 -1.0000 -2.00 -0.9953 -1.00 -0.8427 -0.50 -0.5205 -0.25 -0.2763 0.00 0.0000 0.25 0.2763 0.50 0.5205 1.00 0.8427 2.00 0.9953 3.00 1.0000 x erfc(x) ----- ------- -3.00 2.0000 -2.00 1.9953 -1.00 1.8427 -0.50 1.5205 -0.25 1.2763 0.00 1.0000 0.25 0.7237 0.50 0.4795 1.00 0.1573 2.00 0.0047 3.00 0.0000 >>>

Example 17

@example17.py

# random import random print random.choice(['Ashish', 'Ranjan', 'presentation']) print random.sample(xrange(100), 10) # sampling without replacement print random.random() # random float print random.randrange(6) # random integer chosen from range(6)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example17.py =============== Ashish [26, 79, 93, 77, 9, 65, 85, 82, 80, 88] 0.588481503994 3 >>>

Example 18

@example18.py

# permutation def perm(l): if len(l) <= 1: return [l] r = [] # here is new list with all permutations! for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) for x in p: r.append(l[i:i+1] + x) return r a = [1,2,3] print perm(a)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example18.py =============== [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] >>>

Example 19

@example18.py

# complex numbers complex1 = 2 + 3j complex2 = 2 - 3j print "complex1: ", complex1 print "complex2: ", complex2 print "complex1 * complex1 = ", complex1 * complex1 print "complex1 * complex2 = ", complex1 * complex2 print "complex1.real: ", complex1.real print "complex2.imag: ", complex2.imag

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example19.py =============== complex1: (2+3j) complex2: (2-3j) complex1 * complex1 = (-5+12j) complex1 * complex2 = (13+0j) complex1.real: 2.0 complex2.imag: -3.0 >>>

Example 20

@example20.py

# try except def divide(x, y): try: result = x / y except ZeroDivisionError: print "division by zero!" else: print "result is", result finally: print "executing finally clause" divide(2, 1) print divide(2, 0) print divide("2", "1")

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example20.py =============== result is 2 executing finally clause division by zero! executing finally clause executing finally clause Traceback (most recent call last): File "F:/Python Programs/set 1/example20.py", line 17, in <module> divide("2", "1") File "F:/Python Programs/set 1/example20.py", line 5, in divide result = x / y TypeError: unsupported operand type(s) for /: 'str' and 'str' >>>

Example 21

@example21.py

# lists a = ['Ashish', 'Ranjan', 100, 1234] print " list a=",a # list indices start at 0, print '\na[0]=', a[0] print 'a[3]=', a[3] print 'a[-2]=', a[-2] # lists can be sliced, concatenated and so on: print "\na[1:-1]=", a[1:-1] print a[:2] + ['an', 2*2] print 3*a[:3] + ['presentation!'] # possible to change individual elements of a list: a[2] = a[2] + 23 print "\nchanging a[2]=", a #Assignment to slices is also possible, and this can even change the size of the list: # Replace some items: a[0:2] = [1, 12] print "\n", a # Remove some: a[0:2] = [] print "\n", a # Insert some: a[1:1] = ['WHAT ???', 'xyzzy'] print "\n", a a[:0] = a # Insert (a copy of) itself at the beginning print "\n", a print "length=", len(a) # possible to nest lists (create lists containing other lists) q = [2, 3] p = [1, q, 4] print "\n nest list=", p print 'length =', len(p) print p[1] print p[1][0] print p[1].append('xtra') print p print q a1 = [66.6, 333, 333, 1, 1234.5] print "\na1: ", a1 print "a1.count(333): ",a1.count(333), "a1.count(66.6): ", a1.count(66.6), "a1.count('x'): ", a1.count('x') a1.insert(2, -1) print "After a1.insert(2, -1), a1: ", a1 a1.append(333) print "After a1.append(333), a1: ", a1 print "a1.index(333): ", a1.index(333) a1.remove(333) print "After a1.remove(333): ", a1 a1.reverse() print "After a1.reverse(): ", a1 a1.sort() print "After a1.sort(), a1: ", a1

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example21.py =============== list a= ['Ashish', 'Ranjan', 100, 1234] a[0]= Ashish a[3]= 1234 a[-2]= 100 a[1:-1]= ['Ranjan', 100] ['Ashish', 'Ranjan', 'an', 4] ['Ashish', 'Ranjan', 100, 'Ashish', 'Ranjan', 100, 'Ashish', 'Ranjan', 100, 'presentation!'] changing a[2]= ['Ashish', 'Ranjan', 123, 1234] [1, 12, 123, 1234] [123, 1234] [123, 'WHAT ???', 'xyzzy', 1234] [123, 'WHAT ???', 'xyzzy', 1234, 123, 'WHAT ???', 'xyzzy', 1234] length= 8 nest list= [1, [2, 3], 4] length = 3 [2, 3] 2 [1, [2, 3, 'xtra'], 4] [2, 3, 'xtra'] a1: [66.6, 333, 333, 1, 1234.5] a1.count(333): 2 a1.count(66.6): 1 a1.count('x'): 0 After a1.insert(2, -1), a1: [66.6, 333, -1, 333, 1, 1234.5] After a1.append(333), a1: [66.6, 333, -1, 333, 1, 1234.5, 333] a1.index(333): 1 After a1.remove(333): [66.6, -1, 333, 1, 1234.5, 333] After a1.reverse(): [333, 1234.5, 1, 333, -1, 66.6] After a1.sort(), a1: [-1, 1, 66.6, 333, 333, 1234.5] >>>

Example 22

example22.py

# Lists as Stacks stack = [3, 4, 5] stack.append(6) stack.append(7) print stack x=stack.pop() print "popped ",x print stack x=stack.pop() print "popped ",x x=stack.pop() print "popped ",x print stack # Lists as Queues queue = ["Ashish", "Ranjan", "presentation"] queue.append("Rajiv") # Rajiv arrives queue.append("Suraj") # Suraj arrives print queue s=queue.pop(0) print s s=queue.pop(0) print s print queue

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example22.py =============== [3, 4, 5, 6, 7] popped 7 [3, 4, 5, 6] popped 6 popped 5 [3, 4] ['Ashish', 'Ranjan', 'presentation', 'Rajiv', 'Suraj'] Ashish Ranjan ['presentation', 'Rajiv', 'Suraj'] >>>

@example23.py

# del statement a = [-1, 1, 66.6, 333, 333, 1234.5] del a[0] print a del a[2:4] print a

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example23.py =============== [1, 66.6, 333, 333, 1234.5] [1, 66.6, 1234.5] >>>

Example 24

@example24.py

# Sequence #filter def f(x): return x % 2 != 0 and x % 3 != 0 res = filter(f, range(2, 25)) print res # map def cube(x): return x*x*x res = map(cube, range(1, 11)) print res # reduce(func, sequence)" returns a single value constructed by # calling the binary function func on the first two items of the sequence, # then on the result and the next item, and so on def add(x,y): return x+y r = reduce(add, range(1, 11)) print r

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example24.py =============== [5, 7, 11, 13, 17, 19, 23] [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 55 >>>

Example 25

@example25.py

# A tuple consists of a number of values separated by commas t = 12345, 54321, 'hello!' # tuple packing print t[0] print t # Tuples may be nested: u = t, (1, 2, 3, 4, 5) print u

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example25.py =============== 12345 (12345, 54321, 'hello!') ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>>

Example 26

@example26.py

# Dictionaries / associative memories' / associative arrays tel = {'ashish': 4098, 'ranjan': 4139} tel['presentation'] = 4127 print tel print tel['ashish'] del tel['ranjan'] tel['an'] = 4127 print tel print tel.keys() x=tel.has_key('ranjan') print x # The dict() constructor builds dictionaries directly from lists # of key-value pairs stored as tuples. When the pairs form a pattern, # list comprehensions can compactly specify the key-value list. d=dict([('ashish', 4139), ('ranjan', 4127), ('presentation', 4098)]) print d vec=[1,2,3,4,5] dd=dict([(x, x**2) for x in vec]) # use a list comprehension print dd

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example26.py =============== {'ranjan': 4139, 'presentation': 4127, 'ashish': 4098} 4098 {'presentation': 4127, 'ashish': 4098, 'an': 4127} ['presentation', 'ashish', 'an'] False {'ranjan': 4127, 'presentation': 4098, 'ashish': 4139} {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} >>>

Example 27

@example27.py

# sys module # A module allows us to logically organize our Python code. # Grouping related code into a module makes the code easier to understand and use. # A module is a Python object with arbitrarily named attributes that we can bind and reference. # A module is a file consisting of Python code. # A module can define functions, classes and variables. # A module can also include runnable code. # dir(system) gives a summary of the available constants, functions and methods. # Using help(sys) provides valuable detail information. import sys print "dir(sys):\n", dir(sys) print print "The current version number of Python: " print "sys.version: ", sys.version print "sys.version_info: ", sys.version_info print "sys.platform: ", sys.platform print "sys.maxint: ", sys.maxint # sys.argv is a list which contains the command-line arguments passed to the script. print print "sys.argv: ", sys.argv # it can be iterated via a for loop: # @cmd python example27.py arg1 arg2 # Output: sys.argv: ['example27.py', 'arg1', 'arg2'] # Function name: example27.py # 1. argument: arg1 # 2. argument: arg2 for i in range(len(sys.argv)): if i == 0: print "Function name: %s" % sys.argv[0] else: print "%d. argument: %s" % (i,sys.argv[i])

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example27.py =============== dir(sys): ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver'] The current version number of Python: sys.version: 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] sys.version_info: sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0) sys.platform: win32 sys.maxint: 2147483647 sys.argv: ['F:\\Python Programs\\set 1\\example27.py'] Function name: F:\Python Programs\set 1\example27.py >>>

Example 28

@example28.py

# convert any value to a string: with repr() or str() s = 'an Ashish Ranjan presentation' print "str(s): ", str(s) print "repr(s): ", repr(s) print "str(0.1): ", str(0.1) print "repr(0.1): ", repr(0.1) x = 10 * 3.25 y = 200 * 200 s = '\nThe value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' print s # The repr() of a string adds string quotes and backslashes: hello = 'hello, world\n' hellos = repr(hello) print "\nhellos: ", hellos # The argument to repr() may be any Python object: print "repr((x, y, ('spam', 'eggs'))): ", repr((x, y, ('spam', 'eggs'))) # reverse quotes are convenient in interactive sessions: print x, y, ('spam', 'eggs')

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example28.py =============== str(s): an Ashish Ranjan presentation repr(s): 'an Ashish Ranjan presentation' str(0.1): 0.1 repr(0.1): 0.1 The value of x is 32.5, and y is 40000... hellos: 'hello, world\n' repr((x, y, ('spam', 'eggs'))): (32.5, 40000, ('spam', 'eggs')) 32.5 40000 ('spam', 'eggs') >>>

Example 28

@example28.py

# two ways to write a table of squares and cubes: for x in range(1, 11): print repr(x).rjust(2), repr(x*x).rjust(3), # Note trailing comma on previous line print repr(x*x*x).rjust(4) print '=================================================' for x in range(1,11): print '%2d %3d %4d' % (x, x*x, x*x*x)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example29.py =============== 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 ================================================= 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 >>>

Example 30

@example30.py

# regular expression # complete list of the metacharacters # . ^ $ * + ? { } [ ] \ | ( ) # \d: Matches any decimal digit; this is equivalent to the class [0-9]. # \D: Matches any non-digit character; this is equivalent to the class [^0-9]. # \s: Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v]. # \S: Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v]. # \w: Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_]. # \W: Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_]. # These sequences can be included inside a character class. # For example, [\s,.] is a character class that will match any whitespace character, or ',' or '.'. # ..: It matches anything except a newline character, and there's an alternate mode (re.DOTALL) where it will match even a newline. # '.' is often used where you want to match "any character". import re r = re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') print r s = re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') print s print # The match Function: re.match(pattern, string, flags=0) # This function attempts to match RE pattern to string with optional flags. line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: print "No match!!" print # The search Function: re.search(pattern, string, flags=0) # This function searches for first occurrence of RE pattern within string with optional flags. line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!" print # match checks for a match only at the beginning of the string, # while search checks for a match anywhere in the string (this is what Perl does by default). line = "Cats are smarter than dogs"; matchObj = re.match( r'dogs', line, re.M|re.I) if matchObj: print "match --> matchObj.group() : ", matchObj.group() else: print "No match!!" searchObj = re.search( r'dogs', line, re.M|re.I) if searchObj: print "search --> searchObj.group() : ", searchObj.group() else: print "Nothing found!!" print # Search and Replace # re.sub(pattern, repl, string, max=0) # This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. # This method returns modified string. phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'\D', "", phone) print "Phone Num : ", num

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example30.py =============== ['foot', 'fell', 'fastest'] cat in the hat matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter searchObj.group() : Cats are smarter than dogs searchObj.group(1) : Cats searchObj.group(2) : smarter No match!! search --> searchObj.group() : dogs Phone Num : 2004-959-559 Phone Num : 2004959559 >>>

Example 31

@example31.py

# dates from datetime import date now = date.today() print now print now.strftime("%m-%d-%y or %d %b %Y is a %A on the %d day of %B") # dates support calendar arithmetic def calculate_age(born): today = date.today() # date.today() returns the date in the local timezone that may be different from the place of birth. return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) print "Calculated age is: ", calculate_age(date(1986, 8, 15))

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example31.py =============== 2016-04-25 04-25-16 or 25 Apr 2016 is a Monday on the 25 day of April Calculated age is: 29 >>>

Example 32

@example32.py

# open file for write f1 = open('test11.txt','w') print f1 f1.write("aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz\n") f1.write("abcdefghijklmnopqrstuvwxyz0123456789"); f1.close() #open file for read f2 = open('test11.txt','r') # line reading s = f2.readline() print "It's contents: ", s f2.close() print f3 = open('test11.txt','r') # pieces reading s1 = f3.read(5) print s1 print f3.tell() s2 = f3.read(19) print s2 print f3.tell() s2 = f3.read(25) print s2 print f3.tell() f3.close() f4 = open('test44.txt','r+') f4.write('0123456789abcdef') f4.seek(5) # Go to the 6th byte in the file print f4.read(1) f4.seek(-3, 2) # Go to the 3rd byte before the end print f4.read(1)

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:\Python Programs\set 1\example32.py =============== <open file 'test11.txt', mode 'w' at 0x01F9FA18> It's contents: aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz aabbc 5 cddeeffgghhiijjkkll 24 mmnnooppqqrrssttuuvvwwxxy 49 5 d >>>

Example 33

@example33.py

# glob - Filename pattern matching # Even though the glob API is very simple, the module packs a lot of power. # It is useful in any situation where your program needs to look for a list of files on the filesystem with names matching a pattern. # If you need a list of filenames that all have a certain extension, prefix, or any common string in the middle, # use glob instead of writing code to scan the directory contents yourself. # The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. # There are only a few special characters: two different wild-cards, and character ranges are supported. # The patterns rules are applied to segments of the filename (stopping at the path separator, /). # Paths in the pattern can be relative or absolute. Shell variable names and tilde (~) are not expanded. import glob for fileName in glob.glob('dir/*'): # files inside folder 'dir' print fileName print currDIR = glob.glob('*.*') # files in current directory print currDIR

@cmd

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART: F:/Python Programs/set 1/example33.py =============== dir\pytohn1.py dir\test.py dir\test11.txt dir\test22.txt dir\test33.txt dir\test44.txt dir\test55.txt ['example10.py', 'example11.py', 'example12.py', 'example13.py', 'example14.py', 'example15.py', 'example16.py', 'example17.py', 'example18.py', 'example19.py', 'example2.py', 'example20.py', 'example21.py', 'example22.py', 'example23.py', 'example24.py', 'example25.py', 'example26.py', 'example27.py', 'example28.py', 'example29.py', 'example3.py', 'example30.py', 'example31.py', 'example32.py', 'example33.py', 'example4.py', 'example5.py', 'example6.py', 'example7.py', 'example8.py', 'example9.py', 'python.html', 'pytohn1.py', 'test.py', 'test11.txt', 'test22.txt', 'test33.txt', 'test44.txt', 'test55.txt'] >>>