Problem 1: Write a program that asks the user to input any positive integer and outputs the sum of all numbers between one and that number.
This program asks the user to input any positive integer and outputs the sum of all numbers between one and that number. The input can be any positive integer. If the user inputs something other than this an error message is printed until a positive integer is entered.
When an exception is detected by the statements between try and except, Python jumps to the exception handling statement and executes these. The program then continues at the next line after the exception handling clause. If no exception is raised then the exception handling statements are skipped.
A ValueError
is raised if the input is not an integer as it expects an integer.
- A
ValueError
is when the right type of argument is received but it is an inappropriate value
"""
This code asks the user to input a valid positive integer
until a valid input in entered
"""
while True:
try:
x = int(input("Please enter a positive integer: "))
if x < 0:
raise ValueError
break
except ValueError:
print("That was not a positive integer. \
Please try again")
total = 0
while x >= 1:
total += x
x -= 1
print (total)