如何在 spyder 中执行简单的交互式程序?

How can I execute simple interactive program in spyder?

我写了典型的猜数游戏:

import random
secret = random.randint(1, 99) 
guess = 0
tries = 0
print("Hey you on board! I am the dreadfull pirat Robert, and I have a 
secret!")
print("that is a magic number from 1 to 99. I give you 6 tries.")
while guess != secret & tries < 6:
    guess = input()
    if guess < secret:
        print("You! Son of a Biscuit Eater! It is too little! YOU Scurvy dog!")
    elif guess > secret:
        print("Yo-ho-ho! It is generous, right? BUT it is still wrong! The 
number is too large, Savvy? Shiver me timbers!")   
    tires = tries + 1
if guess == secret:
    print("Enough! You guessed it! Now you know my secret and I can have a peaceful life. Take my ship, and be new captain")
else:
    print("You are not lucky enough to live! You do not have ties. But before you walk the plank...")
    print("The number was ", secret)
    print("Sorry pal! This number became actually you death punishment. Dead men tell no tales! Yo Ho Ho!")

但是 spyder 会不停地执行这一切,让用户输入数字,我得到的只是这个输出:

Hey you on board! I am the dreadfull pirat Roberth, and I have a secret! that is a magic number from 1 to 99. I give you 6 tries. You are not lucky enough to live! You do not have ties. But before you walk the plank... The number was 56 Sorry pal! This number became actually you death punishment. Dead men tell no tales! Yo Ho Ho!

我试图调用 cmd -> spyder 并在那里执行它(通过复制粘贴),但我遇到了很多错误,例如:

print("The number was ", secret) File "", line 1 print("The number was ", secret)

但是,逐行(至少所有带打印的行)执行此代码不是问题。

我如何以交互方式执行我的代码,以便用户可以输入数字然后游戏继续?

您的代码有几个问题,在 tires=tries+1 中您可能打错了代码。

其次,guess 读取字符串,因此您需要将 guess 转换为 int 以进行整数比较,使用类似 guess=int(guess).

的东西

你没有看到这个的原因是因为你在 while 循环中的条件没有执行为真,运行 guess != secret & tries < 6 在解释器中你会看到条件是假的.

相反,您应该使用 and,因为这是一个逻辑运算符,而 & 是一个按位逻辑运算符(它们不相同)。

while guess != secret and tries < 6: 是您应该替换的适当代码行。