1. Hello, Python
# Intro
We'll start with a brief overview of Python syntax, variable assignment, and arithmetic operators.
# Hello, Python!
spam_amount = 0 #Variable assignment
print(spam_amount)
# Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam)
spam_amount = spam_amount + 4
2
3
4
5
Variable assignment :spam_amount = 0
- 无需声明变量
- 无需设置type
if spam_amount > 0:
print("But I don't want ANY spam!")
viking_song = "Spam Spam Spam"
print(viking_song)
2
3
4
5
The colon (:
) at the end of the if
line indicates that a new "code block" is starting. Subsequent lines which are indented are part of that code block.
viking_song = "Spam " * spam_amount
print(viking_song)
2
Python offers a number of cheeky little time-saving tricks like this where operators like *
and +
have a different meaning depending on what kind of thing they're applied to. (The technical term for this is operator overloading (opens new window)(运算符重载))
# Numbers and arithmetic in Python
type(19.95)
type()
is very useful to be able to ask Python "what kind of thing is this?".
Operator | Name | Description |
---|---|---|
a + b | Addition | Sum of a and b |
a - b | Subtraction | Difference of a and b |
a * b | Multiplication(乘法) | Product of a and b |
a / b | True division(除法) | Quotient of a and b |
a // b | Floor division | Quotient of a and b , removing fractional parts(除法取整数部分) |
a % b | Modulus(余数) | Integer remainder after division of a by b |
a ** b | Exponentiation(指数) | a raised to the power of b |
-a | Negation | The negative of a |
# Order of operations(优先级)
hat_height_cm = 25
my_height_cm = 190
# How tall am I, in meters, when wearing my hat?
total_height_meters = hat_height_cm + my_height_cm / 100
print("Height in meters =", total_height_meters, "?")
total_height_meters = (hat_height_cm + my_height_cm) / 100
print("Height in meters =", total_height_meters)
2
3
4
5
6
7
8
Parentheses are your useful here. You can add them to force Python to evaluate sub-expressions in whatever order you want.
# Builtin functions for working with numbers
print(min(1, 2, 3))
print(max(1, 2, 3))
2
min
and max
return the minimum and maximum of their arguments
print(abs(32))
print(abs(-32))
2
abs
returns the absolute value of it argument
print(float(10))
print(int(3.33))
# They can even be called on strings!
print(int('807') + 1)
2
3
4
In addition to being the names of Python's two main numerical types, int
and float
can also be called as functions which convert their arguments to the corresponding type
# Exercise: Syntax, Variables, and Numbers
Try your first Python programming exercise (opens new window)
# 0.
What is your favorite color?
# create a variable called color with an appropriate value on the line below
# (Remember, strings in Python must be enclosed in 'single' or "double" quotes)
color = "blue"
q0.check()
2
3
4
# 1.
pi = 3.14159 # approximate
diameter = 3
# Create a variable called 'radius' equal to half the diameter
radius = diameter / 2
# Create a variable called 'area', using the formula for the area of a circle: pi times the radius squared
area = pi * radius ** 2
q1.check()
2
3
4
5
6
7
8
# 2.
Add code to the following cell to swap variables a
and b
(so that a
refers to the object previously referred to by b
and vice versa).
####### Setup code - don't touch this part ###############
# If you're curious, these are examples of lists. We'll talk about
# them in depth a few lessons from now. For now, just know that they're
# yet another type of Python object, like int or float.
a = [1, 2, 3]
b = [3, 2, 1]
q2.store_original_ids()
#################################################
# Your code goes here. Swap the values to which a and b refer.
# If you get stuck, you can always uncomment one or both of the lines in
# the next cell for a hint, or to peek at the solution.
tmp = a
a = b
b = tmp
#################################################
q2.check()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Solution: The most straightforward solution is to use a third variable to temporarily store one of the old values:
tmp = a
a = b
b = tmp
2
3
If you've read lots of Python code, you might have seen the following trick to swap two variables in one line:
a, b = b, a
We'll demystify this bit of Python magic later when we talk about tuples.
# 3.
a) Add parentheses to the following expression so that it evaluates to 1.
(5 - 3) // 2
b) 🌶️ Add parentheses to the following expression so that it evaluates to 0
(8 - 3) * (2 - (1 + 1))
# 4.
Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves. For the sake of their friendship, any candies left over will be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.
Write an arithmetic expression below to calculate how many candies they must smash for a given haul.
# Variables representing the number of candies collected by alice, bob, and carol
alice_candies = 121
bob_candies = 77
carol_candies = 109
# Your code goes here! Replace the right-hand side of this assignment with an expression
# involving alice_candies, bob_candies, and carol_candies
to_smash = (alice_candies . bob_candies + carol_candies) % 3
q4.check()
2
3
4
5
6
7
8
9
10