I learned python years ago and I am just trying to re-learn it now. I'm trying to make a basic program that asks name and age, and I have a while loop to try and make sure that the person actually puts in the correct numbers to confirm their name, but it just keeps looping over and over.
name = input("What's your name? ")
print("Are you sure your name is",name,"? Type 1 for YES or 2 for NO.")
sure = int(input())
while(sure != 1 or 2):
sure == input("Please type 1 for yes or 2 for NO.")
在我看来,“确保”始终为!= 1或2,请尝试使用“与”
There are a few problems that can be fix to make your code work.
sure
captures the input
as an int
but only the first time.
The fix: Move int()
into the while
loop declaration, or even better compare sure
to a string by quoting '1'
and '2'
as input
will return a string.
or '2'
is incorrect as sure
is never compared to '2'
. You were probably thinking:
sure != '1' or sure != '2' #'or' would not work in this scenario
or
sure != '1' and sure != '2'
However, this could more simply be written as sure not in ('1','2')
.
The fix: replace != '1' or '2'
declaration with: not in ('1','2')
In the loop sure == input
is a comparison and not an assignment.
The fix: replace sure == input
with: sure = input
The fixed code should look like the following:
name = input("What's your name? ")
print("Are you sure your name is",name,"? Type 1 for YES or 2 for NO.")
sure = input()
while(sure not in ('1','2')):
sure = input("Please type 1 for yes or 2 for NO.")
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.