How do I limit inputs to only be Specific multiples in Python?

Question:

Currently doing a college assignment where we need to input and add 3 different scores.
The Scores must be not be less than 0 or greater than 10, and they can only be in multiples of 0.5. It’s the latter part I’m having trouble with.

How do I tell the program to give an error if the input isn’t a multiple of 0.5?

score1 = float(input("Please input the first score: ")

if score1 <0 or score1 >10:
  score1 = float(input("Error! Scores can only be between 0 and 10.n Please input Score 1 again: "))
elif score1 
Asked By: TaxingClock

||

Answers:

Nested if statement comes into play here. First it will check the condn is score>0 and score<10 then the next if statement of checking multiple statement comes to play. Use loop for taking input back to back until condn not met.

score = float(input("Enter score"))
if score>0 and score<10:
   if (score*10)%5 == 0:
       print(" Score is a Multiple of 0.5")
   else:
       print("Score is Not multiple of 0.5")
else:
   print("Error! Scores can only be between 0 and 10")

`

Answered By: Luicfer Ai

One way to do this is to use a while loop:

    score1 = float(input("Please input the first score: ")
    # while loop will keep asking for correct input if the input does not satisfy the requirements
    while score1 <0 or score1 >10 or not (score1%0.5)== 0.0:        
        score1 = float(input("Error! Scores can only be between 0 and 10 and in multiples of 0.5.n Please input Score 1 again: ")
    print(score1, "passes all the tests")

or alternatively, you could raise an error statement if you’d like:

    score1 = float(input("score: "))
    if score1<0 or score1>10 or not (score1%0.5)==0.0:
            raise BaseException("Error! the input score1 must be between 1 and 10 and a multiple of 0.5")
    print(score1, "passes all the tests")
Answered By: Ryan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.