Python猜测游戏不起作用

时间:2015-05-07 13:20:26

标签: python random

我正在创建一个python代码,它会选择一个随机数,并将其与用户猜测进行比较。

import random
attempts=0
secret=random.randint(1,49)
print "welcome to my guessing game"
repeat
def repeat():
    guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
        if secret==guess:
            print "Well Done! you guessed it in "+attempts+" attempts"
        elif secret < guess:
            print "too high"
            guess=raw_input("have another go")
        elif secret > guess:
            print "too low"
            guess=raw_input("have another go")
    attempts += 1
while guess != secret and attempts>6:
    repeat()

但是说没有定义重复。

3 个答案:

答案 0 :(得分:1)

这将允许用户猜7次,然后打印游戏结束: 这适用于Python 2. for Python 3.使用 int(input(""))

import random

secret = random.randint(1,49)
attempts = 0
for attempts in range(7):
    guess=input("I have thought of a number between 1 and 50. you have to try and guess it: ")
    if secret==guess:
        print "Well Done! you guessed it "
    elif secret < guess:
        print "too high"
        guess=input(" Enter to have another go")
    elif secret > guess:
        print "too low"
        guess=input("Enter to have another go")
    if attempts == 6:
        print "Game Over"

答案 1 :(得分:1)

程序无效,因为在创建函数之前无法运行或调用函数。此外,您应该通过执行此操作来调用重复&#34; repeat()&#34;

答案 2 :(得分:0)

我已将您的代码改编为以下应该有效的代码。您可能希望在Local and Global Variables上阅读导致代码中出现主要问题的原因。

import random

def repeat(secret, attempts):
    guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
    if secret==guess:
        print "Well Done! you guessed it in "+attempts+" attempts"
    elif secret < guess:
        print "too high"
        guess=raw_input("have another go")
    elif secret > guess:
        print "too low"
        guess=raw_input("have another go")
    attempts += 1
    while guess != secret and attempts < 6:
        repeat(secret, attempts)

attempts = 0
secret = random.randint(1,49)
print "welcome to my guessing game"
repeat(secret, attempts)
相关问题