Sarwan Shah - 1 year ago 67
Python Question

# The 'if' statement

i'm very new to python & programming overall. I'd like to know how to use the 'if' statement to give output as a variable or integer if the variable-input satisfies the conditions put forward. I'm writing a very basic program for providing students a provisional CGPA based on their input marks for practice.

This is my code:

``````def maths(a, b):
print "Total marks for maths this term are equal to %d + %d=" % (a, b), a + b
return a + b

def english(a, b):
print "Total marks for english this term are equal to %d + %d=" % (a, b), a + b
return a + b

math_marks = maths(int(raw_input("Maths 1st assignment marks>")),int(raw_input("Maths 2nd assignment marks>")))
english_marks = english(int(raw_input("English 1st assignment marks>")),int(raw_input("English 2nd assignment marks>")))

if english_marks > 80: GPA = 4
if english_marks > 70: GPA = 3
if english_marks > 60: GPA = 2
if english_marks > 50: GPA = 1
if english_marks > 40: GPA = 0

if math_marks > 80: GPA1 = 4
if math_marks > 70: GPA1 = 3
if math_marks > 60: GPA1 = 2
if math_marks > 50: GPA1 = 1
if math_marks > 40: GPA1 = 0

CGPA = GPA + GPA1 / 2
print "Your CGPA is %d" % (CGPA)
``````

When i run the code i get no error, however, the CGPA prints out as '0'. So could someone please guide me through how to fix this?

Regards,
Sarwan

To expand a bit on the comments:

Let's assume `english_marks = 95`. When this line of code executes:

``````if english_marks > 80: GPA = 4
``````

95 is obviously greater than 80, so GPA is set to 4.

However, then we get to the next line:

``````if english_marks > 70: GPA = 3
``````

95 is also greater than 70, so GPA is reset to 3. And so on for 60, 50, and 40.

The solution is to rework your if statement. Leave the first `if` alone and change all the rest to `elif`, so that only one assignment will execute:

``````if english_marks > 80: GPA = 4
elif english_marks > 70: GPA = 3
elif english_marks > 60: GPA = 2
elif english_marks > 50: GPA = 1
elif english_marks > 40: GPA = 0
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download