Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Instructor: Zhuojun Duan

Similar presentations


Presentation on theme: "Chapter 3 Instructor: Zhuojun Duan"— Presentation transcript:

1 Chapter 3 Instructor: Zhuojun Duan
CSC 2302/CSC 7352 , Fall 2017 Chapter 3 Instructor: Zhuojun Duan The Department of Computer Science

2 Chapter 3 Imperative Programming
Python Programs Interactive Input/Output One-Way and Two-Way if Statements for Loops User-Defined Functions Object and class Assignments Revisited and Parameter Passing

3 Python program A Python program is a sequence of Python statements
line1 = 'Hello Python developer...' A Python program is a sequence of Python statements Stored in a text file called a Python module Executed using an IDE or “from the command line” A Python program is a sequence of Python statements Stored in a text file called a Python module Executed using an IDE or “from the command line” line2 = 'Welcome to the world of Python!' print(line1) print(line2) line1 = 'Hello Python developer...' line2 = 'Welcome to the world of Python!' print(line1) print(line2) line1 = 'Hello Python developer...' line2 = 'Welcome to the world of Python!' print(line1) print(line2) line1 = 'Hello Python developer...' line2 = 'Welcome to the world of Python!' print(line1) print(line2) line1 = 'Hello Python developer...' line2 = 'Welcome to the world of Python!' print(line1) print(line2) line1 = 'Hello Python developer...' line2 = 'Welcome to the world of Python!' print(line1) print(line2) Run hello.py Hello Python developer… Run hello.py Hello Python developer… Welcome to the world of Python! Run hello.py hello.py

4 Built-in function print()
Function print() prints its input argument to the IDLE window The argument can be any object: an integer, a float, a string, a list, … Strings are printed without quotes and “to be read by people”, rather than “to be interpreted by Python”, The “string representation” of the object is printed >>> print(0) >>> print(0.0) 0.0 >>> print('zero') zero >>> print([0, 1, 'two']) [0, 1, 'two']

5 Built-in function input()
Function input() requests and reads input from the user interactively It’s (optional) input argument is the request message Typically used on the right side of an assignment statement >>> name = input('Enter your name: ') Enter your name: Michael >>> name 'Michael' >>> ========= RESTART ============= >>> Enter your first name: Michael Enter your last name: >>> name = input('Enter your name: ') Enter your name: Michael >>> name 'Michael' >>> ========= RESTART ============= >>> Enter your first name: Michael Enter your last name: Jordan Hello Michael Jordan... Welcome to the world of Python! >>> name = input('Enter your name: ') >>> name = input('Enter your name: ') Enter your name: Michael >>> >>> name = input('Enter your name: ') Enter your name: Michael >>> name 'Michael' >>> ========= RESTART ============= >>> Enter your first name: >>> name = input('Enter your name: ') Enter your name: Michael >>> name 'Michael' >>> name = input('Enter your name: ') Enter your name: >>> name = input('Enter your name: ') Enter your name: Michael When executed: The input request message is printed The user enters the input The string typed by the user is assigned to the variable on the left side of the assignment statement first = input('Enter your first name: ') last = input('Enter your last name: ') line1 = 'Hello’ + first + '' + last + '…' print(line1) print('Welcome to the world of Python!') first = input('Enter your first name: ') last = input('Enter your last name: ') line1 = 'Hello’ + first + '' + last + '…' print(line1) print('Welcome to the world of Python!') first = input('Enter your first name: ') last = input('Enter your last name: ') line1 = 'Hello’ + first + '' + last + '…' print(line1) print('Welcome to the world of Python!') first = input('Enter your first name: ') last = input('Enter your last name: ') line1 = 'Hello’ + first + '' + last + '…' print(line1) print('Welcome to the world of Python!') input.py

6 Built-in function eval()
Function input() evaluates anything the user enters as a string What if we want the user to interactively enter non-string input such as a number? Function input() evaluates anything the user enters as a string What if we want the user to interactively enter non-string input such as a number? Solution 1: Use type conversion Solution 2: Use function eval() Takes a string as input and evaluates it as a Python expression >>> age = input('Enter your age: ') Enter your age: 18 >>> age '18' >>> age = input('Enter your age: ') Enter your age: 18 >>> age '18' >>> int(age) 18 >>> eval('18') >>> eval('age') >>> eval('[2,3+5]') [2, 8] >>> eval('x') Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> eval('x') File "<string>", line 1, in <module> NameError: name 'x' is not defined >>> >>> age = input('Enter your age: ') Enter your age: 18 >>> age '18' >>> int(age) 18

7 Exercise Write a program that: Requests the user’s name
Requests the user’s age Computes the user’s age one year from now and prints the message shown >>> Enter your name: Marie Enter your age: 17 Marie, you will be 20 next year! name = input('Enter your name: ') age = int(input('Enter your age: ')) line = name + ', you will be ' + str(age+1) + ' next year!' print(line)

8 Exercise Write a program that:
Requests the user’s name Requests the user’s age Prints a message saying whether the user is eligible to vote or not Need a way to execute a Python statement if a condition is true

9 print('Be sure to drink liquids.')
One-way if statement if <condition>: <indented code block> <non-indented statement> if temp > 86: print('It is hot!') print('Be sure to drink liquids.') print('Goodbye.') if temp > 86: print('It is hot!') print('Be sure to drink liquids.') print('Goodbye.') if temp > 86: print('It is hot!') print('Be sure to drink liquids.') print('Goodbye.') The value of temp is 90. The value of temp is 50. temp > 86: True print('It is hot!') Rhombus 'rɑmbəs False print('Be sure to drink liquids.') Print('Goddbye.')

10 Exercises Write corresponding if statements:
If age is greater than 62 then print 'You can get Social Security benefits’ If string 'large bonuses' appears in string report then print 'Vacation time!’ If hits is greater than 10 and shield is 0 then print "You're dead..." >>> hits = 12 >>> shield = 0 >>> if hits > 10 and shield == 0: print("You're dead...") You're dead... >>> hits, shield = 12, 2 >>> >>> age = 45 >>> if age > 62: print('You can get Social Security benefits') >>> age = 65 You can get Social Security benefits >>> >>> report = 'no bonuses this year' >>> if 'large bonuses' in report: print('Vacation time!') >>> report = 'large bonuses this year' Vacation time!

11 Indentation is critical
if temp > 86: print('It is hot!') print('Drink liquids.') print('Goodbye.') if temp > 86: print('It is hot!') print('Drink liquids.') print('Goodbye.') temp > 86: temp > 86: True True print('It is hot!') print('It is hot!') False False print('Drink liquids.') print('Drink liquids.') print('Goddbye.') print('Goddbye.')

12 print('Be sure to drink liquids.')
Two-way if statement if <condition>: <indented code block 1> else: <indented code block 2> <non-indented statement> if temp > 86: print('It is hot!') print('Be sure to drink liquids.') else: print('It is not hot.') print('Bring a jacket.') print('Goodbye.') if temp > 86: print('It is hot!') print('Be sure to drink liquids.') else: print('It is not hot.') print('Bring a jacket.') print('Goodbye.') if temp > 86: print('It is hot!') print('Be sure to drink liquids.') else: print('It is not hot.') print('Bring a jacket.') print('Goodbye.') The value of temp is 90. The value of temp is 50. temp > 86: False True print('It is not hot!') print('It is hot!') print('Bring a jacket.') print('Be sure to drink liquids.') print('Bring a jacket.')

13 Exercise Write a program that: Requests the user’s name
Requests the user’s age Prints a message saying whether the user is eligible to vote or not >>> Enter your name: Marie Enter your age: 17 Marie, you can't vote. >>> ============RESTART================ Enter your age: 18 Marie, you can vote. name = input('Enter your name: ') age = eval(input('Enter your age: ')) if age < 18: print(name + ", you can't vote.") else: print(name + ", you can vote.")

14 Execution control structures
The one-way and two-way if statements are examples of execution control structures Execution control structures are programming language statements that control which statements are executed, i.e., the execution flow of the program The one-way and two-way if statements are, more specifically, conditional structures Iteration structures are execution control structures that enable the repetitive execution of a statement or a block of statements The for loop statement is an iteration structure that executes a block of code for every item of a sequence

15 for loop Executes a block of code for every item of a sequence If sequence is a string, items are its characters (single-character strings) >>> name = 'Apple' >>> for char in name: print(char) A p >>> name = 'Apple' >>> for char in name: print(char) >>> name = 'Apple' >>> for char in name: print(char) A p >>> name = 'Apple' >>> for char in name: print(char) A p >>> name = 'Apple' >>> for char in name: print(char) A p >>> name = 'Apple' >>> for char in name: print(char) >>> name = 'Apple' >>> for char in name: print(char) A p l >>> name = 'Apple' >>> for char in name: print(char) A p l e >>> name = 'Apple' >>> for char in name: print(char) A p l >>> name = 'Apple' >>> for char in name: print(char) A >>> name = 'Apple' >>> for char in name: print(char) A name = 'A p p l e' 'A' char = 'p' char = 'p' char = 'l' char = 'e' char =

16 for loop 'stop' 'desktop' 'post' 'top'
Executes a code block for every item of a sequence Sequence can be a string, a list, … Block of code must be indented for <variable> in <sequence>: <indented code block > <non-indented code block> for word in ['stop', 'desktop', 'post', 'top']: if 'top' in word: print(word) print('Done.') 'stop' word = 'desktop' word = >>> stop desktop >>> stop desktop top Done. >>> stop desktop >>> stop >>> stop desktop top >>> word = 'post' word = 'top'

17 Built-in function range()
Function range() is used to iterate over a sequence of numbers in a specified range To iterate over the n numbers 0, 1, 2, …, n-1 for i in range(n): To iterate over the n numbers i, i+1, i+2, …, n-1 for i in range(i, n): To iterate over the n numbers i, i+c, i+2c, i+3c, …, n-1 for i in range(i, n, c): >>> for i in range(2, 16, 4): print(i) 2 6 10 14 >>> >>> for i in range(0, 16, 4): print(i) 4 8 12 >>> >>> for i in range(2, 16, 10): print(i) 2 12 >>> >>> for i in range(2, 6): print(i) 2 3 4 5 >>> >>> for i in range(0): print(i) >>> >>> for i in range(2, 2): print(i) >>> >>> for i in range(2, 3): print(i) 2 >>> >>> for i in range(4): print(i) 1 2 3 >>> >>> for i in range(1): print(i) >>>

18 Exercise Write for loops that will print the following sequences:
0, 1, 2, 3, 4, 5, 6, 7, 8 , 9, 10 1, 2, 3, 4, 5, 6, 7, 8, 9 0, 2, 4, 6, 8 1, 3, 5, 7, 9 20, 30, 40, 50, 60

19 Defining new functions
A few built-in functions we have seen: abs(), max(), len(), sum(), print() >>> abs(-9) 9 >>> max(2, 4) 4 >>> lst = [2,3,4,5] >>> len(lst) >>> sum(lst) 14 >>> print() >>> def f(x): res = 2*x + 10 return x**2 + 10 >>> f(1) 11 >>> f(3) 19 >>> f(0) 10 >>> abs(-9) 9 >>> max(2, 4) 4 >>> lst = [2,3,4,5] >>> len(lst) >>> sum(lst) 14 >>> print() >>> >>> abs(-9) 9 >>> max(2, 4) 4 >>> lst = [2,3,4,5] >>> len(lst) >>> sum(lst) 14 >>> print() >>> def f(x): res = 2*x + 10 return x**2 + 10 >>> New functions can be defined using def def: function definition keyword f: name of function x: variable name for input argument def f(x): res = x**2 + 10 return res return: specifies function output

20 print() versus return def f(x): res = x**2 + 10 return res def f(x): res = x**2 + 10 print(res) >>> f(2) 14 >>> f(2) 14 >>> 2*f(2) 28 >>> f(2) 14 >>> 2*f(2) Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> 2*f(2) TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' >>> f(2) 14 Function returns value of res which can then be used in an expression Function prints value of res but does not return anything

21 Defining new functions
The general format of a function definition is a def <function name> (<0 or more variables>): <indented function body> b Let’s develop function hyp() that: Takes two numbers as input (side lengths a and b of above right triangle ) Returns the length of the hypotenuse c >>> hyp(3,4) 5.0 >>> [haɪ'pɑtənus] import math def hyp(a, b): res = math.sqrt(a**2 + b**2) return res import math def hyp(a, b): res = math.sqrt(a**2 + b**2) def hyp(a, b):

22 Exercise Write function hello() that:
takes a name (i.e., a string) as input prints a personalized welcome message Note that the function does not return anything >>> hello('Julie') Welcome, Julie, to the world of Python. >>> def hello(name): line = 'Welcome, ' + name + ', to the world of Python.' print(line) def hello(name): def hello(name): line = 'Welcome, ' + name + ', to the world of Python.’

23 Exercise Write function rng() that: takes a list of numbers as input
returns the range of the numbers in the list The range is the difference between the largest and smallest number in the list >>> rng([4, 0, 1, -2]) 6 >>> def rng(lst): res = max(lst) - min(lst) return res def rng(lst): def rng(lst): res = max(lst) - min(lst)

24 Comments and docstrings
Python programs should be documented So the developer who writes/maintains the code understands it So the user knows what the program does >>> help(f) Help on function f in module __main__: f(x) >>> help(f) Help on function f in module __main__: f(x) >>> def f(x): 'returns x**2 + 10' res = x**2 + 10 return res returns x**2 + 10 >>> Comments def f(x): res = x** # compute result return res # and return it Docstring def f(x): 'returns x**2 + 10' res = x** # compute result return res # and return it

25 Objects and classes 3 3.0 'three' [1, 2, 3]
>>> c = 'three' >>> d = [1, 2, 3] >>> type(a) <class 'int'> >>> type(b) <class 'float'> >>> type(c) <class 'str'> >>> type(d) <class 'list'> >>> a = [] >>> a = 3 >>> b = 3.0 >>> >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> d = [1, 2, 3] >>> >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> d = [1, 2, 3] >>> type(a) <class 'int'> >>> type(b) <class 'float'> >>> type(c) <class 'str'> >>> type(d) <class 'list'> >>> >>> a = 3 >>> In Python, every value, whether a simple integer value like 3 or a more complex value, such as the list ['hello', 4,  5]  is stored in memory as an object. Every object has a value and a type; It is the object that has a type, not the variable! int float str list 3 3.0 'three' [1, 2, 3] An object’s type determines what values it can have and how it can be manipulated Terminology: object X is of type int = object X belongs to class int

26 Class and class methods
Once again: In Python, every value is stored in memory as an object, every object belongs to a class (i.e., has a type), and the object’s class determines what operations can be performed on it We saw the operations that can be performed on classes int and float >>> pets = ['goldfish', 'cat', 'dog'] >>> pets.append('guinea pig') >>> pets.append('dog') >>> pets ['goldfish', 'cat', 'dog', 'guinea pig', 'dog'] >>> pets.count('dog') 2 >>> pets.remove('dog') ['goldfish', 'cat', 'guinea pig', 'dog'] >>> pets.reverse() ['dog', 'guinea pig', 'cat', 'goldfish'] >>> fish = ['goldfish'] >>> myPets = ['cat', 'dog'] >>> fish * 3 ['goldfish', 'goldfish', 'goldfish'] >>> pets = fish + myPets >>> pets ['goldfish', 'cat', 'dog'] >>> 'frog' in pets False >>> pets[-1] 'dog' >>> The list class supports: operators such as +, *, in, [], etc. methods such as append(), count(), remove(), reverse(), etc.

27 <variable> = <expression>
Assignment statement: a second look a b c d A variable does not exist before it is assigned 3 [1, 2, 3] >>> a Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> a NameError: name 'a' is not defined >>> a = 3 >>> b = >>> a Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> a NameError: name 'a' is not defined >>> a = 3 >>> b = >>> c = 'three' >>> a Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> a NameError: name 'a' is not defined >>> >>> a Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> a NameError: name 'a' is not defined >>> a = 3 >>> b = >>> c = 'three' >>> d = [1, 2] + [3] >>> a Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> a NameError: name 'a' is not defined >>> a = 3 'three' 3.3 <variable> = <expression> <expression> is evaluated and its value put into an object of appropriate type The object is assigned name <variable>

28 Mutable and immutable types
c d >>> a 3 >>> a 3 >>> a = 6 6 >>> d [1, 2, 3] >>> a 3 >>> a = 6 6 >>> a 3 >>> a = 6 6 >>> d [1, 2, 3] >>> d[1] = 7 [1, 7, 3] 3 [1, 7, 3] [1, 2, 3] 'three' 3.3 6 The object (3) referred to by variable a does not change; instead, a refers to a new object (6) Integers are immutable The object ([1, 2, 3]) referred to by d changes Lists are mutable

29 Assignment and mutability
c d >>> a 6 >>> b 3.3 >>> a 6 >>> b 3.3 >>> b = a >>> a = 9 >>> c = d >>> c [1, 7, 3] >>> a 6 >>> b 3.3 >>> b = a >>> a = 9 >>> c = d >>> c [1, 7, 3] >>> d[2] = 9 [1, 7, 9] >>> a 6 >>> b 3.3 >>> b = a >>> a = 9 >>> a 6 >>> b 3.3 >>> b = a 9 3 [1, 7, 9] [1, 7, 3] 'three' 3.3 6 c and d refer to the same list object a and b refer to the same integer object The list that c refers to changes; d refers to the same list object, so it changes too Because lists are mutable, a change to d affects c a now refers to a new object (9); b still refers to the old object (6) Because integers are immutable, a change to a does not affect the value of b

30 Swapping values a b tmp Want: a b Have: 3 6 3 6 >>> a 3
>>> tmp = b >>> b = a >>> a 3 >>> b 6 >>> tmp = b >>> b = a >>> a = tmp >>> a 3 >>> b 6 >>> a, b = b, a >>> a 3 >>> b 6 >>> b = a >>> a 3 >>> b 6 >>> a 3 >>> b 6 >>> tmp = b

31 Immutable parameter passing
x shell Function call g(a) 3 5 >>> a = 3 >>> g(a) >>> >>> a = 3 >>> >>> a = 3 >>> g(a) >>> def g(x): x = 5 def g(x): x = 5 def g(x): x = 5 Variable x inside g() refers to the object a refers to As if we executed x = a Function g() did not, and cannot, modify the value of a in the interactive shell. This is because a refers to an immutable object.

32 Mutable parameter passing
lst l shell Function call h(lst) [5,2,3] [1,2,3] >>> lst = [1,2,3] >>> h(lst) >>> >>> lst = [1,2,3] >>> h(lst) >>> >>> lst = [1,2,3] >>> def h(l): l[0] = 5 def h(l): l[0] = 5 def h(l): l[0] = 5 Variable l inside h() refers to the object lst refers to As if we executed l = lst Function h() did modify the value of lst in the interactive shell. This is because lst and l refer to an mutable object.

33 Exercise Write function swapFS() that: takes a list as input
swaps the first and second element of the list, but only if the list has at least two elements The function does not return anything >>> mylst = ['one', 'two', 'three'] >>> swapFS(mylst) >>> mylst ['two', 'one', 'three'] >>> mylst = ['one'] ['one'] >>> def swapFS(lst): if len(lst) > 1: lst[0], lst[1] = lst[1], lst[0] def swapFS(lst): def swapFS(lst): if len(lst) > 1:

34 Questions Thank You!


Download ppt "Chapter 3 Instructor: Zhuojun Duan"

Similar presentations


Ads by Google