问题简单猜猜python中的数字游戏

时间:2015-09-02 16:27:03

标签: python python-3.x

我有一个问题,我简单猜猜python中的数字游戏。代码在下面给出。程序从来没有给我一个正确的猜测,它不断询问数字。

import random 
import time

time1 = time.time()

number = random.randint(1,1000)

print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam  thinking of the number between 1 and 1000")

while True:
guess = int(input("guess: ") )
if guess > number:
    print("too high!")
    if guess < number:
        print("too low!")
        if guess == number:
            break
        print("yahoo,you guessed the number!")
        input()
        time2 = time.time()

这是python 3中的猜数游戏。

4 个答案:

答案 0 :(得分:1)

您需要正确缩进代码,您还应该使用if/elif's,因为猜测在任何时候都只能是更高,更低或相等的值。您还需要在成功猜测之前打印:

while True:
    guess = int(input("guess: ") )
    if guess > number:
        print("too high!")
    elif guess < number:
        print("too low!")
    elif guess == number:
        print("yahoo,you guessed the number!")
        time2 = time.time()
        break

如果猜测是&gt;,那么你的循环就无法破解,因为你的if嵌套在外if guess > number:内。数字然后if guess < number:被评估,但由于显而易见的原因,不可能是真的,所以你无限循环。

答案 1 :(得分:0)

import random 
import time

time1 = time.time()
number = random.randint(1,1000)

print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am  thinking of the number between 1 and 1000")

while True:
    guess = int(input("guess: ") )
    if guess > number:
        print("too high!")
    if guess < number:
        print("too low!")
    if guess == number:
        print("yahoo,you guessed the number!")
        time2 = time.time()
        break

没有太大变化,这是一个有效的代码。

答案 2 :(得分:0)

secret_number = 5
chance = 1
while chance <= 3:
    your_guess = int(input("Your Guess:- "))
    chance = chance + 1
    if your_guess == secret_number:
        print("You Won !!")
        break
else:
    print("You failed..TRY AGAIN..")

答案 3 :(得分:0)

import random as rand

# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
    number = int(input("guess the number :  "))
    if(number in l1):
        print("this number is alraedy entered")
        i=i
    else:
        l1.append(number)
        if(number == r):
            print(number)
            break
        if(number>r):
            print(" number is less than your number ")
        elif(number<r):
            print("number is greater than your number")
        i =i+1
print("number is")
print(r)