如果x比y高3

时间:2013-10-31 19:10:17

标签: python string numbers

我正在做一个猜谜游戏的程序;只有当数字比随机数高3或少3时,我才能让程序给出H或L的反馈。

这就是我目前所拥有的

import random
def game3():
    rndnumber = str(random.randint(0,9999)) #gets a number between 0-9999
    while len(rndnumber) < 4: 
        rndnumber = '0'+ rndnumber # adds 0s incase the number is less then a 1000
    print(rndnumber) #lets me know that the program generates the right type of number (remove this after testing)
    feedback = 0 #adds a variable
    for x in range(1,11): #makes a loop that runs for 10 times
        print("Attempt",x)
        attempt = input("Guess a number between 0-9999:")#gets the users guess
        feedback = "" #makes a feedback variable
        for y in range(4): #makes a loop that runs for 4 times
            if attempt[y] == rndnumber[y]: #if attempt is the same then add a Y to the number
                feedback += "Y"
            elif attempt[y] < rndnumber[y]:
                feedback += "L"
            elif attempt[y] > rndnumber[y]:
                feedback += "H"
            else:
                feedback += "N"
        print(feedback)
        if  x == 10:
            print("You Lose the correct answer was",rndnumber)
        if feedback == "YYYY" and x > 1:
            print("You win it took",x,"attempts.")
            break; #stops the program
        elif feedback == "YYYY":
            print("You won on your first attempt!")
            break; #stops the program

3 个答案:

答案 0 :(得分:0)

  

如果x比y高3,则

if x+3 == y:
    #code
  

只有当数字比随机数高3时,程序才会给出反馈   数量减少或减少3个。

if x+3 == y or x-3 == y:
    #give feedback

来源:

http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html

答案 1 :(得分:0)

你可以使用

if attempt == rndnumber + 3 or attempt == rndnumber - 3:
    # Do something...

答案 2 :(得分:0)

在第10行中,您将在变量尝试中保存一个字符串。 但是,在第13行中,您将try用作字典。

您可能想在此重新考虑整个方法。

编辑:

当然我也曾经做过猜谜游戏。虽然我现在肯定会使用不同的方法,但我认为它可能对您有所帮助,并在此python 3代码中为您自己的游戏构建您的需求。

import random

print ("Hello! What is your name?")
name = input()
print ("Well,", name, ", I am thinking of a number between 1 and 100.\nTake a guess.")
number = random.randint(1, 100) # create a number between 1 and 100
guess = input() # read user's guess
guess = int(guess)
guessnumber = 1 # first try to guess the number
guessed = False # number isn't guessed yet
while guessed == False:
    if (number == guess):
        print ("Good job,", name + "! You guessed my number in",guessnumber, "guesses!")
        guessed = True
    elif (guess > number):
        print ("Your guess is too high.")
        guess = input("Take another guess: ")
        guess = int(guess)
        guessnumber+=1
    else:
        print ("Your guess is too low.")
        guess = input("Take another guess: ")
        guess = int(guess)
        guessnumber+=1