简体   繁体   中英

is it bad practice to overwrite a variable in a different datatype python

I was wondering when I was input validating in python whether it is good practice to overwrite a variable in a different data type, example:

x = "initialise"
while x == "initialise":
    try:
        x = int(input("what is the number "))
    except ValueError:
        print ("it has to be a number\n")

print (x)

if it is bad practice then can you tell me a different way in which I can input validate this if it is ok then can you help me aswell? thanks.

In your particular example, you should use the special None keyword when initializing a variable without a value.

In general, try not to use the same variable for multiple datatypes.

Is this what you intended to do..?

x = "initialise"
guess_value = None
while guess_value != x:
    try:
        guess_value = eval(input("what is the number: "))
    except NameError:
        print ("it has to be a number\n")
print (guess_value)

Regarding the overwriting the data type, it doesn't matter as the variable name being assigned to new data type. Only thing what you need to make sure is that the new data type works for your program.

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