当前位置: 动力学知识库 > 问答 > 编程问答 >

python - assigning variable twice or not?

问题描述:

name = ''

while name != 'your name':

print('please type your name.')

name = input()

print('Thank you!')

Question: this is part of a coding example excercise. the program runs correctly. But my question is, aren't we assigning the variable-name twice here, 1st- as empty string, 2nd-as input(), and if so, assigning a variable twice is still okay ?

网友答案:

Yes, it is okay to define the variable twice, since you need it for the loop. Another way to do this would be to allow the loop to continue forever, until you explicitly break out of it. For example, you could rewrite your example as:

while True:
    name = input('please type your name')
    if name:
        break
print name

In this case, instead of pre-defining name, you create a loop that will start and continue until you issue a break statement (since the loop condition is True). After getting the name using input, the conditional if name will allow you to break out of the loop, as long as a name was entered.

As @eli_dink points out, the following is probably better practice:

waiting_for_name = True
while waiting_for_name:
    name = input('please type your name')
    if name:
        waiting_for_name = False
print name
网友答案:

You can assign a variable name as many times as you need to. Each time you do, that name is unbound from the object it used to refer to, and rebound to the result of the RHS of the assignment.

This is quite common inside loops, where you might do a similar series of calculations at each iteration - it's also implicitly used in a standard Python for loop - for example:

for letter in "mystring":
    print(letter)

You can see that the name letter refers to a different object each time around the loop. That loop is in fact an easier to read version of this loop:

mystring = "mystring"
i = 0
while i < len(mystring):
    letter = mystring[i]
    print(letter)
    i = i + 1

To make the while loop work, we had to add the variable i, whose value changes constantly throughout the loop (which is normally hidden in the behind-the-scenes mechanics of the for loop). We also rebind the name letter each time around the loop, which is just what the for loop does. This type of pattern would be quite difficult, if not impossible, if we weren't allowed to reuse the variable names in this way.

Note that this isn't something specific to loops: it just happens to be very commonly used there. You might also see it, for example, if you have a long calculation which doesn't fit nicely in one line - it can be useful to 'build it up' over several lines, reusing the same variable each time (although sometimes it is better style to find different meaningful names for the intermediate values, particularly if there are other things going on in between).

网友答案:

Yes, it's ok. That's why it's called "variable". It literally means "able to vary".

分享给朋友:
您可能感兴趣的文章:
随机阅读: