Python: Working on arrays need assistance in setting a range so the user cannot enter an input over 100

Question:

This is a snippet of the code I am working on

mark =[]
    totMark1 = 0

# Set the value for pre_class_activity and determine the weight of pre-class activities
    pre_class_activity = 4
    weight1 = pre_class_activity * 4

    try:
# ask the user to enter their marks they got in the pre class activity store them in the array
        print("Please enter the marks you have obtained in the " + str(pre_class_activity) + " pre-class activities in numeric values: ")
        for i in range(pre_class_activity):
            mark.insert(i, int(input()))
        
#calculate average and percent mark for pre class activities
        for i in range(pre_class_activity):
            totMark1 = totMark1 + mark[i]*4
            avg1 = totMark1/pre_class_activity
        
# check average to see if there is an error in user input
        if avg1 >= 401:
            print(avg1)
            print("i am sorry you can not have a mark higher than 100%, try again")
            quit()

I tried if in range for different variables, as well as creating a list although I cannot figure it out

Asked By: Cole Carley

||

Answers:

for i in range(pre_class_activity):
    marks = -1
    while marks not in range(101):
        marks = int(input())
        
        if marks not in range(101):
            print("Marks should be between 0 and 100")

    mark.append(marks)

It runs a loop, so in case if the input is not in range 0 – 100, the program will ask the user for another input until it is between 0 and 100. It also uses .append() instead of .insert() as inserting a value in the last place is the same as appending. The if condition checks whether the input is within Valid range or not, and prints an error message in case of invalid input

Answered By: KillerRebooted
mark =[]
totMark1 = 0

pre_class_activity = 4
weight1 = pre_class_activity * 4

try:

    print("Please enter the marks you have obtained in the " + str(pre_class_activity) + " pre-class activities in numeric values: ")

    for i in range(pre_class_activity):
        marks = -1
        while marks not in range(101):
            marks = int(input())
    
            if marks not in range(101):
                print("Marks should be between 0 and 100")
                continue


    for i in range(pre_class_activity):
        totMark1 = totMark1 + marks*4
        avg1 = totMark1/pre_class_activity

I still need to change a few this that @chris mentioned about the average

Answered By: Cole Carley
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.