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.
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.
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.
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.
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.
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. Сохраните результат «True/False является ли n нечетным?» в is_odd (используйте %), а «n находится ли между 10 и 20?» в in_range (используйте >, < и and).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.