How to request optional additional input in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

24th Feb 2018, 10:58 PM
Erik Umble
Erik Umble - avatar
4 Answers
+ 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.
24th Feb 2018, 11:52 PM
Pedro Demingos
Pedro Demingos - avatar
+ 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)
24th Feb 2018, 11:36 PM
Pedro Demingos
Pedro Demingos - avatar
+ 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
24th Feb 2018, 11:48 PM
Erik Umble
Erik Umble - avatar
+ 3
Thanks, that is a great idea!😀
25th Feb 2018, 12:42 AM
Erik Umble
Erik Umble - avatar