0% found this document useful (0 votes)
91 views51 pages

Python Chapter+02+Slides

Uploaded by

daiadams
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
91 views51 pages

Python Chapter+02+Slides

Uploaded by

daiadams
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 51

Chapter 2

How to write
your first programs

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 1
Applied objectives
1. Use the IDLE shell to test numeric and string operations.
2. Code, test, and debug programs that require the skills that you’ve
learned in this chapter. That includes the use of:
comments for documenting your code and commenting out
statements
implicit and explicit continuation
str, int, and float values and variables
multiple assignment
arithmetic expressions
string concatenation with the + operator and f-strings
special characters in strings
the built-in print(), input(), str(), float(), int(), and round()
functions
function chaining

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 2
Knowledge objectives (part 1)
1. Describe the use of indentation when coding Python statements.
2. Describe the use of Python comments, including “commenting
out” portions of Python code.
3. Describe these data types: str, int, float.
4. List two recommendations for creating a Python variable name.
5. Distinguish between underscore notation (snake case) and camel
case.
6. Describe the evaluation of an arithmetic expression, including
order of precedence and the use of parentheses.
7. Distinguish among these arithmetic operators: /, //, and %.
8. Describe the use of += operator in a compound arithmetic
expression.
9. Describe the use of escape sequences when working with strings.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 3
Knowledge objectives (part 2)
10.Describe the syntax for calling one of Python’s built-in
functions.
11. Describe the use of the print(), input(), str(), float(), int(), and
round() functions.
12.Describe what it means to chain functions.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 4
The Python code for a Test Scores program
#!/usr/bin/env python3

counter = 0
score_total = 0
test_score = 0

while test_score != 999:


test_score = int(input("Enter test score: "))
if test_score >= 0 and test_score <= 100:
score_total += test_score
counter += 1

average_score = round(score_total / counter)

print("Total Score: " + str(score_total))


print("Average Score: " + str(average_score))

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 5
An indentation error
print("Total Score: " + str(score_total))
print("Average Score: " + str(average_score))

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 6
Two ways to continue one statement over two
or more lines
Implicit continuation
print("Total Score: " + str(score_total)
+ "\nAverage Score: " + str(average_score))

Explicit continuation
print("Total Score: " + str(score_total) \
+ "\nAverage Score: " + str(average_score))

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 7
Coding rules
 Python relies on proper indentation. Incorrect indentation causes
an error.
 The standard indentation is four spaces.
 With implicit continuation, you can divide statements after
parentheses, brackets, and braces, and before or after operators
like plus or minus signs.
 With explicit continuation, you can use the \ character to divide
statements anywhere in a line.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 8
The Test Scores program with comments (part 1)
#!/usr/bin/env python3

# This is a tutorial program that illustrates the use of


# the while and if statements

# initialize variables
counter = 0
score_total = 0
test_score = 0

# get scores
while test_score != 999:
test_score = int(input("Enter test score: "))
if test_score >= 0 and test_score <= 100:
score_total += test_score # add score to total
counter += 1 # add 1 to counter

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 9
The Test Scores program with comments (part 2)
# calculate average score
#average_score = score_total / counter
#average_score = round(average_score)
average_score = round( # implicit continuation
score_total / counter) # same results as
# commented out statements

# display the result


print("======================")
print("Total Score: " + str(score_total) # implicit cont.
+ "\nAverage Score: " + str(average_score))

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 10
Guidelines for using comments
 Use comments to describe portions of code that are hard to
understand, but don’t overdo them.
 Use comments to comment out (or disable) statements that you
don’t want to test.
 If you change the code that’s described by comments, change the
comments too.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 11
The syntax for calling any function
function_name([arguments])

The print() function


print([data])

A script with three statements


print("Hello out there!")
print()
print("Goodbye!")

The console after the program runs


Hello out there!

Goodbye!

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 12
Three Python data types
Data type Name Examples
str String "Mike" "40"
'Please enter name: '

int Integer 21 450 0 -25

float Floating-point 21.9 450.25


0.01 -25.2 3.1416

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 13
Code that initializes variables
first_name = "Mike" # sets first_name to a str of "Mike"
quantity1 = 3 # sets quantity1 to an int of 3
quantity2 = 5 # sets quantity2 to an int of 5
list_price = 19.99 # sets list_price to a float of 19.99

Code that assigns new values


to the variables above
first_name = "Joel" # sets first_name to a str of "Joel"
quantity1 = 10 # sets quantity1 to an int of 10
quantity1 = quantity2 # sets quantity1 to an int of 5
quantity1 = "15" # sets quantity1 to a str of "15"

Code that assigns values to two variables


quantity1 = 3, list_price = 19.99

Code that causes an error due to incorrect case


quantity1 = Quantity2 # NameError: 'Quantity2' is not defined

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 14
How to code literal values
 To code a literal value for a string, enclose the characters of the
string in single or double quotation marks. This is called a string
literal.
 To code a literal value for a number, code the number without
quotation marks. This is called a numeric literal.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 15
Rules for naming variables
 A variable name must begin with a letter or underscore.
 A variable name can’t contain spaces, punctuation, or special
characters other than the underscore.
 A variable name can’t begin with a number, but can use numbers
later in the name.
 A variable name can’t be the same as a keyword that’s reserved
by Python.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 16
Python keywords
and except lambda while
as False None with
assert finally nonlocal yield
break for not
class from or
continue global pass
def if raise
del import return
elif in True
else is try

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 17
Two naming styles for variables
variable_name # underscore notation
variableName # camel case

Recommendations for naming variables


 Start all variable names with a lowercase letter.
 Use underscore notation or camel case.
 Use meaningful names that are easy to remember.
 Don’t use the names of built-in functions, such as print().

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 18
Python’s arithmetic operators
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
// Integer division
% Modulo / Remainder
** Exponentiation

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 19
Examples with two operands
Example Result
5 + 4 9
25 / 4 6.25
25 // 4 6
25 % 4 1
3 ** 2 9

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 20
The order of precedence
Order Operators Direction
1 ** Left to right
2 * / // % Left to right
3 + - Left to right

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 21
Examples that show the order of precedence
and use of parentheses
Example Result
3 + 4 * 5 23 (the multiplication is done first)
(3 + 4) * 5 35 (the addition is done first)

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 22
Code that calculates sales tax
subtotal = 200.00
tax_percent = .05
tax_amount = subtotal * tax_percent # 10.0
grand_total = subtotal + tax_amount # 210.0

Code that calculates the perimeter of a rectangle


width = 4.25
length = 8.5
perimeter = (2 * width) + (2 * length) # 25.5

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 23
The most useful compound assignment operators
+=
-=
*=

Two ways to increment the number in a variable


counter = 0
counter = counter + 1 # counter = 1
counter += 1 # counter = 2

Code that adds two numbers to a variable


score_total = 0 # score_total = 0
score_total += 70 # score_total = 70
score_total += 80 # score_total = 150

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 24
More compound assignment operator examples
total = 1000.0
total += 100.0 # total = 1100.0

counter = 10
counter -= 1 # counter = 9

price = 100
price *= .8 # price = 80.0

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 25
A floating-point result that isn’t precise
subtotal = 74.95 # subtotal = 74.95
tax = subtotal * .1 # tax = 7.495000000000001

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 26
The Python shell after some numeric testing

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 27
How to use the shell
 To test a statement, type it at the prompt and press the Enter key.
You can also type the name of a variable at the prompt to see
what its value is.
 Any variables that you create remain active for the current
session. As a result, you can use them in statements that you
enter later in the same session.
 To retype your previous entry, press Alt+p (Windows) or
Command+p (macOS).
 To cycle through all of the previous entries, continue pressing the
Alt+p (Windows) or Command+p (macOS) keystroke until the
entry you want is displayed at the prompt.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 28
How to assign strings to variables
first_name = "Bob" # Bob
last_name = 'Smith' # Smith
name = "" # (empty string)
name = "Bob Smith" # Bob Smith

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 29
How to join strings
With the + operator
name = last_name + ", " + first_name
# name is "Smith, Bob"
With an f-string
name = f"{last_name}, {first_name}"
# name is "Smith, Bob"

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 30
The str() function
str(data)

How to join a string and a number


name = "Bob Smith"
age = 40
With the + operator and the str() function
message = name + " is " + str(age) + " years old."
With an f-string
message = f"{name} is {age} years old."
# str() function not needed

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 31
Common escape sequences
Sequence Character
\n New line
\t Tab
\r Return
\" Quotation mark in a double quoted string
\' Quotation mark in a single quoted string
\\ Backslash

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 32
Implicit continuation of a string
With the + operator
print("Name: " + name + "\n" +
"Age: " + str(age))
With an f-string
print(f"Name: {name}\n"
f"Age: {age}")

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 33
The new line character
print("Title: Python Programming\nQuantity: 5")

Displayed on the console


Title: Python Programming
Quantity: 5

The tab and new line characters


print("Title:\t\tPython Programming\nQuantity:\t5")

Displayed on the console


Title: Python Programming
Quantity: 5

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 34
The backslash in a Windows path
print("C:\\murach\\python")

Displayed on the console


C:\murach\python

Four ways to include quotation marks in a string


"Type \"x\" to exit" # String is: Type "x" to exit.
'Type \'x\' to exit' # String is: Type 'x' to exit.
"Type 'x' to exit" # String is: Type 'x' to exit.
'Type "x" to exit' # String is: Type "x" to exit.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 35
The Python shell with string testing

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 36
Review of how to use the shell
 To test a statement, type it at the prompt and press the Enter key.
You can also type the name of a variable at the prompt to see
what its value is.
 Any variables that you create remain active for the current
session. As a result, you can use them in statements that you
enter later in the same session.
 To retype the previous statement on Windows, press Alt+p. To
cycle through all of the previous statements, continue pressing
Alt+p. On macOS, use Command+p.

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 37
The syntax of the print() function
print(data[, sep=' '][, end='\n'])

Three print() functions


print(19.99) # 19.99
print("Price:", 19.99) # Price: 19.99
print(1, 2, 3, 4) # 1 2 3 4

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 38
Two ways to get the same result
A print() function that receives four arguments
print("Total Score:", score_total,
"\nAverage Score:", average_score)

A print() function that receives one string


as the argument
print(f"Total Score: {score_total}"
f"\nAverage Score: {average_score}")

The data that’s displayed by both functions


Total Score: 240
Average Score: 80

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 39
Examples that use the sep and end arguments
print(1,2,3,4,sep=' | ') # 1 | 2 | 3 | 4
print(1,2,3,4,end='!!!') # 1 2 3 4!!!

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 40
The input() function
input([prompt])

Code that gets string input from the user


first_name = input("Enter your first name: ")
print(f"Hello, {first_name}!")

The console
Enter your first name: Mike
Hello, Mike!

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 41
Another way to get input from the user
print("What is your first name?")
first_name = input()
print(f"Hello, {first_name}!")

The console
What is your first name?
Mike
Hello, Mike!

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 42
Code that attempts to get numeric input
score_total = 0
score = input("Enter your score: ")
score_total += score # causes an error
# because score is a string

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 43
Three functions for working with numbers
int(data)
float(data)
round(number [,digits])

Code that causes an exception


x = 15
y = "5"
z = x + y # TypeError: can't add an int to a str

How using the int() function fixes the exception


x = 15
y = "5"
z = x + int(y) # z is 20

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 44
Code that gets an int value from the user
quantity = input("Enter the quantity: ") # get str
type
quantity = int(quantity) # convert to int type

How to use chaining to get the value in one statement


quantity = int(input("Enter the quantity: "))

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 45
Code that gets a float value from the user
price = input("Enter the price: ") # get str type
price = float(price) # convert to float type

How to use chaining to get the value in one statement


price = float(input("Enter the price: "))

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 46
Code that uses the round() function
miles_driven = 150
gallons_used = 5.875
mpg = miles_driven / gallons_used # 25.53191489361702
mpg = round(mpg, 2) # 25.53

How to combine the last two statements


mpg = round(miles_driven / gallons_used, 2)

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 47
The console for the Miles Per Gallon program
The Miles Per Gallon program

Enter miles driven: 150


Enter gallons of gas used: 35.875

Miles Per Gallon: 4.18

Bye!

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 48
The code for the Miles Per Gallon program
#!/usr/bin/env python3

# display a title
print("The Miles Per Gallon program")
print()

# get input from the user


miles_driven = float(input("Enter miles driven:\t\t"))
gallons_used = float(input(
"Enter gallons of gas used:\t"))

# calculate and round miles per gallon


mpg = miles_driven / gallons_used
mpg = round(mpg, 2)

# display the result


print()
print(f"Miles Per Gallon:\t\t{mpg}")
print()
print("Bye!")

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 49
The console for the Test Scores program
The Test Scores program

Enter 3 test scores


======================
Enter test score: 75
Enter test score: 85
Enter test score: 95
======================
Total Score: 255
Average Score: 85

Bye!

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 50
The code for the Test Scores program
#!/usr/bin/env python3

# display a title
print("The Test Scores program")
print()
print("Enter 3 test scores")
print("======================")

# get scores from the user and accumulate the total


total_score = 0 # initialize the total_score variable
total_score += int(input("Enter test score: "))
total_score += int(input("Enter test score: "))
total_score += int(input("Enter test score: "))

# calculate average score


average_score = round(total_score / 3)

# format and display the result


print("======================")
print("Total Score: ", total_score,
"\nAverage Score:", average_score)
print()
print("Bye!")

© 2021, Mike Murach & Associates, Inc.


Murach's Python Programming (2nd Ed.) C2, Slide 51

You might also like