22.4k views
5 votes
Write a PYTHON program that:

1) Asks the user to input a sequence of comma separated numbers, e.g., 4,6,7,454,78 (no space in between)
2) Transforms the input string into a list using the function split(). For example, userstr.split(',') will split the string userstr at each ',' and return a list of separated items.
3) Checks whether the user input is all-digit (use .isdigit() function). If yes, go to next step; if not, let the user try until they get it right.
4) Converts all items in the list into integer
5) Adds all numbers together and return the sum.

User Bsteo
by
8.1k points

1 Answer

3 votes

Answer:

while True:

user_input = input("Please enter a sequence of comma-separated numbers: ")

if user_input.replace(",", "").isdigit():

break

print("Invalid input! Please try again.")

num_list = user_input.split(",")

num_list = [int(num) for num in num_list]

total_sum = sum(num_list)

print("The sum of the numbers is:", total_sum)

Explanation:

This program uses a while loop to repeatedly ask the user for input until they provide a valid sequence of comma-separated numbers (all-digit input). The .isdigit() function is used to check if the input is all-digit. If the input is valid, the program splits the input string at each ',' using the .split() function, converts each item in the resulting list into an integer using list comprehension, then adds all numbers together using the sum() function. Finally, the program outputs the total sum.

User Robert Wohlfarth
by
8.2k points

No related questions found