Home > Software engineering >  How to have entries created based on user input (Python)
How to have entries created based on user input (Python)

Time:03-20

I have created a program that calculates the average of a student, and I want input to be created based on the user input, for example: if the user types 5, it creates 5 input.

    print('Average of students')
def student_average():
    while True:
        try:
            # I want to create inputs depending on the user's input in the following question:
            number_of_qualifications = int(input('What is the number of qualifications?: '))
            qualification_1 = float(input('What is the first qualification?: '))
            qualification_2 = float(input('What is the second qualification?: '))
            qualification_3 = float(input('What is the third qualification?: '))
            qualification_4 = float(input('What is the fourth qualification?: '))
            break
        except:
            print('This is not an option')
    sum = (qualification_1   qualification_2   qualification_3   qualification_4)
    average = (sum / 4)
    print(average)
student_average()

CodePudding user response:

You need to use a loop. I've removed the try/except, you can add that back in if you want.

def student_average():
    number_of_qualifications = int(input('What is the number of qualifications?: '))
    sumx = 0
    for _ in range(number_of_qualifications):
        sumx  = float(input('What is the next qualification?: '))
    return sumx / number_of_qualifications

print(student_average())

CodePudding user response:

I have modified your codes, so the try-except feature is preserved

def student_average():
    total, c = 0,0
    number_of_qualifications = int(input('What is the number of qualifications?: '))
    while True:
        try:
            # I want to create inputs depending on the user's input in the following question:
            total  = float(input(f'{c 1} What is the qualification?: '))
            c  = 1
            if c == number_of_qualifications:
                break
        except:
            print('This is not an option')
    average = (total / number_of_qualifications)
    print(average)
    
print('Average of students')
student_average()

Output:

Average of students
What is the number of qualifications?:  3
1 What is the qualification?:  4
2 What is the qualification?:  5
3 What is the qualification?:  a
This is not an option
3 What is the qualification?:  6
5.0
  • Related