Python Forum

Full Version: Check all input, easy way! Help pls!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
while True:
    try:
        midterm_1= float(input('Please enter your first midterm: '))
        midterm_2= float(input('Please enter your second midterm: '))
        
        midterm_total= midterm_1*(20/100) + midterm_2*(20/100)
        print('your total percentage from midterm scores is: ' + str(midterm_total))
        
        
        summary_paper= float((input('Please enter your score for summary paper: ')))
        
        response_paper= float((input('Please enter your score for response paper: ')))
        
        writing_total= summary_paper *(10/100) + response_paper *(20/100)
        
        print('your total percentage from writing is: ' + str(writing_total))
        break
    
    except:
        print('Please enter a valid number')



i= 1
my_list= []
while i<=10:
    try:
        my_list.append(int(input('Please enter your discussion score: ')))
        i+=1
    
    except:
        print('Please enter valid number: ')

print(my_list)

dis_total=[]
for x in my_list: 
        dis_total.append(x*(2/100))

print('your total percentage from discussion is: '  + str(sum(dis_total)))        
        
        

i= 1
top_hat= []
while i<=5:
    try:
        top_hat.append(int(input('Please enter your top hat score: ')))
        i+=1
    
    except:
        print('Please enter valid number: ')

print(top_hat)

top_hat_total=[]
for x in top_hat: 
        top_hat_total.append(x*(2/100))

print('your total percentage from top hat is: '  + str(sum(top_hat_total)))        
        
total_sum = midterm_total + writing_total + sum(dis_total) + sum(top_hat_total)

if total_sum >0 and total_sum<100: 
    if total_sum >= 86:
        print('You received an A')
    
    elif total_sum >= 74:
         print('You received a B')
    
    elif total_sum >= 62:
         print('You received a C')
              
    elif total_sum >= 54:
         print('You received a D')
    
    else:
        print('You failed :(')
    
else:
    print('Something is not right!')     
What i want to do is to check each input to see if it is between 0 and 100, if not ask to enter again. What is the easiest way to do this? Thanks!
Anything that is repetitive is a candidate for a function. Below is a function vinput that takes the prompt as an argument and returns the validated input.

def vinput(prompt) :
    valid = False
    while not valid :
        try :
            temp = float(input(prompt))
            if temp<0 or temp>100:
                raise ValueError
            else :
                valid = True
        except ValueError :
            print('Invalid entry, try again')
    return temp

midterm1 = vinput('Enter score for midterm: ')
Thank you!