简体   繁体   中英

Assigning variable values to if statement

if GPA == unweighted:
A+ = 4.33
A = 4
A- = 3.67
B+ = 3.33
B = 3.0
value1 = credits*grade1

Ok so I am trying to assign those number values to those variables if the if statement is true, but when I run the program, it says there is a syntax error. Can someone please help me fix this? Thanks.

You can't use operators as part of the identifiers for your variables. Full explanation in the Python docs about identifiers

The Python interpreter will identify the + and - as actual code to execute and not as part of you variables names like A+ .

In Python as well as in other programming languages the only allowed characters for variable identifiers are letters ( az , AZ ), numbers ( 0-9 ) and underscore ( _ ). Though keep in mind there is an extra rule that specified you can't start an identifier with a number as well. Additional to that, in Python 3 (via PEP 3131 ) support was added for non-ASCII characters, meaning you could even write your variables in Russian ( картофель = 10 ).

I would rename those variables as a_plus , a_minus o b_plus .

Why not use a dictionary? You can store the weighted and unweighted grade scales with the grades as keys.

gpa = {
    'unweighted':
        {
        'A+' : 4.33,
        'A'  : 4,
        'A-' : 3.67,
        'B+' : 3.33,
        'B'  : 3.0,
        'B-' : 2.67
        },
    'weighted':
        {
        'A+' : 4.67,
        'A'  : 4.3
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM