简体   繁体   中英

Why input() function in python gets only first written object?

For example:

a = input()
print(a)

Then, I am inputting those separated words written: separated In output, I am only getting "4"

But when I am inputting them like this: not separated

I am getting each word.

How can I get each word by inputting separately?

You need a separate input() for each line, so for 2 sentences you will need:

a = input()
b = input()
print(a)
print(b)

In case you are expecting multiple inputs, but you dont know how many you can place the input() inside a loop until an exit condition is met

line = ""
while line != "exit":
  line = input()
  # Do whatever with line
input()

reads just one line. To read all the lines, you need to use for example:

import fileinput
for line in fileinput.input():
    <do sth>
    

if your variable is meant to be string, you can easily concatenate your strings with +. If the variable should later be printed and give the same output as the given input, you can use '/n':

my_var = ""
for line in fileinput.input():
    my_var += '/n' + line

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