Tutorial by Examples

Python 2.x2.3 raw_input will wait for the user to enter text and then return the result as a string. foo = raw_input("Put a message here that asks the user for input") In the above example foo will store whatever input the user provides. Python 3.x3.0 input will wait for the user ...
Python 3.x3.0 In Python 3, print functionality is in the form of a function: print("This string will be displayed in the output") # This string will be displayed in the output print("You can print \n escape characters too.") # You can print escape characters too. Pyth...
def input_number(msg, err_msg=None): while True: try: return float(raw_input(msg)) except ValueError: if err_msg is not None: print(err_msg) def input_number(msg, err_msg=None): while True: try: return ...
Python 2.x2.3 In Python 2.x, to continue a line with print, end the print statement with a comma. It will automatically add a space. print "Hello,", print "World!" # Hello, World! Python 3.x3.0 In Python 3.x, the print function has an optional end parameter that is what...
Python programs can read from unix pipelines. Here is a simple example how to read from stdin: import sys for line in sys.stdin: print(line) Be aware that sys.stdin is a stream. It means that the for-loop will only terminate when the stream has ended. You can now pipe the output of anot...
Input can also be read from files. Files can be opened using the built-in function open. Using a with <command> as <name> syntax (called a 'Context Manager') makes using open and getting a handle for the file super easy: with open('somefile.txt', 'r') as fileobj: # write code here ...

Page 1 of 1