我刚开始学习Python。这段代码有什么问题?

时间:2013-12-10 12:05:01

标签: python python-3.3

import random
print("Let's play the Random Number Game")
guess=random.randint(1,15)
print("\n I've choosed a random Number from 1 to 15", "Try guessing the number")
def strt( ):
userguess=input("\n Enter the number")
if userguess==guess :
    print("wow! you've guessed the correct number in" ,"time")
else:
    if userguess>guess:
        print("Guess a smaller number")
            strt( )
    else : print("Guess a Larger number")
            strt( )
strt()
input("Hit Enter to Exit")

我刚开始学习Python。这段代码怎么了?

3 个答案:

答案 0 :(得分:4)

除了正确缩进之外,您的程序还包含一个小错误。

input()在Python中返回str,如果不进行某种转换,则无法在Python中将字符串与int进行比较。 e.g:

userguess = int(input("Guess: "))

如果不进行此类型转换,则会抛出TypeError,如下所示:

>>> "foo" > 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

正确版本的程序,并且正确缩进并修复了上述错误:

import random


print("Let's play the Random Number Game")
guess = random.randint(1, 15)
print("\n I've choosed a random Number from 1 to 15", "Try guessing the number")


def strt():
    userguess = int(input("\n Enter the number"))
    if userguess == guess:
        print("wow! you've guessed the correct number in", "time")
    else:
        if userguess > guess:
            print("Guess a smaller number")
            strt()
        else:
            print("Guess a Larger number")
            strt()


strt()
input("Hit Enter to Exit")

答案 1 :(得分:1)

您的代码缺少适当的缩进。

Python代码使用缩进而不是代码块的其他语法,如Pascal中的beginend对,或C ++中的{}因此,正确的缩进对于Python编译器来说是至关重要的。

答案 2 :(得分:0)

好的,假设您已经修复了缩进,还有另一个问题:您将整数guess与字符串userguess进行比较。因此,相等性检查将始终失败,并且比较检查将抛出TypeError

>>> "1" == 1
False
>>> "1" > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

您需要在用户的输入上调用int(),以使变量具有可比性。