Variables
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
A box with a name
- A variable is a named box that holds a value.
- You put a value in the box, then use the name later.
- The value can be a number or a string.
日本語
名前のついた箱
- 変数 は値を格納する名前のついた箱です。
- 箱に値を入れ、後でその名前を使って使用します。
- 値は数値やストリングであることができます。
English
Make a variable
- Write
name = valueto store a value. - The name is on the left. The value is on the right.
=means "store this value", not "is equal to".
日本語
変数の作成
- 値を格納するには
name = valueを書きます。 - 名前 は左側に、値 は右側に来ます。
=は「等しい」ではなく、「この値を格納する」という意味です。
city = "Paris"
print(city)
English
Naming rules
- Use letters, digits, and the underscore
_. - A name cannot start with a digit and cannot have spaces.
- Names are case-sensitive:
scoreandScoreare different. - Pick clear names like
ageortotal_score.
日本語
名前の命名ルール
- 英字母、数字、アンダーバー
_を使います。 - 名前は数字で始められず、スペースを含めてはいけません。
- 名前は大文字・小文字を区別します:
scoreとScoreは別物です。 ageやtotal_scoreのように明確な名前を選びましょう。
English
Change a variable
- You can store a new value at any time.
- The new value replaces the old one.
- The name still points to one value — the latest one.
日本語
変数の値を変える
- いつでも新しい値を格納できます。
- 新しい値は古い値を上書きします。
- 名前はStill一つの値を指しています——最新のものです。
Explore · 探索
A variable is a labelled box
Step through the program. Each line stores a value in a named box; reassigning count overwrites its box. One name, one current value.
count = 1
count = 2
print(count)
English
Constants
- A constant is a value that should not change.
- Python has no special keyword for it.
- By convention, we write constant names in
UPPERCASE.
日本語
定数
- 定数 は変更してはいけない値です。
- Python に特別なキーワードはありません。
- 慣例として、定数の名前は
UPPERCASE(大文字)で書きます。
PI = 3.14159
print(PI)
English
Common mistakes
- Use
=to store a value: the name goes on the left, the value on the right. - Use a variable only after you have given it a value, or you get a NameError.
- Names cannot start with a number or contain spaces.
日本語
よくあるミス
- 値を格納するには
=を使います:名前は左、値は右です。 - 値を与えずに変数を使うと NameError が発生します。
- 名前は数字で始められず、スペースを含めてはいけません。
English
Now you try
- Use a variable for each task below.
- Press Check answer to test your code.
日本語
あなたも試してみよう
- 以下の各タスクで変数を使用してください。
- 回答を確認 を押してコードを試してください。
Create a variable called age and store the number 15 in it.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
The variable color starts as "red". Reassign it so that it becomes "blue".
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Constants are written in UPPERCASE by convention. Create a constant MAX_SCORE and set it to 100.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
a is 1 and b is 2. Swap them, so a becomes 2 and b becomes 1, without typing the numbers 1 or 2 again. (Tip: a third variable can hold one value for a moment.)
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。