浏览代码

Add programs folder

Swaroop C H 9 年之前
父节点
当前提交
ed99d1bae9
共有 91 个文件被更改,包括 1120 次插入0 次删除
  1. 1 0
      programs/abc.txt
  2. 41 0
      programs/backup_ver1.py
  3. 9 0
      programs/backup_ver1.txt
  4. 51 0
      programs/backup_ver2.py
  5. 10 0
      programs/backup_ver2.txt
  6. 58 0
      programs/backup_ver3.py
  7. 5 0
      programs/backup_ver3.txt
  8. 58 0
      programs/backup_ver4.py
  9. 10 0
      programs/backup_ver4.txt
  10. 6 0
      programs/break.py
  11. 11 0
      programs/break.txt
  12. 9 0
      programs/continue.py
  13. 8 0
      programs/continue.txt
  14. 23 0
      programs/ds_reference.py
  15. 7 0
      programs/ds_reference.txt
  16. 23 0
      programs/ds_seq.py
  17. 16 0
      programs/ds_seq.txt
  18. 15 0
      programs/ds_str_methods.py
  19. 5 0
      programs/ds_str_methods.txt
  20. 24 0
      programs/ds_using_dict.py
  21. 10 0
      programs/ds_using_dict.txt
  22. 22 0
      programs/ds_using_list.py
  23. 10 0
      programs/ds_using_list.txt
  24. 14 0
      programs/ds_using_tuple.py
  25. 7 0
      programs/ds_using_tuple.txt
  26. 24 0
      programs/exceptions_finally.py
  27. 5 0
      programs/exceptions_finally.txt
  28. 8 0
      programs/exceptions_handle.py
  29. 11 0
      programs/exceptions_handle.txt
  30. 20 0
      programs/exceptions_raise.py
  31. 7 0
      programs/exceptions_raise.txt
  32. 3 0
      programs/exceptions_using_with.py
  33. 4 0
      programs/for.py
  34. 6 0
      programs/for.txt
  35. 7 0
      programs/function1.py
  36. 3 0
      programs/function1.txt
  37. 5 0
      programs/function_default.py
  38. 3 0
      programs/function_default.txt
  39. 15 0
      programs/function_docstring.py
  40. 5 0
      programs/function_docstring.txt
  41. 13 0
      programs/function_global.py
  42. 4 0
      programs/function_global.txt
  43. 6 0
      programs/function_keyword.py
  44. 4 0
      programs/function_keyword.txt
  45. 11 0
      programs/function_local.py
  46. 4 0
      programs/function_local.txt
  47. 16 0
      programs/function_param.py
  48. 3 0
      programs/function_param.txt
  49. 9 0
      programs/function_return.py
  50. 2 0
      programs/function_return.txt
  51. 9 0
      programs/function_varargs.py
  52. 2 0
      programs/function_varargs.txt
  53. 19 0
      programs/if.py
  54. 15 0
      programs/if.txt
  55. 13 0
      programs/io_input.py
  56. 11 0
      programs/io_input.txt
  57. 21 0
      programs/io_pickle.py
  58. 2 0
      programs/io_pickle.txt
  59. 9 0
      programs/io_unicode.py
  60. 28 0
      programs/io_using_file.py
  61. 5 0
      programs/io_using_file.txt
  62. 4 0
      programs/module_using_name.py
  63. 7 0
      programs/module_using_name.txt
  64. 7 0
      programs/module_using_sys.py
  65. 12 0
      programs/module_using_sys.txt
  66. 43 0
      programs/more_decorator.py
  67. 12 0
      programs/more_decorator.txt
  68. 4 0
      programs/more_lambda.py
  69. 2 0
      programs/more_lambda.txt
  70. 3 0
      programs/more_list_comprehension.py
  71. 2 0
      programs/more_list_comprehension.txt
  72. 4 0
      programs/mymodule.py
  73. 4 0
      programs/mymodule_demo.py
  74. 3 0
      programs/mymodule_demo.txt
  75. 4 0
      programs/mymodule_demo2.py
  76. 11 0
      programs/oop_init.py
  77. 2 0
      programs/oop_init.txt
  78. 8 0
      programs/oop_method.py
  79. 2 0
      programs/oop_method.txt
  80. 54 0
      programs/oop_objvar.py
  81. 16 0
      programs/oop_objvar.txt
  82. 5 0
      programs/oop_simplestclass.py
  83. 2 0
      programs/oop_simplestclass.txt
  84. 45 0
      programs/oop_subclass.py
  85. 8 0
      programs/oop_subclass.txt
  86. 4 0
      programs/poem.txt
  87. 8 0
      programs/shoplist.data
  88. 24 0
      programs/stdlib_logging.py
  89. 7 0
      programs/stdlib_logging.txt
  90. 19 0
      programs/while.py
  91. 9 0
      programs/while.txt

+ 1 - 0
programs/abc.txt

@@ -0,0 +1 @@
+Imagine non-English language here

+ 41 - 0
programs/backup_ver1.py

@@ -0,0 +1,41 @@
+import os
+import time
+
+# 1. The files and directories to be backed up are
+# specified in a list.
+# Example on Windows:
+# source = ['"C:\\My Documents"', 'C:\\Code']
+# Example on Mac OS X and Linux:
+source = ['/Users/swa/notes']
+# Notice we had to use double quotes inside the string
+# for names with spaces in it.
+
+# 2. The backup must be stored in a
+# main backup directory
+# Example on Windows:
+# target_dir = 'E:\\Backup'
+# Example on Mac OS X and Linux:
+target_dir = '/Users/swa/backup'
+# Remember to change this to which folder you will be using
+
+# 3. The files are backed up into a zip file.
+# 4. The name of the zip archive is the current date and time
+target = target_dir + os.sep + \
+         time.strftime('%Y%m%d%H%M%S') + '.zip'
+
+# Create target directory if it is not present
+if not os.path.exists(target_dir):
+    os.mkdir(target_dir)  # make directory
+
+# 5. We use the zip command to put the files in a zip archive
+zip_command = "zip -r {0} {1}".format(target,
+                                      ' '.join(source))
+
+# Run the backup
+print("Zip command is:")
+print(zip_command)
+print("Running:")
+if os.system(zip_command) == 0:
+    print('Successful backup to', target)
+else:
+    print('Backup FAILED')

+ 9 - 0
programs/backup_ver1.txt

@@ -0,0 +1,9 @@
+$ python backup_ver1.py
+Zip command is:
+zip -r /Users/swa/backup/20140328084844.zip /Users/swa/notes
+Running:
+  adding: Users/swa/notes/ (stored 0%)
+  adding: Users/swa/notes/blah1.txt (stored 0%)
+  adding: Users/swa/notes/blah2.txt (stored 0%)
+  adding: Users/swa/notes/blah3.txt (stored 0%)
+Successful backup to /Users/swa/backup/20140328084844.zip

+ 51 - 0
programs/backup_ver2.py

@@ -0,0 +1,51 @@
+import os
+import time
+
+# 1. The files and directories to be backed up are
+# specified in a list.
+# Example on Windows:
+# source = ['"C:\\My Documents"', 'C:\\Code']
+# Example on Mac OS X and Linux:
+source = ['/Users/swa/notes']
+# Notice we had to use double quotes inside the string
+# for names with spaces in it.
+
+# 2. The backup must be stored in a
+# main backup directory
+# Example on Windows:
+# target_dir = 'E:\\Backup'
+# Example on Mac OS X and Linux:
+target_dir = '/Users/swa/backup'
+# Remember to change this to which folder you will be using
+
+# Create target directory if it is not present
+if not os.path.exists(target_dir):
+    os.mkdir(target_dir)  # make directory
+
+# 3. The files are backed up into a zip file.
+# 4. The current day is the name of the subdirectory
+# in the main directory.
+today = target_dir + os.sep + time.strftime('%Y%m%d')
+# The current time is the name of the zip archive.
+now = time.strftime('%H%M%S')
+
+# The name of the zip file
+target = today + os.sep + now + '.zip'
+
+# Create the subdirectory if it isn't already there
+if not os.path.exists(today):
+    os.mkdir(today)
+    print('Successfully created directory', today)
+
+# 5. We use the zip command to put the files in a zip archive
+zip_command = "zip -r {0} {1}".format(target,
+                                      ' '.join(source))
+
+# Run the backup
+print("Zip command is:")
+print(zip_command)
+print("Running:")
+if os.system(zip_command) == 0:
+    print('Successful backup to', target)
+else:
+    print('Backup FAILED')

+ 10 - 0
programs/backup_ver2.txt

@@ -0,0 +1,10 @@
+$ python backup_ver2.py
+Successfully created directory /Users/swa/backup/20140329
+Zip command is:
+zip -r /Users/swa/backup/20140329/073201.zip /Users/swa/notes
+Running:
+  adding: Users/swa/notes/ (stored 0%)
+  adding: Users/swa/notes/blah1.txt (stored 0%)
+  adding: Users/swa/notes/blah2.txt (stored 0%)
+  adding: Users/swa/notes/blah3.txt (stored 0%)
+Successful backup to /Users/swa/backup/20140329/073201.zip

+ 58 - 0
programs/backup_ver3.py

@@ -0,0 +1,58 @@
+import os
+import time
+
+# 1. The files and directories to be backed up are
+# specified in a list.
+# Example on Windows:
+# source = ['"C:\\My Documents"', 'C:\\Code']
+# Example on Mac OS X and Linux:
+source = ['/Users/swa/notes']
+# Notice we had to use double quotes inside the string
+# for names with spaces in it.
+
+# 2. The backup must be stored in a
+# main backup directory
+# Example on Windows:
+# target_dir = 'E:\\Backup'
+# Example on Mac OS X and Linux:
+target_dir = '/Users/swa/backup'
+# Remember to change this to which folder you will be using
+
+# Create target directory if it is not present
+if not os.path.exists(target_dir):
+    os.mkdir(target_dir)  # make directory
+
+# 3. The files are backed up into a zip file.
+# 4. The current day is the name of the subdirectory
+# in the main directory.
+today = target_dir + os.sep + time.strftime('%Y%m%d')
+# The current time is the name of the zip archive.
+now = time.strftime('%H%M%S')
+
+# Take a comment from the user to
+# create the name of the zip file
+comment = input('Enter a comment --> ')
+# Check if a comment was entered
+if len(comment) == 0:
+    target = today + os.sep + now + '.zip'
+else:
+    target = today + os.sep + now + '_' + \
+        comment.replace(' ', '_') + '.zip'
+
+# Create the subdirectory if it isn't already there
+if not os.path.exists(today):
+    os.mkdir(today)
+    print('Successfully created directory', today)
+
+# 5. We use the zip command to put the files in a zip archive
+zip_command = "zip -r {0} {1}".format(target,
+                                      ' '.join(source))
+
+# Run the backup
+print("Zip command is:")
+print(zip_command)
+print("Running:")
+if os.system(zip_command) == 0:
+    print('Successful backup to', target)
+else:
+    print('Backup FAILED')

+ 5 - 0
programs/backup_ver3.txt

@@ -0,0 +1,5 @@
+$ python backup_ver3.py
+  File "backup_ver3.py", line 39
+    target = today + os.sep + now + '_' +
+                                        ^
+SyntaxError: invalid syntax

+ 58 - 0
programs/backup_ver4.py

@@ -0,0 +1,58 @@
+import os
+import time
+
+# 1. The files and directories to be backed up are
+# specified in a list.
+# Example on Windows:
+# source = ['"C:\\My Documents"', 'C:\\Code']
+# Example on Mac OS X and Linux:
+source = ['/Users/swa/notes']
+# Notice we had to use double quotes inside the string
+# for names with spaces in it.
+
+# 2. The backup must be stored in a
+# main backup directory
+# Example on Windows:
+# target_dir = 'E:\\Backup'
+# Example on Mac OS X and Linux:
+target_dir = '/Users/swa/backup'
+# Remember to change this to which folder you will be using
+
+# Create target directory if it is not present
+if not os.path.exists(target_dir):
+    os.mkdir(target_dir)  # make directory
+
+# 3. The files are backed up into a zip file.
+# 4. The current day is the name of the subdirectory
+# in the main directory.
+today = target_dir + os.sep + time.strftime('%Y%m%d')
+# The current time is the name of the zip archive.
+now = time.strftime('%H%M%S')
+
+# Take a comment from the user to
+# create the name of the zip file
+comment = input('Enter a comment --> ')
+# Check if a comment was entered
+if len(comment) == 0:
+    target = today + os.sep + now + '.zip'
+else:
+    target = today + os.sep + now + '_' + \
+        comment.replace(' ', '_') + '.zip'
+
+# Create the subdirectory if it isn't already there
+if not os.path.exists(today):
+    os.mkdir(today)
+    print('Successfully created directory', today)
+
+# 5. We use the zip command to put the files in a zip archive
+zip_command = "zip -r {0} {1}".format(target,
+                                      ' '.join(source))
+
+# Run the backup
+print("Zip command is:")
+print(zip_command)
+print("Running:")
+if os.system(zip_command) == 0:
+    print('Successful backup to', target)
+else:
+    print('Backup FAILED')

+ 10 - 0
programs/backup_ver4.txt

@@ -0,0 +1,10 @@
+$ python backup_ver4.py
+Enter a comment --> added new examples
+Zip command is:
+zip -r /Users/swa/backup/20140329/074122_added_new_examples.zip /Users/swa/notes
+Running:
+  adding: Users/swa/notes/ (stored 0%)
+  adding: Users/swa/notes/blah1.txt (stored 0%)
+  adding: Users/swa/notes/blah2.txt (stored 0%)
+  adding: Users/swa/notes/blah3.txt (stored 0%)
+Successful backup to /Users/swa/backup/20140329/074122_added_new_examples.zip

+ 6 - 0
programs/break.py

@@ -0,0 +1,6 @@
+while True:
+    s = input('Enter something : ')
+    if s == 'quit':
+        break
+    print('Length of the string is', len(s))
+print('Done')

+ 11 - 0
programs/break.txt

@@ -0,0 +1,11 @@
+$ python break.py
+Enter something : Programming is fun
+Length of the string is 18
+Enter something : When the work is done
+Length of the string is 21
+Enter something : if you wanna make your work also fun:
+Length of the string is 37
+Enter something : use Python!
+Length of the string is 11
+Enter something : quit
+Done

+ 9 - 0
programs/continue.py

@@ -0,0 +1,9 @@
+while True:
+    s = raw_input('Enter something : ')
+    if s == 'quit':
+        break
+    if len(s) < 3:
+        print 'Too small'
+        continue
+    print 'Input is of sufficient length'
+    # Do other kinds of processing here...

+ 8 - 0
programs/continue.txt

@@ -0,0 +1,8 @@
+$ python continue.py
+Enter something : a
+Too small
+Enter something : 12
+Too small
+Enter something : abc
+Input is of sufficient length
+Enter something : quit

+ 23 - 0
programs/ds_reference.py

@@ -0,0 +1,23 @@
+print('Simple Assignment')
+shoplist = ['apple', 'mango', 'carrot', 'banana']
+# mylist is just another name pointing to the same object!
+mylist = shoplist
+
+# I purchased the first item, so I remove it from the list
+del shoplist[0]
+
+print('shoplist is', shoplist)
+print('mylist is', mylist)
+# Notice that both shoplist and mylist both print
+# the same list without the 'apple' confirming that
+# they point to the same object
+
+print('Copy by making a full slice')
+# Make a copy by doing a full slice
+mylist = shoplist[:]
+# Remove first item
+del mylist[0]
+
+print('shoplist is', shoplist)
+print('mylist is', mylist)
+# Notice that now the two lists are different

+ 7 - 0
programs/ds_reference.txt

@@ -0,0 +1,7 @@
+$ python ds_reference.py
+Simple Assignment
+shoplist is ['mango', 'carrot', 'banana']
+mylist is ['mango', 'carrot', 'banana']
+Copy by making a full slice
+shoplist is ['mango', 'carrot', 'banana']
+mylist is ['carrot', 'banana']

+ 23 - 0
programs/ds_seq.py

@@ -0,0 +1,23 @@
+shoplist = ['apple', 'mango', 'carrot', 'banana']
+name = 'swaroop'
+
+# Indexing or 'Subscription' operation #
+print('Item 0 is', shoplist[0])
+print('Item 1 is', shoplist[1])
+print('Item 2 is', shoplist[2])
+print('Item 3 is', shoplist[3])
+print('Item -1 is', shoplist[-1])
+print('Item -2 is', shoplist[-2])
+print('Character 0 is', name[0])
+
+# Slicing on a list #
+print('Item 1 to 3 is', shoplist[1:3])
+print('Item 2 to end is', shoplist[2:])
+print('Item 1 to -1 is', shoplist[1:-1])
+print('Item start to end is', shoplist[:])
+
+# Slicing on a string #
+print('characters 1 to 3 is', name[1:3])
+print('characters 2 to end is', name[2:])
+print('characters 1 to -1 is', name[1:-1])
+print('characters start to end is', name[:])

+ 16 - 0
programs/ds_seq.txt

@@ -0,0 +1,16 @@
+$ python ds_seq.py
+Item 0 is apple
+Item 1 is mango
+Item 2 is carrot
+Item 3 is banana
+Item -1 is banana
+Item -2 is carrot
+Character 0 is s
+Item 1 to 3 is ['mango', 'carrot']
+Item 2 to end is ['carrot', 'banana']
+Item 1 to -1 is ['mango', 'carrot']
+Item start to end is ['apple', 'mango', 'carrot', 'banana']
+characters 1 to 3 is wa
+characters 2 to end is aroop
+characters 1 to -1 is waroo
+characters start to end is swaroop

+ 15 - 0
programs/ds_str_methods.py

@@ -0,0 +1,15 @@
+# This is a string object
+name = 'Swaroop'
+
+if name.startswith('Swa'):
+    print('Yes, the string starts with "Swa"')
+
+if 'a' in name:
+    print('Yes, it contains the string "a"')
+
+if name.find('war') != -1:
+    print('Yes, it contains the string "war"')
+
+delimiter = '_*_'
+mylist = ['Brazil', 'Russia', 'India', 'China']
+print(delimiter.join(mylist))

+ 5 - 0
programs/ds_str_methods.txt

@@ -0,0 +1,5 @@
+$ python ds_str_methods.py
+Yes, the string starts with "Swa"
+Yes, it contains the string "a"
+Yes, it contains the string "war"
+Brazil_*_Russia_*_India_*_China

+ 24 - 0
programs/ds_using_dict.py

@@ -0,0 +1,24 @@
+# 'ab' is short for 'a'ddress'b'ook
+
+ab = {
+    'Swaroop': 'swaroop@swaroopch.com',
+    'Larry': 'larry@wall.org',
+    'Matsumoto': 'matz@ruby-lang.org',
+    'Spammer': 'spammer@hotmail.com'
+}
+
+print("Swaroop's address is", ab['Swaroop'])
+
+# Deleting a key-value pair
+del ab['Spammer']
+
+print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
+
+for name, address in ab.items():
+    print('Contact {} at {}'.format(name, address))
+
+# Adding a key-value pair
+ab['Guido'] = 'guido@python.org'
+
+if 'Guido' in ab:
+    print("\nGuido's address is", ab['Guido'])

+ 10 - 0
programs/ds_using_dict.txt

@@ -0,0 +1,10 @@
+$ python ds_using_dict.py
+Swaroop's address is swaroop@swaroopch.com
+
+There are 3 contacts in the address-book
+
+Contact Swaroop at swaroop@swaroopch.com
+Contact Matsumoto at matz@ruby-lang.org
+Contact Larry at larry@wall.org
+
+Guido's address is guido@python.org

+ 22 - 0
programs/ds_using_list.py

@@ -0,0 +1,22 @@
+# This is my shopping list
+shoplist = ['apple', 'mango', 'carrot', 'banana']
+
+print('I have', len(shoplist), 'items to purchase.')
+
+print('These items are:', end=' ')
+for item in shoplist:
+    print(item, end=' ')
+
+print('\nI also have to buy rice.')
+shoplist.append('rice')
+print('My shopping list is now', shoplist)
+
+print('I will sort my list now')
+shoplist.sort()
+print('Sorted shopping list is', shoplist)
+
+print('The first item I will buy is', shoplist[0])
+olditem = shoplist[0]
+del shoplist[0]
+print('I bought the', olditem)
+print('My shopping list is now', shoplist)

+ 10 - 0
programs/ds_using_list.txt

@@ -0,0 +1,10 @@
+$ python ds_using_list.py
+I have 4 items to purchase.
+These items are: apple mango carrot banana
+I also have to buy rice.
+My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
+I will sort my list now
+Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
+The first item I will buy is apple
+I bought the apple
+My shopping list is now ['banana', 'carrot', 'mango', 'rice']

+ 14 - 0
programs/ds_using_tuple.py

@@ -0,0 +1,14 @@
+# I would recommend always using parentheses
+# to indicate start and end of tuple
+# even though parentheses are optional.
+# Explicit is better than implicit.
+zoo = ('python', 'elephant', 'penguin')
+print('Number of animals in the zoo is', len(zoo))
+
+new_zoo = 'monkey', 'camel', zoo
+print('Number of cages in the new zoo is', len(new_zoo))
+print('All animals in new zoo are', new_zoo)
+print('Animals brought from old zoo are', new_zoo[2])
+print('Last animal brought from old zoo is', new_zoo[2][2])
+print('Number of animals in the new zoo is',
+      len(new_zoo)-1+len(new_zoo[2]))

+ 7 - 0
programs/ds_using_tuple.txt

@@ -0,0 +1,7 @@
+$ python ds_using_tuple.py
+Number of animals in the zoo is 3
+Number of cages in the new zoo is 3
+All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
+Animals brought from old zoo are ('python', 'elephant', 'penguin')
+Last animal brought from old zoo is penguin
+Number of animals in the new zoo is 5

+ 24 - 0
programs/exceptions_finally.py

@@ -0,0 +1,24 @@
+import sys
+import time
+
+f = None
+try:
+    f = open("poem.txt")
+    # Our usual file-reading idiom
+    while True:
+        line = f.readline()
+        if len(line) == 0:
+            break
+        print(line, end='')
+        sys.stdout.flush()
+        print("Press ctrl+c now")
+        # To make sure it runs for a while
+        time.sleep(2)
+except IOError:
+    print("Could not find file poem.txt")
+except KeyboardInterrupt:
+    print("!! You cancelled the reading from the file.")
+finally:
+    if f:
+        f.close()
+    print("(Cleaning up: Closed the file)")

+ 5 - 0
programs/exceptions_finally.txt

@@ -0,0 +1,5 @@
+$ python exceptions_finally.py
+Programming is fun
+Press ctrl+c now
+^C!! You cancelled the reading from the file.
+(Cleaning up: Closed the file)

+ 8 - 0
programs/exceptions_handle.py

@@ -0,0 +1,8 @@
+try:
+    text = input('Enter something --> ')
+except EOFError:
+    print('Why did you do an EOF on me?')
+except KeyboardInterrupt:
+    print('You cancelled the operation.')
+else:
+    print('You entered {}'.format(text))

+ 11 - 0
programs/exceptions_handle.txt

@@ -0,0 +1,11 @@
+# Press ctrl + d
+$ python exceptions_handle.py
+Enter something --> Why did you do an EOF on me?
+
+# Press ctrl + c
+$ python exceptions_handle.py
+Enter something --> ^CYou cancelled the operation.
+
+$ python exceptions_handle.py
+Enter something --> No exceptions
+You entered No exceptions

+ 20 - 0
programs/exceptions_raise.py

@@ -0,0 +1,20 @@
+class ShortInputException(Exception):
+    '''A user-defined exception class.'''
+    def __init__(self, length, atleast):
+        Exception.__init__(self)
+        self.length = length
+        self.atleast = atleast
+
+try:
+    text = input('Enter something --> ')
+    if len(text) < 3:
+        raise ShortInputException(len(text), 3)
+    # Other work can continue as usual here
+except EOFError:
+    print('Why did you do an EOF on me?')
+except ShortInputException as ex:
+    print(('ShortInputException: The input was ' +
+           '{0} long, expected at least {1}')
+          .format(ex.length, ex.atleast))
+else:
+    print('No exception was raised.')

+ 7 - 0
programs/exceptions_raise.txt

@@ -0,0 +1,7 @@
+$ python exceptions_raise.py
+Enter something --> a
+ShortInputException: The input was 1 long, expected at least 3
+
+$ python exceptions_raise.py
+Enter something --> abc
+No exception was raised.

+ 3 - 0
programs/exceptions_using_with.py

@@ -0,0 +1,3 @@
+with open("poem.txt") as f:
+    for line in f:
+        print(line, end='')

+ 4 - 0
programs/for.py

@@ -0,0 +1,4 @@
+for i in range(1, 5):
+    print(i)
+else:
+    print('The for loop is over')

+ 6 - 0
programs/for.txt

@@ -0,0 +1,6 @@
+$ python for.py
+1
+2
+3
+4
+The for loop is over

+ 7 - 0
programs/function1.py

@@ -0,0 +1,7 @@
+def say_hello():
+    # block belonging to the function
+    print('hello world')
+# End of function
+
+say_hello()  # call the function
+say_hello()  # call the function again

+ 3 - 0
programs/function1.txt

@@ -0,0 +1,3 @@
+$ python function1.py
+hello world
+hello world

+ 5 - 0
programs/function_default.py

@@ -0,0 +1,5 @@
+def say(message, times=1):
+    print(message * times)
+
+say('Hello')
+say('World', 5)

+ 3 - 0
programs/function_default.txt

@@ -0,0 +1,3 @@
+$ python function_default.py
+Hello
+WorldWorldWorldWorldWorld

+ 15 - 0
programs/function_docstring.py

@@ -0,0 +1,15 @@
+def print_max(x, y):
+    '''Prints the maximum of two numbers.
+
+    The two values must be integers.'''
+    # convert to integers, if possible
+    x = int(x)
+    y = int(y)
+
+    if x > y:
+        print(x, 'is maximum')
+    else:
+        print(y, 'is maximum')
+
+print_max(3, 5)
+print(print_max.__doc__)

+ 5 - 0
programs/function_docstring.txt

@@ -0,0 +1,5 @@
+$ python function_docstring.py
+5 is maximum
+Prints the maximum of two numbers.
+
+    The two values must be integers.

+ 13 - 0
programs/function_global.py

@@ -0,0 +1,13 @@
+x = 50
+
+
+def func():
+    global x
+
+    print('x is', x)
+    x = 2
+    print('Changed global x to', x)
+
+
+func()
+print('Value of x is', x)

+ 4 - 0
programs/function_global.txt

@@ -0,0 +1,4 @@
+$ python function_global.py
+x is 50
+Changed global x to 2
+Value of x is 2

+ 6 - 0
programs/function_keyword.py

@@ -0,0 +1,6 @@
+def func(a, b=5, c=10):
+    print('a is', a, 'and b is', b, 'and c is', c)
+
+func(3, 7)
+func(25, c=24)
+func(c=50, a=100)

+ 4 - 0
programs/function_keyword.txt

@@ -0,0 +1,4 @@
+$ python function_keyword.py
+a is 3 and b is 7 and c is 10
+a is 25 and b is 5 and c is 24
+a is 100 and b is 5 and c is 50

+ 11 - 0
programs/function_local.py

@@ -0,0 +1,11 @@
+x = 50
+
+
+def func(x):
+    print('x is', x)
+    x = 2
+    print('Changed local x to', x)
+
+
+func(x)
+print('x is still', x)

+ 4 - 0
programs/function_local.txt

@@ -0,0 +1,4 @@
+$ python function_local.py
+x is 50
+Changed local x to 2
+x is still 50

+ 16 - 0
programs/function_param.py

@@ -0,0 +1,16 @@
+def print_max(a, b):
+    if a > b:
+        print(a, 'is maximum')
+    elif a == b:
+        print(a, 'is equal to', b)
+    else:
+        print(b, 'is maximum')
+
+# directly pass literal values
+print_max(3, 4)
+
+x = 5
+y = 7
+
+# pass variables as arguments
+print_max(x, y)

+ 3 - 0
programs/function_param.txt

@@ -0,0 +1,3 @@
+$ python function_param.py
+4 is maximum
+7 is maximum

+ 9 - 0
programs/function_return.py

@@ -0,0 +1,9 @@
+def maximum(x, y):
+    if x > y:
+        return x
+    elif x == y:
+        return 'The numbers are equal'
+    else:
+        return y
+
+print(maximum(2, 3))

+ 2 - 0
programs/function_return.txt

@@ -0,0 +1,2 @@
+$ python function_return.py
+3

+ 9 - 0
programs/function_varargs.py

@@ -0,0 +1,9 @@
+def total(initial=5, *numbers, **keywords):
+    count = initial
+    for number in numbers:
+        count += number
+    for key in keywords:
+        count += keywords[key]
+    return count
+
+print(total(10, 1, 2, 3, vegetables=50, fruits=100))

+ 2 - 0
programs/function_varargs.txt

@@ -0,0 +1,2 @@
+$ python function_varargs.py
+166

+ 19 - 0
programs/if.py

@@ -0,0 +1,19 @@
+number = 23
+guess = int(input('Enter an integer : '))
+
+if guess == number:
+    # New block starts here
+    print('Congratulations, you guessed it.')
+    print('(but you do not win any prizes!)')
+    # New block ends here
+elif guess < number:
+    # Another block
+    print('No, it is a little higher than that')
+    # You can do whatever you want in a block ...
+else:
+    print('No, it is a little lower than that')
+    # you must have guessed > number to reach here
+
+print('Done')
+# This last statement is always executed,
+# after the if statement is executed.

+ 15 - 0
programs/if.txt

@@ -0,0 +1,15 @@
+$ python if.py
+Enter an integer : 50
+No, it is a little lower than that
+Done
+
+$ python if.py
+Enter an integer : 22
+No, it is a little higher than that
+Done
+
+$ python if.py
+Enter an integer : 23
+Congratulations, you guessed it.
+(but you do not win any prizes!)
+Done

+ 13 - 0
programs/io_input.py

@@ -0,0 +1,13 @@
+def reverse(text):
+    return text[::-1]
+
+
+def is_palindrome(text):
+    return text == reverse(text)
+
+
+something = input("Enter text: ")
+if is_palindrome(something):
+    print("Yes, it is a palindrome")
+else:
+    print("No, it is not a palindrome")

+ 11 - 0
programs/io_input.txt

@@ -0,0 +1,11 @@
+$ python3 io_input.py
+Enter text: sir
+No, it is not a palindrome
+
+$ python3 io_input.py
+Enter text: madam
+Yes, it is a palindrome
+
+$ python3 io_input.py
+Enter text: racecar
+Yes, it is a palindrome

+ 21 - 0
programs/io_pickle.py

@@ -0,0 +1,21 @@
+import pickle
+
+# The name of the file where we will store the object
+shoplistfile = 'shoplist.data'
+# The list of things to buy
+shoplist = ['apple', 'mango', 'carrot']
+
+# Write to the file
+f = open(shoplistfile, 'wb')
+# Dump the object to a file
+pickle.dump(shoplist, f)
+f.close()
+
+# Destroy the shoplist variable
+del shoplist
+
+# Read back from the storage
+f = open(shoplistfile, 'rb')
+# Load the object from the file
+storedlist = pickle.load(f)
+print(storedlist)

+ 2 - 0
programs/io_pickle.txt

@@ -0,0 +1,2 @@
+$ python io_pickle.py
+['apple', 'mango', 'carrot']

+ 9 - 0
programs/io_unicode.py

@@ -0,0 +1,9 @@
+# encoding=utf-8
+import io
+
+f = io.open("abc.txt", "wt", encoding="utf-8")
+f.write(u"Imagine non-English language here")
+f.close()
+
+text = io.open("abc.txt", encoding="utf-8").read()
+print(text)

+ 28 - 0
programs/io_using_file.py

@@ -0,0 +1,28 @@
+poem = '''\
+Programming is fun
+When the work is done
+if you wanna make your work also fun:
+    use Python!
+'''
+
+# Open for 'w'riting
+f = open('poem.txt', 'w')
+# Write text to file
+f.write(poem)
+# Close the file
+f.close()
+
+# If no mode is specified,
+# 'r'ead mode is assumed by default
+f = open('poem.txt')
+while True:
+    line = f.readline()
+    # Zero length indicates EOF
+    if len(line) == 0:
+        break
+    # The `line` already has a newline
+    # at the end of each line
+    # since it is reading from a file.
+    print(line, end='')
+# close the file
+f.close()

+ 5 - 0
programs/io_using_file.txt

@@ -0,0 +1,5 @@
+$ python3 io_using_file.py
+Programming is fun
+When the work is done
+if you wanna make your work also fun:
+    use Python!

+ 4 - 0
programs/module_using_name.py

@@ -0,0 +1,4 @@
+if __name__ == '__main__':
+    print('This program is being run by itself')
+else:
+    print('I am being imported from another module')

+ 7 - 0
programs/module_using_name.txt

@@ -0,0 +1,7 @@
+$ python module_using_name.py
+This program is being run by itself
+
+$ python
+>>> import module_using_name
+I am being imported from another module
+>>>

+ 7 - 0
programs/module_using_sys.py

@@ -0,0 +1,7 @@
+import sys
+
+print('The command line arguments are:')
+for i in sys.argv:
+    print(i)
+
+print('\n\nThe PYTHONPATH is', sys.path, '\n')

+ 12 - 0
programs/module_using_sys.txt

@@ -0,0 +1,12 @@
+$ python module_using_sys.py we are arguments
+The command line arguments are:
+module_using_sys.py
+we
+are
+arguments
+
+
+The PYTHONPATH is ['/tmp/py',
+# many entries here, not shown here
+'/Library/Python/2.7/site-packages',
+'/usr/local/lib/python2.7/site-packages']

+ 43 - 0
programs/more_decorator.py

@@ -0,0 +1,43 @@
+from time import sleep
+from functools import wraps
+import logging
+logging.basicConfig()
+log = logging.getLogger("retry")
+
+
+def retry(f):
+    @wraps(f)
+    def wrapped_f(*args, **kwargs):
+        MAX_ATTEMPTS = 5
+        for attempt in range(1, MAX_ATTEMPTS + 1):
+            try:
+                return f(*args, **kwargs)
+            except:
+                log.exception("Attempt %s/%s failed : %s",
+                              attempt,
+                              MAX_ATTEMPTS,
+                              (args, kwargs))
+                sleep(10 * attempt)
+        log.critical("All %s attempts failed : %s",
+                     MAX_ATTEMPTS,
+                     (args, kwargs))
+    return wrapped_f
+
+
+counter = 0
+
+
+@retry
+def save_to_database(arg):
+    print("Write to a database or make a network call or etc.")
+    print("This will be automatically retried if exception is thrown.")
+    global counter
+    counter += 1
+    # This will throw an exception in the first call
+    # And will work fine in the second call (i.e. a retry)
+    if counter < 2:
+        raise ValueError(arg)
+
+
+if __name__ == '__main__':
+    save_to_database("Some bad value")

+ 12 - 0
programs/more_decorator.txt

@@ -0,0 +1,12 @@
+$ python more_decorator.py
+Write to a database or make a network call or etc.
+This will be automatically retried if exception is thrown.
+ERROR:retry:Attempt 1/5 failed : (('Some bad value',), {})
+Traceback (most recent call last):
+  File "more_decorator.py", line 14, in wrapped_f
+    return f(*args, **kwargs)
+  File "more_decorator.py", line 39, in save_to_database
+    raise ValueError(arg)
+ValueError: Some bad value
+Write to a database or make a network call or etc.
+This will be automatically retried if exception is thrown.

+ 4 - 0
programs/more_lambda.py

@@ -0,0 +1,4 @@
+points = [{'x': 2, 'y': 3},
+          {'x': 4, 'y': 1}]
+points.sort(key=lambda i: i['y'])
+print(points)

+ 2 - 0
programs/more_lambda.txt

@@ -0,0 +1,2 @@
+$ python more_lambda.py
+[{'y': 1, 'x': 4}, {'y': 3, 'x': 2}]

+ 3 - 0
programs/more_list_comprehension.py

@@ -0,0 +1,3 @@
+listone = [2, 3, 4]
+listtwo = [2*i for i in listone if i > 2]
+print(listtwo)

+ 2 - 0
programs/more_list_comprehension.txt

@@ -0,0 +1,2 @@
+$ python more_list_comprehension.py
+[6, 8]

+ 4 - 0
programs/mymodule.py

@@ -0,0 +1,4 @@
+def say_hi():
+    print('Hi, this is mymodule speaking.')
+
+__version__ = '0.1'

+ 4 - 0
programs/mymodule_demo.py

@@ -0,0 +1,4 @@
+import mymodule
+
+mymodule.say_hi()
+print('Version', mymodule.__version__)

+ 3 - 0
programs/mymodule_demo.txt

@@ -0,0 +1,3 @@
+$ python mymodule_demo.py
+Hi, this is mymodule speaking.
+Version 0.1

+ 4 - 0
programs/mymodule_demo2.py

@@ -0,0 +1,4 @@
+from mymodule import say_hi, __version__
+
+say_hi()
+print('Version', __version__)

+ 11 - 0
programs/oop_init.py

@@ -0,0 +1,11 @@
+class Person:
+    def __init__(self, name):
+        self.name = name
+
+    def say_hi(self):
+        print('Hello, my name is', self.name)
+
+p = Person('Swaroop')
+p.say_hi()
+# The previous 2 lines can also be written as
+# Person('Swaroop').say_hi()

+ 2 - 0
programs/oop_init.txt

@@ -0,0 +1,2 @@
+$ python oop_init.py
+Hello, my name is Swaroop

+ 8 - 0
programs/oop_method.py

@@ -0,0 +1,8 @@
+class Person:
+    def say_hi(self):
+        print('Hello, how are you?')
+
+p = Person()
+p.say_hi()
+# The previous 2 lines can also be written as
+# Person().say_hi()

+ 2 - 0
programs/oop_method.txt

@@ -0,0 +1,2 @@
+$ python oop_method.py
+Hello, how are you?

+ 54 - 0
programs/oop_objvar.py

@@ -0,0 +1,54 @@
+class Robot:
+    """Represents a robot, with a name."""
+
+    # A class variable, counting the number of robots
+    population = 0
+
+    def __init__(self, name):
+        """Initializes the data."""
+        self.name = name
+        print("(Initializing {})".format(self.name))
+
+        # When this person is created, the robot
+        # adds to the population
+        Robot.population += 1
+
+    def die(self):
+        """I am dying."""
+        print("{} is being destroyed!".format(self.name))
+
+        Robot.population -= 1
+
+        if Robot.population == 0:
+            print("{} was the last one.".format(self.name))
+        else:
+            print("There are still {:d} robots working.".format(
+                Robot.population))
+
+    def say_hi(self):
+        """Greeting by the robot.
+
+        Yeah, they can do that."""
+        print("Greetings, my masters call me {}.".format(self.name))
+
+    @classmethod
+    def how_many(cls):
+        """Prints the current population."""
+        print("We have {:d} robots.".format(cls.population))
+
+
+droid1 = Robot("R2-D2")
+droid1.say_hi()
+Robot.how_many()
+
+droid2 = Robot("C-3PO")
+droid2.say_hi()
+Robot.how_many()
+
+print("\nRobots can do some work here.\n")
+
+print("Robots have finished their work. So let's destroy them.")
+droid1.die()
+droid2.die()
+
+Robot.how_many()

+ 16 - 0
programs/oop_objvar.txt

@@ -0,0 +1,16 @@
+$ python oop_objvar.py
+(Initializing R2-D2)
+Greetings, my masters call me R2-D2.
+We have 1 robots.
+(Initializing C-3PO)
+Greetings, my masters call me C-3PO.
+We have 2 robots.
+
+Robots can do some work here.
+
+Robots have finished their work. So let's destroy them.
+R2-D2 is being destroyed!
+There are still 1 robots working.
+C-3PO is being destroyed!
+C-3PO was the last one.
+We have 0 robots.

+ 5 - 0
programs/oop_simplestclass.py

@@ -0,0 +1,5 @@
+class Person:
+    pass  # An empty block
+
+p = Person()
+print(p)

+ 2 - 0
programs/oop_simplestclass.txt

@@ -0,0 +1,2 @@
+$ python oop_simplestclass.py
+<__main__.Person instance at 0x10171f518>

+ 45 - 0
programs/oop_subclass.py

@@ -0,0 +1,45 @@
+class SchoolMember:
+    '''Represents any school member.'''
+    def __init__(self, name, age):
+        self.name = name
+        self.age = age
+        print('(Initialized SchoolMember: {})'.format(self.name))
+
+    def tell(self):
+        '''Tell my details.'''
+        print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
+
+
+class Teacher(SchoolMember):
+    '''Represents a teacher.'''
+    def __init__(self, name, age, salary):
+        SchoolMember.__init__(self, name, age)
+        self.salary = salary
+        print('(Initialized Teacher: {})'.format(self.name))
+
+    def tell(self):
+        SchoolMember.tell(self)
+        print('Salary: "{:d}"'.format(self.salary))
+
+
+class Student(SchoolMember):
+    '''Represents a student.'''
+    def __init__(self, name, age, marks):
+        SchoolMember.__init__(self, name, age)
+        self.marks = marks
+        print('(Initialized Student: {})'.format(self.name))
+
+    def tell(self):
+        SchoolMember.tell(self)
+        print('Marks: "{:d}"'.format(self.marks))
+
+t = Teacher('Mrs. Shrividya', 40, 30000)
+s = Student('Swaroop', 25, 75)
+
+# prints a blank line
+print()
+
+members = [t, s]
+for member in members:
+    # Works for both Teachers and Students
+    member.tell()

+ 8 - 0
programs/oop_subclass.txt

@@ -0,0 +1,8 @@
+$ python oop_subclass.py
+(Initialized SchoolMember: Mrs. Shrividya)
+(Initialized Teacher: Mrs. Shrividya)
+(Initialized SchoolMember: Swaroop)
+(Initialized Student: Swaroop)
+
+Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
+Name:"Swaroop" Age:"25" Marks: "75"

+ 4 - 0
programs/poem.txt

@@ -0,0 +1,4 @@
+Programming is fun
+When the work is done
+if you wanna make your work also fun:
+    use Python!

+ 8 - 0
programs/shoplist.data

@@ -0,0 +1,8 @@
+(lp0
+S'apple'
+p1
+aS'mango'
+p2
+aS'carrot'
+p3
+a.

+ 24 - 0
programs/stdlib_logging.py

@@ -0,0 +1,24 @@
+import os
+import platform
+import logging
+
+if platform.platform().startswith('Windows'):
+    logging_file = os.path.join(os.getenv('HOMEDRIVE'),
+                                os.getenv('HOMEPATH'),
+                                'test.log')
+else:
+    logging_file = os.path.join(os.getenv('HOME'),
+                                'test.log')
+
+print("Logging to", logging_file)
+
+logging.basicConfig(
+    level=logging.DEBUG,
+    format='%(asctime)s : %(levelname)s : %(message)s',
+    filename=logging_file,
+    filemode='w',
+)
+
+logging.debug("Start of the program")
+logging.info("Doing something")
+logging.warning("Dying now")

+ 7 - 0
programs/stdlib_logging.txt

@@ -0,0 +1,7 @@
+$ python stdlib_logging.py
+Logging to /Users/swa/test.log
+
+$ cat /Users/swa/test.log
+2014-03-29 09:27:36,660 : DEBUG : Start of the program
+2014-03-29 09:27:36,660 : INFO : Doing something
+2014-03-29 09:27:36,660 : WARNING : Dying now

+ 19 - 0
programs/while.py

@@ -0,0 +1,19 @@
+number = 23
+running = True
+
+while running:
+    guess = int(input('Enter an integer : '))
+
+    if guess == number:
+        print('Congratulations, you guessed it.')
+        # this causes the while loop to stop
+        running = False
+    elif guess < number:
+        print('No, it is a little higher than that.')
+    else:
+        print('No, it is a little lower than that.')
+else:
+    print('The while loop is over.')
+    # Do anything else you want to do here
+
+print('Done')

+ 9 - 0
programs/while.txt

@@ -0,0 +1,9 @@
+$ python while.py
+Enter an integer : 50
+No, it is a little lower than that.
+Enter an integer : 22
+No, it is a little higher than that.
+Enter an integer : 23
+Congratulations, you guessed it.
+The while loop is over.
+Done