此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
变量保存值
- 变量(variable)用来存储一个值,方便以后使用。
- 在 Python 里写作
score = 10。=的意思是"存到左边"。 - 你可以通过把一个新值存进去来改变一个变量。
English
score = 10
score = score + 5
print(score)
算术运算符
- 常用的运算符是
+、-、*、/。 //表示整除(不要余数);**表示乘方。%表示相除后剩下的余数。
English
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
关系运算符
- 这些运算符比较两个值,给出
True或False。 ==是"等于",!=是"不等于"。<、>、<=、>=比较大小。
English
print(5 == 5) # True
print(5 != 3) # True
print(7 < 2) # False
逻辑运算符
and只有在两边都为True时才是True。or在至少一边为True时就是True。not把True变成False,反过来也一样。
English
print(True and False) # False
print(True or False) # True
print(not True) # False
在 AP CSP 伪代码中
- AP 考试用它自己的伪代码(pseudocode),不是 Python。思想是一样的。
- 赋值用一个向左的箭头。
MOD是余数。DISPLAY用来打印。
English
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
常见错误
- 先给变量赋值再使用。
input()返回文本——需要数字时用int(...)转换。
现在轮到你
- 在下面输入你的代码,按运行查看输出。
- 按检查答案来测试它。
探索
Variables hold one value
A variable is a named box; assigning replaces what it holds.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Use % (MOD) to print the remainder when 29 is divided by 4. Your program should print just the number.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
You pack 50 apples into boxes of 6. Store the number of full boxes 入 boxes using //收集和使用数据,并且 apples left over 入 leftover using %.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
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).
点击“运行”查看此处输出。