260 likes | 423 Views
Introduction to Python. What is Python?. Interpreted object oriented high level programming language No compiling or linking neccesary Extensible: add new functions or modules to the interpreter. Benefits. Offers more structure and support for large programs than shell and batch files
E N D
What is Python? • Interpreted object oriented high level programming language • No compiling or linking neccesary • Extensible: add new functions or modules to the interpreter
Benefits • Offers more structure and support for large programs than shell and batch files • Modules – can be reused • No compilation saves development time • Easy to read syntax
The Interpreter • Similar to UNIX • Reads and executes commands interactively • When called with a file name argument, it reads and executes a script from that file. • Invoking is simple: • python or • python -c command [arg] ...
Script name and additional arguments are passed to sys.argv • When commands are read from a tty, the interpreter is said to be in interactive mode. • Primary Prompt: >>> • Secondary Prompt: ... • Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
Example: >>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print "Be careful not to fall off!" ... Be careful not to fall off!
Using Python as a Calculator • >>> 2+2 • 4 • >>> # This is a comment • ... 2+2 • 4 • >>> 2+2 # and a comment on the same line as code • 4 • >>> (50-5*6)/4 • 5.0 • >>> 8/5 # Fractions aren’t lost when dividing integers • 1.6
Using Variables >>> width = 20 >>> height = 5*9 >>> width * height 900 >>> x = y = z = 0 # Zero x, y and z >>> x 0 >>> y 0 >>> z 0
Using Variables >>> # try to access an undefined variable ... n Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ’n’ is not defined >>> # last printed expression is stored as _ >>> price * tax 12.5625 >>> price + _ 113.0625
Strings >>> ’spam eggs’ ’spam eggs’ >>> ’doesn\’t’ "doesn’t" >>> "doesn’t“ "doesn’t“ >>> ’"Yes," he said.’ ’"Yes," he said.’ >>> "\"Yes,\" he said." ’"Yes," he said.’ >>> ’"Isn\’t," she said.’ ’"Isn\’t," she said.’
New lines hello = "This is a rather long string containing\n\ several lines of text just as you would do in C.\n\ Note that whitespace at the beginning of the line is\ significant." print(hello) This is a rather long string containing several lines of text just as you would do in C. Note that whitespace at the beginning of the line is significant.
Manipulating Strings >>> word = ’Help’ + ’A’ >>> word ’HelpA’ >>> ’<’ + word*5 + ’>’ ’<HelpAHelpAHelpAHelpAHelpA>’ >>> ’str’ ’ing’ ’string’ >>> ’str’.strip() + ’ing’ ’string’
Subscripts >>> word[4] ’A’ >>> word[0:2] ’He’ >>> word[2:4] ’lp’ >>> word[:2] # The first two characters ’He’ >>> word[2:] # Everything except the first two characters ’lpA’
More Slice Notation >>> word[0] = ’x’ Traceback (most recent call last): File "<stdin>", line 1, in ? >>> ’x’ + word[1:] ’xelpA’ >>> ’Splat’ + word[4] ’SplatA’ >>> word[1:100] ’elpA’ >>> word[10:] ’’ >>> word[2:1] ’’
More Slice Notation >>> word[-1] # The last character ’A’ >>> word[-2] # The last-but-one character ’p’ >>> word[-2:] # The last two characters ’pA’ >>> word[:-2] # Everything except the last two characters ’Hel’
Lists • Most versatile compound data type. • List items may be different types. >>> a = [’spam’, ’eggs’, 100, 1234] >>> a [’spam’, ’eggs’, 100, 1234]
Lists Indices >>> a[0] ’spam’ >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] [’eggs’, 100] >>> a[:2] + [’bacon’, 2*2] [’spam’, ’eggs’, ’bacon’, 4] >>> 3*a[:3] + [’Boo!’] [’spam’, ’eggs’, 100, ’spam’, ’eggs’, 100, ’spam’, ’eggs’, 100, ’Boo!’]
Programming >>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... print(b) ... a, b = b, a+b ... 1 1 2 3 5 8
if Statements >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print(’Negative changed to zero’) ... elifx == 0: ... print(’Zero’) ... elifx == 1: ... print(’Single’) ... else: ... print(’More’) ... More
for Statements >>> # Measure some strings: ... a = [’cat’, ’window’, ’for’] >>> for x in a: ... print(x, len(x)) ... cat 3 window 6 for 3
Using range() function >>> for i in range(5): ... print(i) ... 0 1 2 3 4
Using break and else for loops >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, ’equals’, x, ’*’, n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, ’is a prime number’) ...
Using pass The pass statement is used for when a statement is required but no action. >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ... >>> class MyEmptyClass: ... pass ...
Defining Functions >>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while b < n: ... print(b, end=’ ’) ... a, b = b, a+b ... print() ... >>> # Now call the function we just defined: ... fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Keyword Arguments -May use keyword arguments of the form: keyword = value def parrot(voltage, state=’a stiff’, action=’voom’): print("-- This parrot wouldn’t", action, end=’ ’) print("if you put", voltage, "volts through it.")