18.1 CS 102 Unit 18 Python Mark Redekopp
18.2 Credits • Many of the examples below are taken from the online Python tutorial at: – http://docs.python.org/tutorial/introduction.html
18.3 Python in Context • Two major versions with some language differences – Python 2.x – Python 3.x (we will focus on this version) • Interpreted, not compiled like C++ – Can type in single commands at a time and have them execute in "real time" – Somewhat slower – Better protection (no memory faults)
18.4 Interactive vs. Scripts • Can invoke python and work interactively – % python #python 2.x – % python3 #python 3.x >>> print("Hello World") Ctrl-D (Linux/Mac) [Ctrl-Z Windows] at the prompt will exit. • Can write code into a text file and execute that file as a script – % python3 myscript.py # python2.x >>>print "Hello world" # python3.x >>> print("Hello world") myscript.py
18.5 Types # python 2.x >>> 3 / 2 1 # python2.x • Types 1.5 # python3.x – Bool: True/False (not true/false ) # python 3.x – Integers >>> 3 // 2 1 • Integer division => see examples >>> 1.25 / 0.5 – Floats 2.5 – Complex >>> 2+4j + 3-2j – Strings (5+2j) • Dynamically typed >>> "Hello world" 'Hello world' – No need to "type" a variable >>> 5 == 6 – Python figures it out based on what it is False assigned – Can change when re-assigned >>> x = 3 >>> x = "Hi" >>> x = 5.0 + 2.5
18.6 Strings • Enclosed in either double >>> 'spam eggs' 'spam eggs' or single quotes >>> "doesn't" – The unused quote type "doesn't" can be used within the >>>'"Yes," he said.' '"Yes," he said.' string >>> "Con" + "cat" + "enate" • Can concatenate using 'Concatenate' the ‘+’ operator >>> i = 5 >>> j = 2.75 • Can convert other types >>> "i is " + str(i) + " & j is" + str(j) 'i is 5 & j is 2.75' to string via the str(x) method • Compare with ==, !=, etc.
18.7 Simple Console I/O >>> print("A new line will") • Python3.x >>> print('be printed') A new line will be printed – Output using print() >>> print('A new line will', end='') • Must use parentheses >>> print(' not be printed') • Use end='' argument for ending A new line will be printed options # Getting input – Input using input(prompt) >>> response = input("Enter text: ") Enter text: I am here • Returns a string of all text typed until >>> print(response) the newline I am here • Conversion to numeric types: >>> response = input("Enter a num: ") Enter a num: 6 – int( string_var ) convert to an integer >>> x = int(response) >>> x = float(response) – float(string_var) convert to a float
18.8 Selection Structures • if… elif …else myin = input("Enter a number: ") • Ends with a : on that line x = int(myin) • Blocks of code delineated by if x > 10: print("Number is greater than 10") indentation (via tabs/spaces) elif x < 10: print("Number is less than 10") else: print("Number is equal to 10")
18.9 Iterative Structures • while <cond>: secret = 18 • Again code is delineated attempts = 0 by indentation while attempts < 10: myin = input("Enter a number: ") if int(myin) == secret: print("Correct!") break attempts += 1
18.10 Lists >>> x = ['Hi', 5, 6.5] • Lists are like arrays from C++ >>> print(x[1]) 5 but can have different >>> y = x[2] + 1.25 (heterogenous) types in a single 7.75 list object >>> x[2] = 9.5 • Comma separated values >>> x ['Hi', 5, 9.5] between square brackets >>> x.append(11) • Basic operations/functions: ['Hi', 5, 9.5, 11] – append(value) >>> y = x.pop(1) >>> x – pop(loc) ['Hi', 9.5, 11] – len(list) >>> print(y) 5 >>> len(x) 3
18.11 Iterative Structures • for <item> in <collection>: # Prints 0 through 5 on separate lines x = [0,1,2,3,4,5] # equiv to x = range(6) • collection can be list or some other for i in x: collection print(i) • For a specific range of integers just # Prints 0 through 4 on separate lines use range() function to generate a list x = 5 for i in range(x): – Start is inclusive, stop is exclusive print(i) – range(stop) # Prints 2 through 5 on separate lines • 0 through stop-1 for i in range(2,6): – range(start, stop) print(i) • start through stop-1 x = ["hi", "world", "bye"] – range(start, stop, step) mystring = "" for word in x: • start through stop in increments of mystring += word + " " stepsize
18.12 Exercise 1 • Get integers from the user 7 until they type quit 2 -4 • Output only the sum of 9 quit the 1 st and last integers 16 entered
Recommend
More recommend