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

时间:2019-01-09 06:35:04

标签: 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().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_petsno_pets中可接受的答案。如果输入在yes_pets列表中,则需要pets = “your furbaby”。如果输入在no_pets列表中,我想要pets = “that $$$”。但是,如果用户提供的输入不在这两个列表中的任何一个中,我希望它循环并继续询问该问题,直到用户提供可接受的输入为止。

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

我相信第一个if和elif语句在我提供可接受的输入时可以正常工作。但是,当for循环执行时,即使用户提供了可接受的输入,它也会继续循环问题。我尝试了for pets not in yes_pets or no_pets:,但这种逻辑似乎不起作用。因此,将NOT排除在外,我认为正在发生的是它无限循环,因为用户给出了使循环条件成立的答案?当用户给出另一个不在列表中的答案时,由于ELSE,它仍然会循环吗?

7 个答案:

答案 0 :(得分:1)

考虑使用while循环而不是for循环。您可以让while True:条件无限期地循环,如果满足您的条件,则可以break循环。

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=' ')

答案 1 :(得分:1)

问题出在for循环

for pets in yes_pets or no_pets:

尝试执行以下代码。

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))

答案 2 :(得分:0)

您可以为此使用递归

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()

答案 3 :(得分:0)

只需添加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.

答案 4 :(得分:0)

您可以尝试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))

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

答案 5 :(得分:0)

表达式yes_pets or no_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))。它还可以使循环变得更简单,同时允许您轻松添加诸如“也许”之类的选项:

pet_options = dict.fromkeys(yes_pets, 'your furbaby')
pet_options.update(dict.fromkeys(no_pets, 'that $$$'))

...

pets = pet_options.get(input("Do you have any pets? (y/n): ").strip().lower())
while pets is None:
    pets = pet_options.get(input("Sorry didn't catch that. Do you have any pets (y/n)?: ").strip().lower())

答案 6 :(得分:0)

此代码将非常有效且非常有效地运行,直到用户键入以“ 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)