Home > database >  Not sure if this function is right to calculate what I need
Not sure if this function is right to calculate what I need

Time:04-05

So what I want the code to do is collect grades as 1,2, or 3 if one of these numbers isn't chosen then redirect the person to input again until the correct answer is input then continue to run the rest of the code. The program should process an undetermined number of persons

for g_rade in grade:`
  if grade != '1' or '2' or '3':`
    print("Please enter the correct grade")`
continue`
  if grade == '1'or '2' or '3':`
break`
  if grade ==1:`
     if overall grade <= 70:`
        addded_grade = grade   3`
        print(addded_grade)`
  elif grade > 75 and grade < 80:`
        addded_grade = grade   5`
        print(addded_grade)
  else: 
        addded_grade= grade   4`
        print(addded_grade)`
 if grade == 2:`
      if grade < 50:`
         addded_grade= grade   2`
          print(addded_grade)`
      else:`
          addded_grade = grade   1`
          print(addded_grade )`
 if grade == 3:`
          addded_grade= grade   0.5`
          print(addded_grade)`
 print("Finished")`

CodePudding user response:

Dealing with the problem at hand, you basically want to continuously ask for input until it is valid. This can be achieved with a simple while loop. Sample code:

valid = ['1', '2', '3']
a = input('Enter a Grade')
while a not in valid:
    a = input('Enter a valid Grade')

Sample Output:

Enter a Grade
5
Enter a valid Grade
6
Enter a valid Grade
9
Enter a valid Grade
2

CodePudding user response:

This:

if grade != '1' or '2' or '3':

Is almost certainly wrong. It parses as:

if (grade != '1') or '2' or '3':

As '2' and '3' are always true, this entire conditional is always true.

If you want to determine if grade is one of those values, you can use in to check if it exists in a set.

if grade in {'1', '2', '3'}:
  • Related