简体   繁体   中英

How do I read multiple inputs in python 2

I am new to python. I searched and found out how to do it in python 3:

v = [int(x) for x in input().split()]

but in python 2 I get the syntax error. I need it for foobar because I can't code in c++ nor python 3 there which is incredibly annoying.

In Python 2 you have 2 input functions:

  • raw_input : this does what you expect; it reads the input as a string.
  • input : this actually evaluates the user input; this is why you get a syntax error; you cannot evaluate a string like "1 2 3 4 5" .

So you want to use raw_input() :

v = [int(x) for x in raw_input().split()]

In Python 3 input instead does what you want.

Try this:

v = [int(x) for x in raw_input("Enter your numbers separated by space: ").split()]

In Python 2.X

  • raw_input() takes exactly what the user typed and passes it back as a string
  • input() first takes the raw_input() and then performs an eval() on as well.

In Python 3.X

  • raw_input() was renamed to input() so now input() returns exactly what the user typed and passes it back as a string
  • Old input() was removed.

In python3 there is no raw_input . The python3 input is the renamed python2 raw_input . So in python2 you should use raw_input instead. Like this:

v = [int(x) for x in raw_input("Enter numbers here").split(" ")]

The argument in split is the separator. In the first example the separator is a space. But if you want to get the numbers separated with - , you can use it like this:

v = [int(x) for x in raw_input("Enter numbers here").split("-")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM