Home > Blockchain >  How To Make a program for grade of students without if else statements in python
How To Make a program for grade of students without if else statements in python

Time:08-06

Actually, I am a beginner. So Help Me Accordingly. I am Confused, How We Will Be Able To Generate The Same Output Without using if_else, By Using Basics.

#We Really Stalk Code!! :)
M = int(input("Enter The Marks Of Maths(Out OF 100) "))
S = int(input("Enter The Marks Of Science(Out OF 100) "))
E = int(input("Enter The Marks Of English(Out OF 100) "))
TOT=M S E
print("Total Marks",TOT,sep=" ")
PER= (M S E)/3
print("Percentage",round(PER,2),sep=" ")
#Now I want The Below Code To Be Run Without The Use Of if_else
if(PER>50):
  print("A")
elif(PER>0):
 print("B")

elif(PER==0):
  print("C")

CodePudding user response:

If else is the basics. There's literally no more basic construct in programming. Any alternative mechanism of accomplishing this is going to use a more complicated construct (a data structure, a goto or a loop)

Python does have alternative control flow statements. It has goto, and if can be implemented using while and break as follows

while per > 50:
   print("A")
   break

But if-else is always the correct way to do this in Python.

Artificial restrictions don't teach you to be a good programmer. You don't learn to become a good writer by writing an entire essay without using the letter e. You don't learn to become a good footba player by not using your feet. You don't become a better cook by cutting all your vegetables with a spoon.

CodePudding user response:

An alternative to if else in python is switch case in python. Implementing switch case in python can be acheived with the help of dictionary in python.

CodePudding user response:

@NickBailey 's answer is the simplest and probably the best route without if-else statements.

You can also use boolean logic to figure out if the grade should be an A, B, or C with a dictionary.


# Figure out if it's an A, B, or C (only one can be True)
is_a = PER > 50
is_b = PER <= 50 and PER > 0
is_c = PER == 0

# Assign key,val pairs to each grade
grade_values = {
    is_a: "A",
    is_b: "B",
    is_c: "C",
}

# Since only one grade can evaluate to True, grade_values[True] will return the correct grade
grade = grade_values[True]

print(grade)
  • Related