94
83

More than 3 years have passed since last update.

Pythonで複数の値を入力する方法

Last updated at Posted at 2018-04-26

Pythonで複数の整数を入力する

「1 2 3」のようにスペースで区切って一気に複数の整数を入力させ、それを別々の変数に対応させたい という場合の簡単な解決法を紹介しています。

(まずは)Pythonでひとつの文字列を入力する方法

input()を使います。

a=input()
print(a)

結果:

apple
apple

Pythonでひとつの整数を入力する方法

input()を使い入力させ、intで整数に直します。

a=int(input())
print(a)

結果:

1
1

Pythonで複数の文字列を入力する方法

input()で入力した後、split()を使い、スペースの入ってる位置でaとbを区切ります。

a,b=input().split()
print(a)
print(b)

結果:

apple orange
apple
orange

(本題)Pythonで複数の整数を入力する場合

input().split()までは文字列の場合と同じなのですが、整数に直すために int(x) for x in を使います。


a,b=(int(x) for x in input().split())
print(a)
print(b)

結果:

1 2
1
2

マップやループを使う方法より簡単だと思うのでぜひ使ってみてください。

94
83
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
94
83