Home > Blockchain >  How to add numbers in input in a Python for loop?
How to add numbers in input in a Python for loop?

Time:01-28

I'm stuck here:

repeat = int(input("How many : "))
number = 0
nArr = []

for i in range(repeat):
  number  = 1
  name = input("Line-",number,": ")
  nArr.append(name)

print(nArr)

I'm trying to get output like:

How many : 3
Line-1 : Hello
Line-2 : World
Line-3 : Today
['Hello', 'World', 'Today']

However, this program error occurs:

TypeError: input expected at most 1 argument, got 3

But I don't know how. Please, can someone advise where?

Any help would be appreciated.

CodePudding user response:

use format

input("Write this number {}: ".format(number))

CodePudding user response:

You may want to use a print() function to print "Line-",number,": ".

Why name = input("Line-",number,": ") won't work is because instead of concatenating the strings, Python thinks you're passing 3 arguments to input(): "Line-", number and ": ". But as input() takes only 1 argument (whatever the user types in, as a string), it throws that error. Looks like you're confused with string concatenation and the arguments passed to print().

print() takes any number of arguments, and displays them in the console altogether, with additional parameters/options for changing how the data should be displayed etc.
See Python "input expected at most 1 arguments, got 3".

Using print():

show_what_to_enter = print("Line-",number,": ") #just print and tell which line the user has to input
name = input() #wait for and get user input
nArr.append(name)

but this has some issues with how the data is being displayed, so the optional parameters end and sep can be used to get the same output as the one we get using input(), by changing show_what_to_enter like this:

show_what_to_enter = print("Line-",number,": ", end="", sep="")

So, the full code would be:

repeat = int(input("How many : "))
number = 0
nArr = []

for i in range(repeat):
  number  = 1
  show_what_to_enter = print("Line-",number,": ", end="", sep="")
  name = input()
  nArr.append(name)

print(nArr)

Using input():

name = input("Line-"   str(number)   ": ") 
#str(number) because number is an int, and an int and a string cant be concatenated 

The full code:

repeat = int(input("How many : "))
number = 0
nArr = []

for i in range(repeat):
  number  = 1
  name = input("Line-"   str(number)   ": ")
  nArr.append(name)

print(nArr)
  •  Tags:  
  • Related