简体   繁体   中英

What data type should I use in my program

Relatively new to programming and doing some coursework on python. I've been told to label all my variables with the correct data type. For example an integer would be called iVariable and a string would be sString. Although I recall someone telling me that sometimes you need to label a variable containing a number a string? I don't really understand what they meant by this. Below is the start of my code, it's not perfect but if someone could tell me if I've done the data types right or wrong and told me what their supposed to be that would be great. Thanks in advance

iResultlist = 0
sEndScript = 0
while iResultlist == 0:
    if sEndScript == "y":
        iResultlist = 1
    sStudent = input("What is the students name?")
    bInputValid = False
    while (bInputValid == False):
        sUserResponse = input("What score did they get")
        if sUserResponse.isdigit():
            iScore = int(sUserResponse)
            bInputValid = True
        else:
            print ("Enter a valid number please")
    iClass = input("What class is the student in? \"1\, "\"2\" or \"3\"")
    if iClass == "1":
        Class1 = open("Class1.csv", "a+")
        Class1.write(Student+","+Score+"\n")
        Class1.close()

Also is there a data type I should use for my file names? And if so what is it?

sometimes you need to label a variable containing a number a string

I'm guessing that what they meant is a situation like in:

iClass = input("What class is the student in? \"1\, "\"2\" or \"3\"")

The content of iClass is going to be a number, sure. But the type is still a string. To get a numerical value out of it, you still have to convert it via int(iClass) . So if you're really going for the hungarian notation, then it should be something like:

sClass = input(...)  # this is a string, even if the string is "123"
iClass = int(sClass)  # now it's a proper int

Although in the current code, you just don't need the converted iClass at all.

If you're not sure what type something is at some point, you can always print it out during execution, like:

print("iClass is:", type(iClass))

But like @Blorgbeard commented - hungarian notation isn't really popular outside of winapi these days.

You can always test the type of a variable by doing

if isinstance(iClass, int):  
    ... # continue with you example

Instead of 'int' you can use other types like str, float etc

BTW, the Hungarian notation is useful in languages that enforce a variable to only have one type. It was common in the first language I learnt, FORTRAN, but punched cards were the thing too.

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