Python 当变量的值不在列表中时,如何运行循环?

Python 当变量的值不在列表中时,如何运行循环?,python,python-3.x,for-loop,if-statement,Python,Python 3.x,For Loop,If Statement,我正在尝试建立一个快速的小测验程序。我知道我大部分都是对的,但是当我问用户是否有宠物的代码时,我有一点小问题 对Python来说还是相当陌生的,非常感谢您的帮助!这个小问题开始让我头疼起来 另外,我正在运行Python 3.7.1 yes_pets = ["y", "yes", "yeah", "yup", "yeah"] no_pets = ["n", "no", "nope", "nah", "non"] name = input("What is your name?: ").strip

我正在尝试建立一个快速的小测验程序。我知道我大部分都是对的,但是当我问用户是否有宠物的代码时,我有一点小问题

对Python来说还是相当陌生的,非常感谢您的帮助!这个小问题开始让我头疼起来

另外,我正在运行Python 3.7.1

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()
if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
else:
    for pets in yes_pets or no_pets:
        pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
        if pets in yes_pets:
            pets = "your furbaby"
        elif pets in no_pets:
            pets = "that $$$"

print("\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(name, age, place, work, pets, hobbies, music, travel))
-我想要它-

参考用户输入的变量
PETS
,并在列表
yes\u PETS
no\u PETS
中提供可接受的答案。如果输入在
yes\u pets
列表中,我想要
pets=“your furbbaby”
。如果输入在
no_pets
列表中,我想要
pets=“that$$$”
。但是,如果用户提供的输入不在这两个列表中,我希望它循环并再次询问该问题,直到用户提供可接受的输入

-我认为正在发生的事情-


我相信当我给出一个可接受的输入时,第一个if和elif语句工作得很好。但是,当for循环执行时,即使用户提供了可接受的输入,它也会继续循环问题。我尝试了
为宠物而不是在yes\u pets或no\u pets:
中,但这种逻辑似乎不起作用。所以撇开NOT,我认为发生的是它无限循环,因为用户给出了一个答案,使得循环的条件为真?当用户给出了另一个仍然不在列表中的答案时,它仍然会因为ELSE而循环?

您可以使用递归进行此操作

def test():
    yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
    no_pets = ["n", "no", "nope", "nah", "non"]


    pets = input("Do you have any pets? (y/n): ").strip().lower()
    if pets in yes_pets:
        pets = "your furbaby"
        return pets

    elif pets in no_pets:
        pets = "that $$$"
        return pets
    else:
        return test()


name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()

pets = test()

您可以对此使用递归

def test():
    yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
    no_pets = ["n", "no", "nope", "nah", "non"]


    pets = input("Do you have any pets? (y/n): ").strip().lower()
    if pets in yes_pets:
        pets = "your furbaby"
        return pets

    elif pets in no_pets:
        pets = "that $$$"
        return pets
    else:
        return test()


name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()

pets = test()

考虑使用while循环而不是for循环。您可以使用
while True:
条件无限期循环,然后
在满足条件的情况下中断循环

while True:
    pets = input("Do you have any pets? (y/n): ").strip().lower()
    if pets in yes_pets or pets in no_pets:
        break
    print("Sorry didn't catch that.", end=' ')

考虑使用while循环而不是for循环。您可以使用
while True:
条件无限期循环,然后
在满足条件的情况下中断循环

while True:
    pets = input("Do you have any pets? (y/n): ").strip().lower()
    if pets in yes_pets or pets in no_pets:
        break
    print("Sorry didn't catch that.", end=' ')

问题在于for循环

对于“是”或“否”宠物中的宠物:

请尝试执行以下代码

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()

if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
else:
    while True:
        pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
        if pets in yes_pets:
            pets = "your furbaby"
            break
        elif pets in no_pets:
            pets = "that $$$"
            break

print("\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(name, age, place, work, pets, hobbies, music, travel))

问题在于for循环

对于“是”或“否”宠物中的宠物:

请尝试执行以下代码

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()

if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
else:
    while True:
        pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
        if pets in yes_pets:
            pets = "your furbaby"
            break
        elif pets in no_pets:
            pets = "that $$$"
            break

print("\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(name, age, place, work, pets, hobbies, music, travel))
只需添加while循环:

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()
while pets not in yes_pets+no_pets: // HERE
    pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
print(
    "\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(
        name, age, place, work, pets, hobbies, music, travel))
输出:

C:\Users\Desktop>py xxx.py
What is your name?: aydin
How old are you?: 12
Where do you live?: aze
What do you do for a living?: program
What is your favorite hobby?: coding
Who is your favorite musician?: nobel
What country do you want to visit the most?: spain
Do you have any pets? (y/n): nikkilo
Sorry didn't catch that. Do you have any pets (y/n)?: aydin
Sorry didn't catch that. Do you have any pets (y/n)?: y

Hi Aydin! You are 12 years old and you live in Aze.
You work as an program but you do it for your furbaby.
When you're not working we could probably find you
coding listening to some Nobel
dreaming of going to Spain someday.
只需添加while循环:

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()
while pets not in yes_pets+no_pets: // HERE
    pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
print(
    "\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(
        name, age, place, work, pets, hobbies, music, travel))
输出:

C:\Users\Desktop>py xxx.py
What is your name?: aydin
How old are you?: 12
Where do you live?: aze
What do you do for a living?: program
What is your favorite hobby?: coding
Who is your favorite musician?: nobel
What country do you want to visit the most?: spain
Do you have any pets? (y/n): nikkilo
Sorry didn't catch that. Do you have any pets (y/n)?: aydin
Sorry didn't catch that. Do you have any pets (y/n)?: y

Hi Aydin! You are 12 years old and you live in Aze.
You work as an program but you do it for your furbaby.
When you're not working we could probably find you
coding listening to some Nobel
dreaming of going to Spain someday.

您可以尝试使用while循环-

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()
while pets not in yes_pets and pets not in no_pets:
    pets=input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
else:
    pass

print("\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(name, age, place, work, pets, hobbies, music, travel))

这将继续循环并不断询问输入,直到它没有得到有效值。

您可以尝试使用while循环-

yes_pets = ["y", "yes", "yeah", "yup", "yeah"]
no_pets = ["n", "no", "nope", "nah", "non"]

name = input("What is your name?: ").strip().capitalize()
age = int(input("How old are you?: ").strip().lower())
place = input("Where do you live?: ").strip().capitalize()
work = input("What do you do for a living?: ").strip().lower()
hobbies = input("What is your favorite hobby?: ").strip().lower()
music = input("Who is your favorite musician?: ").strip().title()
travel = input("What country do you want to visit the most?: ").strip().capitalize()
pets = input("Do you have any pets? (y/n): ").strip().lower()
while pets not in yes_pets and pets not in no_pets:
    pets=input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()
if pets in yes_pets:
    pets = "your furbaby"
elif pets in no_pets:
    pets = "that $$$"
else:
    pass

print("\nHi {}! You are {} years old and you live in {}.\nYou work as an {} but you do it for {}.\nWhen you're not working we could probably find you\n{} listening to some {}\ndreaming of going to {} someday.".format(name, age, place, work, pets, hobbies, music, travel))

这将继续循环并不断询问输入,直到它没有得到有效值。

表达式
yes\u pets或no\u pets
计算结果为第一个真实操作数。因为这两个列表都不是空的,所以循环是有效的

for pets in yes_pets:
这将运行五次,无论发生什么,因为你没有打破循环。它将在最后一次迭代中存储无意义的输入,因为没有
else
子句

您需要一个无限期运行的循环,只有当用户停止键入您无法理解的废话时,才会中断循环。
while
循环可以很好地实现这一目的。它还消除了一些代码重复:

pets = input("Do you have any pets? (y/n): ").strip().lower()
while pets not in yes_pets and pets not in no_pets:
    pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()

if pets in yes_pets:
    pets = "your furbaby"
else:  # pets in no_pets
    pets = "that $$$"
另一种方法可能是使用映射到正确输出的有效输入字典。这将加快您的搜索速度(查找现在是O(#个有效选项),但将变成O(1))。它还将使循环稍微简单一些,同时允许您轻松添加“maybe”之类的选项:


表达式
yes\u pets或no\u pets
计算为第一个真实操作数。因为这两个列表都不是空的,所以循环是有效的

for pets in yes_pets:
这将运行五次,无论发生什么,因为你没有打破循环。它将在最后一次迭代中存储无意义的输入,因为没有
else
子句

您需要一个无限期运行的循环,只有当用户停止键入您无法理解的废话时,才会中断循环。
while
循环可以很好地实现这一目的。它还消除了一些代码重复:

pets = input("Do you have any pets? (y/n): ").strip().lower()
while pets not in yes_pets and pets not in no_pets:
    pets = input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower()

if pets in yes_pets:
    pets = "your furbaby"
else:  # pets in no_pets
    pets = "that $$$"
另一种方法可能是使用映射到正确输出的有效输入字典。这将加快您的搜索速度(查找现在是O(#个有效选项),但将变成O(1))。它还将使循环稍微简单一些,同时允许您轻松添加“maybe”之类的选项:


这段代码将非常有效地工作,它会循环,直到用户键入任何以“y”或“n”开头的内容,不管它是否大写。你可以删除可接受答案的列表,给老师留下深刻印象

from time import sleep
run = 0
while run == 0:
    response = input("Do you have any pets? (y/n): ")
    if response.upper()[0] == "Y":
        run += 1
        pets = "your furbaby"
    elif response.upper()[0] == "N":
        run += 1
        pets = "that $$$"
    else:
        print("That's not a yes or no answer!")
        sleep(1)

这段代码将非常有效地工作,它会循环,直到用户键入任何以“y”或“n”开头的内容,不管它是否大写。你可以删除可接受答案的列表,给老师留下深刻印象

from time import sleep
run = 0
while run == 0:
    response = input("Do you have any pets? (y/n): ")
    if response.upper()[0] == "Y":
        run += 1
        pets = "your furbaby"
    elif response.upper()[0] == "N":
        run += 1
        pets = "that $$$"
    else:
        print("That's not a yes or no answer!")
        sleep(1)

您对“是”宠物或“否”宠物的
实际上是对“是”宠物或“否”宠物的
。现在认为“代码> P或Q<代码>如P>q<代码>P。现在认为<>代码> p或q>代码>如果p pq q,代码< >代码> p。<代码>宠物不在(YESTAPETS或NONEPETS)不会做你似乎把它固定的东西。这只是一个简单的错误,不是我想的那样,但它是有效的。请分享我所做的,在我的回答中
宠物不在(是宠物或否宠物)
不会做你期望的事情,我修复了它。这只是一个简单的错误,不是我想的那样,但它是有效的。请分享你的想法,在我的回答中,为什么不循环直到你的条件得到满足?@MadPhysicast,这不正是我说的吗?对于初学者来说,如果他们不觉得有义务只在循环的顶端突破,他们就更容易思考这些问题。Python不像Ja那样有do/while