Notes for Ch 2 Lab
In Python, a literal is a notation representing a fixed value in source code
5 – integer literal
“Hello” – String literal
True – Boolean literal
Print Literals
To print a literal, you simply pass it to the print() function
print(5) # Output: 5
print(“Hello”) # Output: Hello
print(True) # Output: True
String Literals
You can use single or double quotes for string literals:
print(‘Single quotes’)
print(“Double quotes”)
For multi-line strings, use triple quotes:
print("””This is a
multi-line
string”””)
Escape Sequence
Escape sequences allow you to include special characters in string literals (begin
with backslash):
print(“Hello\nWorld”) # Output: Hello
# World
F-strings (Formatted String Literals)
F-strings (since Python 3.6) provide a concise way to embed expressions within
string literals:
name = “Alice”
print(f”Hello, {name}”) # Output: Hello, Alice
Operators.py – have students calculate answers by hand then run program
# This program demonstrates the precedence and associativity of operators.
number1 = 20
number2 = 5
number3 = 17
answer1 = number1 * number2 + number3
print(f"Answer 1: {answer1}")
answer2 = number1 * (number2 + number3)
print(f"Answer 2: {answer2}")
answer3 = number1 + number2 - number3
print(f"Answer 3: {answer3}")
answer4 = number1 + (number2 - number3)
print(f"Answer 4: {answer4}")
answer5 = number1 + number2 * number3
print(f"Answer 5: {answer5}")
answer6 = number3 / number2
print(f"Answer 6: {answer6}")
Paint.py – Build a program to calculate the number of gallons of paint needed. Each
gallon of paint will cover 150 square feet.
# Calculates the number of gallons of paint needed.
# Each gallon of paint will cover 150 square feet.
height1 = 9
height2 = 9
width1 = 19.5
width2 = 20.0
squareFeet = (width1 * height1 + width2 * height2) * 2
numGallons = squareFeet / 150
print(f"Number of Gallons: {numGallons:.2f}")
(If time allows, reduce squarefeet by size of doors and windows.)
Temperature.py – Write a program that converts Fahrenheit to Celsius
"""
Temperature.py - This Python program converts a Fahrenheit temperature to
Celsius.
Input: Interactive
Output: Fahrenheit temperature followed by Celsius temperature
"""
# Get interactive user input.
fahrenheitString = input("Enter Fahrenheit temperature: ")
# Convert String to float.
fahrenheit = float(fahrenheitString)
# Calculate celsius.
celsius = (fahrenheit - 32) * (5/9)
# Output.
print(f"Fahrenheit temperature: {fahrenheit:.2f}") # Two digits past the decimal
point
print(f"Celsius temperature: {celsius:.2f}")