【问题标题】:How do I stop this from repeating?我如何阻止这种情况重复?
【发布时间】:2021-09-24 12:24:10
【问题描述】:

我是编码新手。它可以正常工作,直到你猜到一个数字。然后它永远说更高或更低。请帮助我理解我做错了什么。我曾尝试搜索互联网并尝试重新输入一些代码,但它不起作用。我正在尝试进行对话以及迷你猜数字游戏。

这是我的代码

# Conversation A

import random

print("Answer all questions with 'yes' or 'no' and press ENTER")   

print('Hello I am Jim the computer')   
z = input('How are you? ')    
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':    
    print("That's great!")    
else:    
    print("Oh. That's sad. I hope you feel better.")    
a = input("what's your name? ")    
print(a + "? Thats a nice name.")    
b = input('Do you own any pets? ')    
if b == 'yes' or b == 'Yes':    
    print("That's cool. I love pets!")    
else:    
    print("That's a shame, you should get a pet. ")    
c = input("Do you like animals? ")    
if c == 'yes' or c == 'Yes':
    print("Great! Me too!")
else:
    print("Oh that's sad. They're really cute. ")

d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
    input("Ok! Think of a number between 1-30. Do you have it? ")
    print("Double that number.")
    print("Add ten.")
    print("Now divide by 2...")
    print("And subtract your original number!")
    y = input("Was your answer 5? ")
    if y == 'yes' or y == 'Yes':
        print("Yay i got it right! I hope you like my magic trick.")
    else:
        print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
    print("Ok. Maybe next time. I love magic tricks and games!")

e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
    randnum = random.randint(1,100)
    print("I am thinking of a number between 1 and 100...")

if e == 'no' or e == 'No':
    print("oh well see you next time" + a + '.')

guess = int(input())

while guess is not randnum:
    if guess == randnum:
        print("Nice guess " + a + "! Bye, have a nice day!")
    if guess < randnum:
        print("Higher.")
    if guess > randnum:
        print("Lower.")

【问题讨论】:

  • 如果您猜得更高或更低,您的 while 循环将永远运行。只有guess == randnum才会停止。因为你的条件是假的。你根本不需要while循环。
  • 一些提示:您可以使用in 来检查一个字符串是否是多个不同字符串的任意,因此if z in ("Good", "Great", "good", "great") 的行为方式相同,而无需编写所有那些or== 语句。更好的是,您可以使用z.lower() in ("good", "great").lower() 方法返回字符串的小写版本,因此您可以进行不区分大小写的检查。

标签: python loops repeat


【解决方案1】:

当你想停止循环时,你需要添加一个break 语句并将input for guess 移动到循环内,这样你就不会在打印语句之前退出:

while True:
    guess = int(input())
    if guess == randnum:
        print("Nice guess " + a + "! Bye, have a nice day!")
        break

编辑:另外,你不想每次都使用isIs there a difference between "==" and "is"?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 2021-08-17
  • 1970-01-01
  • 2016-03-09
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多