state = "Michigan"
population = 10_077_331
electoral_votes = 15
print(type(state))
print(type(population))
print(type(electoral_votes))<class 'str'>
<class 'int'>
<class 'int'>
Variables, types, strings, booleans, if statements
These are reference solutions. There’s often more than one right answer — if your version produces the same output, that’s what matters.
state = "Michigan"
population = 10_077_331
electoral_votes = 15
print(type(state))
print(type(population))
print(type(electoral_votes))<class 'str'>
<class 'int'>
<class 'int'>
type() returns the class of the object.
vote_share_str = "52.3"
vote_share = float(vote_share_str)
margin = vote_share - (100 - vote_share)
print(f"Margin of victory: {margin:.1f} points")Margin of victory: 4.6 points
Two-party share assumption means the other candidate got 100 - vote_share. Could also compute as 2 * vote_share - 100.
{margin.1f} looks weird, and isn’t something we covered in class. You don’t need it - it’s just rounding to the first decimal place for interpretability.
name = "Senator Bernie Sanders"
print(name[0]) # 'S'
print(name[8:14]) # 'Bernie'
print(name[15:]) # 'Sanders'
print(name[-7:]) # 'Sanders' — same result, no counting requiredS
Bernie
Sanders
Sanders
Negative indices count from the end. [-7:] is “give me everything from 7 characters before the end onward.”
candidate = "Smith"
party = "Democratic"
vote_share = 0.523
state = "Ohio"
print(f"{candidate} ({party}) won {state} with {vote_share:.1%} of the vote.")Smith (Democratic) won Ohio with 52.3% of the vote.
The format spec :.1% does two things: multiplies by 100 and rounds to one decimal place, then appends a %.
print(5 == 5.0) # True — Python compares numerically across int and float
print("Democrat" == "democrat") # False — string equality is case-sensitive
print(60 > 50 and 60 < 70) # True
print(not (50 > 100)) # True
print(0.49 + 0.51 == 1.0) # False (!)True
False
True
True
True
Computers store decimals in binary, and 0.49 and 0.51 don’t have exact binary representations — they’re approximations. The sum is very close to 1.0 but not exactly equal. Standard advice: when comparing floats, check whether the absolute difference is below a small tolerance, not strict equality. (abs(a - b) < 1e-9 is a common pattern.)
turnout = float(input("Enter turnout percentage: "))
if turnout > 60:
print("High turnout")
elif turnout >= 40:
print("Moderate turnout")
else:
print("Low turnout")candidate_a = "Adams"
candidate_b = "Burr"
candidate_c = "Carroll"
votes_a = 4_125
votes_b = 3_980
votes_c = 1_245
total = votes_a + votes_b + votes_c
share_a = votes_a / total
share_b = votes_b / total
share_c = votes_c / total
print(f"{candidate_a}: {share_a:.1%}")
print(f"{candidate_b}: {share_b:.1%}")
print(f"{candidate_c}: {share_c:.1%}")
if share_a > 0.50:
print("Adams wins!")
else:
print("Runoff required.")Adams: 44.1%
Burr: 42.6%
Carroll: 13.3%
Runoff required.