LoginSignup
1
1

More than 3 years have passed since last update.

【python】input()の使い方

Posted at

input()とは

入力である。

input()の使い方

例として入力に1を入れたコードを書く。

a = input()

print(a)
#1
#1

以上のように入力した数である1input()になっていることが分かる。

input()の型

input()に入る文字のを見てみる。intなのかfloatなのかstringなのか。

a = input()

print(type(a))
#1
#<class 'str'>

以上の例から、入力した値の型string(文字)になっていることが分かる。

input()をintの型に変更

input()intの型に変更するコードを以下に書く。

a = int(input())

print(type(a))
#1
<class 'int'>

以上のようにinput()に入力した1がint(数字)の1になっていることが分かる。

intにしないときのエラー

input()に数字を入れてそのまま足し算をしてもエラーになる。

以下がその例。

a = input()

b = a + 1

print(b)
#1
Traceback (most recent call last):
  File "practice.py", line 3, in <module>
    b = a + 1
TypeError: can only concatenate str (not "int") to str

これは入力した1が数字の1ではなく文字の1だと認識されている。
そのため、入力した1を数字の1に直す必要がある。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1