2013-12-10 41 views
0
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。这段代码有什么问题?我刚开始学习Python。这段代码有什么问题?

+4

你告诉我们,它抛出了什么错误? – StoryTeller

+1

你的缩排是关闭的 – inspectorG4dget

+1

[缩进很重要。](http://docs.python.org/2/reference/lexical_analysis.html#indentation) –

回答

1

您的代码缺少正确的缩进。

Python代码使用缩进的,而不是其他的语法来编码块,像对beginend如帕斯卡找到,或者{}如在C++中找到,因此正确的缩进是Python的编译器的关键,以完成其工作。

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()为了使变量相媲美。

4

除了缺少适当的缩进你的程序还包含一个小错误。

input()在Python中返回str,并且无法进行某种转换,您无法将字符串与Python中的ints进行比较。例如:

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") 
+0

耶,两个答案完全一样:) –

+0

呵呵:)我只是想在下班后放松一下,看看我是否能够提升自己的声望:) –