+ 8
How to request optional additional input in Python?
for example if I want a program two add the input numbers but I don't know if user will input 2,3 or 4 numbers, how can I add optional but not required input?
4 ответов
+ 5
Hmm... Then I think a while loop will work. Keep appending inputs to a list until the user inputs “end” or some other keyword. Then check the length of your list and use it to guide the rest of the code.
+ 4
There are a few ways. I think the best one is to get the input, which is by default a string, and split it number by number.
Lets say the user inputs the following:
3 7 35
You could turn that in a list [“3”, “7”, “35”] by using:
mylist = input().split(“ “)
Then you can turn each element of the list into an int by using list comprehension:
mynumbers = [int(x) for x in mylist]
Which will give you a list [3, 7, 35].
That would work for any number of numbers in the input.
If you want to add them all, do:
mysum = 0
for n in mynumbers:
mysum += n
print(mysum)
+ 3
That wasn't really my question...my problem is, I need to find a way to make the program run one way if user inputs 3 things and another way if they input 4 separate inputs
+ 3
Thanks, that is a great idea!😀