Variables and expressions · 变量与表达式
Variables hold values
- A variable stores a value so you can use it later.
- In Python you write
score = 10. The=means "store on the left". - You can change a variable by storing a new value into it.
变量保存值
- 变量(variable)用来存储一个值,方便以后使用。
- 在 Python 里写作
score = 10。=的意思是"存到左边"。 - 你可以通过把一个新值存进去来改变一个变量。
score = 10
score = score + 5
print(score)
Arithmetic operators
- The usual operators are
+,-,*,/. //gives whole-number division (no remainder);**is power.%gives the remainder left after dividing.
算术运算符
- 常用的运算符是
+、-、*、/。 //表示整除(不要余数);**表示乘方。%表示相除后剩下的余数。
print(17 // 5) # whole 5s that fit = 3
print(17 % 5) # what is left over = 2
print(2 ** 3) # 2 to the power 3 = 8
Relational operators
- These compare two values and give
TrueorFalse. ==is "equal",!=is "not equal".<,>,<=,>=compare size.
关系运算符
- 这些运算符比较两个值,给出
True或False。 ==是"等于",!=是"不等于"。<、>、<=、>=比较大小。
print(5 == 5) # True
print(5 != 3) # True
print(7 < 2) # False
Logical operators
andisTrueonly when both sides areTrue.orisTruewhen at least one side isTrue.notflipsTruetoFalseand back.
逻辑运算符
and只有在两边都为True时才是True。or在至少一边为True时就是True。not把True变成False,反过来也一样。
print(True and False) # False
print(True or False) # True
print(not True) # False
In AP CSP pseudocode
- The AP exam uses its own pseudocode, not Python. The ideas are the same.
- Assignment uses a left arrow.
MODis the remainder.DISPLAYprints.
在 AP CSP 伪代码中
- AP 考试用它自己的伪代码(pseudocode),不是 Python。思想是一样的。
- 赋值用一个向左的箭头。
MOD是余数。DISPLAY用来打印。
Python AP CSP pseudocode
score = 10 score ← 10
17 % 5 17 MOD 5
print(score) DISPLAY(score)
a == b a = b
a and b a AND b
Common mistakes
- Give a variable a value before you use it.
input()returns text — convert withint(...)for numbers.
常见错误
- 先给变量赋值再使用。
input()返回文本——需要数字时用int(...)转换。
Now you try
- Type your code below and press Run to see the output.
- Press Check answer to test it.
现在轮到你
- 在下面输入你的代码,按运行查看输出。
- 按检查答案来测试它。
Variables hold one value · 变量保存一个值
A variable is a named box; assigning replaces what it holds. · 变量是一个带名字的盒子;赋值会替换里面的内容。
Use % (MOD) to print the remainder when 29 is divided by 4. Your program should print just the number. · 用 %(MOD)打印 29 除以 4 的余数。你的程序只需要打印这个数字。
Click Run to see the output here. · 点击“运行”查看此处输出。
You pack 50 apples into boxes of 6. Store the number of full boxes in · 入 boxes using //, and the apples left over in · 入 leftover using %. · 你把 50 个苹果装进每箱 6 个的箱子。用 // 把装满的箱子数存进 boxes,用 % 把剩下的苹果数存进 leftover。
Click Run to see the output here. · 点击“运行”查看此处输出。
n is 17. Store True/False for "is n odd?" in is_odd (use %), and for "is n between 10 and 20?" in in_range (use >, <, and and). · n 是 17。把“n 是奇数吗?”的 True/False 存进 is_odd(用 %),把“n 在 10 和 20 之间吗?”存进 in_range(用 >、< 和 and)。
Click Run to see the output here. · 点击“运行”查看此处输出。