【问题标题】:Can someone help me figure out how to run this program successfully? [duplicate]有人可以帮我弄清楚如何成功运行这个程序吗? [复制]
【发布时间】:2021-08-03 14:43:02
【问题描述】:

目标是让计算机猜测一个给定上限和下限的数字,计算机应将“否”作为输入并再次运行程序,直到给出“是”。

这是我现在使用的代码,但是由于返回函数的位置,循环只运行一次。如果我把它拿出来直接跳转打印它会连续运行。

import random

num1 = int(input("enter your minumum value: "))
num2 = int(input("enter your maximum value: ")) 
def number_choice(num1,num2):
    guess = "no"
    while guess == "no": 
        return random.choice(range(num1,num2))
print (number_choice(num1,num2))
guess = input("is that your number, enter yes or no: ")

【问题讨论】:

  • return 总是结束它所在方法的执行。这在relevant documentation 中有明确说明:“return 将当前函数调用与表达式列表(或无)作为返回值”。

标签: python python-3.x loops


【解决方案1】:

试试这个:

import random

num1 = int(input("enter your minimum value: "))
num2 = int(input("enter your maximum value: "))
def number_choice(num1,num2):
        print(random.choice(range(num1,num2)))
guess='no'
while guess.lower()=='no':
    number_choice(num1,num2)
    guess = input("Is that your number, enter yes or no: ")
print('Cheers!')

或者你也可以使用它:

import random

num1 = int(input("enter your minimum value: "))
num2 = int(input("enter your maximum value: ")) 
def number_choice(num1,num2):
    print(rnd.choice(range(num1,num2)))
    guess=input('Is this your number? Type yes or no ')
    if guess=='no':
        number_choice(num1,num2)
    else:
        print('cheers!')

number_choice(num1,num2)

希望对你有帮助!

【讨论】:

  • 答案已更新..
猜你喜欢
  • 2022-12-28
  • 2021-02-12
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多