Notes
Variables and types
- A variable stores a value:
score = 10. Reassignment replaces the old value. Names are case sensitive and cannot start with a digit. - Main types:
int,float,str,bool. Convert withint(),float(),str(). Check withtype().
Operators
+ - * /and//(floor division),%(remainder),**(power)./always gives a float.- Order: parentheses,
**, then* / // %, then+ -.
Input and output
print()shows output.input()always returns a string, so wrap it inint()orfloat()for math.- f-strings such as
f"Hi {name}"insert values into text.
Strings
- Indexes start at 0; negative indexes count from the end. Slices
s[a:b]stop before b. len(s),+(join),*(repeat), and methods like.upper()and.lower().
price = 4
count = 3
print(price * count, "total")
This prints 12 total.
Topics in this unit
Each topic has its own short notes and practice.
Practice
x = 3; y = 4; print(x * y - 2) display?3 * 4 = 12, and 12 - 2 = 10.
print(9 / 3) display?The / operator always returns a float, so the result is 3.0.
print("ab" * 3) display?Multiplying a string repeats it.
n = input("Number: ") and the user types 5. What is type(n)?input() returns a string regardless of what is typed.
word = "banana"; print(word[1:4]) display?Indexes 1, 2, 3 are a, n, a. The slice stops before index 4.
print(23 % 6) display?6 goes into 23 three times (18), leaving a remainder of 5.
Free response
Write your answer first, then open the scoring guide.
Free-response question
A store clerk program asks for a price and a quantity and prints the total cost.
(a) Write Python that reads the price as a decimal number and the quantity as a whole number.
Show the answer and scoring guide
price = float(input("Price: "))
qty = int(input("Quantity: "))
Check off the points you earned:
(b) Write a line that stores the total in a variable named total and prints it in a sentence using an f-string.
Show the answer and scoring guide
total = price * qty
print(f"Total: {total}")
Check off the points you earned:
(c) The user enters 2.5 for the price and 4 for the quantity. What is printed, and what type is the value of total?
Show the answer and scoring guide
It prints Total: 10.0. The type is float, because a float multiplied by an int gives a float.
Check off the points you earned: