Variables let you keep calculated results. In Python you assign values with =.
Basics of assignment #
message = "Hello"
count = 3
pi = 3.14159
The value on the right-hand side is stored in the variable on the left. Reassigning overwrites the previous value.
count = count + 1
print(count) # 4
=means “assign the right-hand side to the left-hand side”. It is different from the mathematical equality sign.
Rules for naming variables #
- Use letters (a–z, A–Z), digits, and underscores
_ - The name cannot start with a digit
- Names are case-sensitive (
Valueandvalueare different)
Python reserves keywords (if, for, while, etc.) and you cannot use them as variable names. Check them with keyword.kwlist.
import keyword
keyword.kwlist
Choose descriptive names to make code readable.
tax_ratecommunicates more thanvalue.
Multiple assignment and swapping values #
You can assign to several variables at once.
x, y = 10, 20
Swapping becomes simple too.
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
Python lets you swap safely without a temporary variable—one of its beloved features.
Dynamic typing #
Python uses dynamic typing; a variable can hold values of different types over time.
value = 10 # int
value = "ten" # str
Changing types unexpectedly can introduce bugs. While learning, stick to one kind of value per variable.
Try it yourself #
- Create variables
name,age, andcity, assign your own information, andprintthem. - Assign two numbers to
aandband write code that swaps their values. - Try to use a keyword as a variable name and see what happens.
参考リンク
Next you’ll work with strings and basic input/output to build interactive programs.