0% found this document useful (0 votes)
7 views

2 - Basic Python Prgramming

Uploaded by

chwaineli
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

2 - Basic Python Prgramming

Uploaded by

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

How to write

your first programs


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

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


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))

Technical Programming II - Python Basics


AN INDENTATION ERROR
print("Total Score: " + str(score_total))
print("Average Score: " + str(average_score))

Technical Programming II - Python Basics


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))

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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))

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


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!

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


TWO NAMING STYLES FOR VARIABLES
variable_name # underscore notation
(snake case)
variableName # camel case

Snake case vs 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().

Technical Programming II - Python Basics


PYTHON’S ARITHMETIC OPERATORS
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
// Integer division
% Modulo / Remainder
** Exponentiation

Technical Programming II - Python Basics


EXAMPLES WITH TWO OPERANDS
Example Result
5 + 4 9
25 / 4 6.25
25 // 4 6
25 % 4 1
3 ** 2 9

Technical Programming II - Python Basics


THE ORDER OF PRECEDENCE
Order Operators Direction
1 ** Left to right
2 * / // % Left to right
3 + - Left to right

Technical Programming II - Python Basics


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)

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


A FLOATING-POINT RESULT THAT ISN’T PRECISE
subtotal = 74.95 # subtotal = 74.95
tax = subtotal * .1 # tax = 7.495000000000001

Technical Programming II - Python Basics


THE PYTHON SHELL AFTER SOME NUMERIC
TESTING
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.

Technical Programming II - Python Basics


HOW TO ASSIGN STRINGS TO VARIABLES
first_name = "Bob" # Bob
last_name = 'Smith' # Smith
name = "" # (empty string)
name = "Bob Smith" # Bob Smith

Technical Programming II - Python Basics


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"

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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}")

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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.

Technical Programming II - Python Basics


THE PYTHON SHELL WITH STRING TESTING
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.

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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!!!

Technical Programming II - Python Basics


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!

Technical Programming II - Python Basics


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!

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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

Technical Programming II - Python Basics


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: "))

Technical Programming II - Python Basics


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: "))

Technical Programming II - Python Basics


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)

Technical Programming II - Python Basics


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!

Technical Programming II - Python Basics


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!")

Technical Programming II - Python Basics


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!

Technical Programming II - Python Basics


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!")

Technical Programming II - Python Basics

You might also like