我已经找到了关于这个问题的其他答案,但是在我的程序中实现这个解决方案时遇到了困难(对于Python来说还是很新的)。以下是我目前掌握的情况:
# Purpose: 'guess' randomly selects a number between 0 and 100 (including those
# numbers) and calculate the cube of that number. It also prompts the user to
# guess the cube root of the cubed number, displaying 'Correct!' if correct, and
# asking the user if they would like to try again if incorrect.
def guess():
import random
rand = random.randint (0, 100)
cubed = rand*rand*rand
# Forming the input question
string = "What is the cube root of"
cubed = str(cubed)
qmark = "?"
question = print(string, cubed + qmark)
user = int(input(question))
while (user == rand):
print ("\nCorrect!")
user = input("\n\tWould you like to try again?").lower()
if (user != rand):
print ("\tIncorrect!, the cube root of", cubed, "is", rand)
这应该是输出的样子:
guess()
What is the cube root of 64000? 56
Incorrect, the cube root of 64000 is 40
Would you like to try again? y
What is the cube root of 216? 6
Correct!
Would you like to try again? n
Goodbye
这可能有助于:
您将
print
函数(即None
)的返回值存储在question
中,然后将question
传递给正在打印它的input
函数这是一个非常好的函数开始尝试!有两件事需要解决:
1)问题变量中不应包含打印。在input()中放入一个变量将为您打印它。这样会更好:
2)底部部分不太正确。也许你想要这样的东西?最后一行再次调用整个函数-这称为“递归”。你知道吗
总而言之,这里是最后的代码:
我最近才开始编程,这是我第一次帮助别人!你知道吗
编辑:根据注释中的建议,下面是一种不使用递归的方法,将所有内容放入“While True循环”(也称为forever循环):
相关问题 更多 >
编程相关推荐