调用后返回不显示

时间:2015-03-05 04:47:56

标签: python return

我试图让用户猜出计算机随机生成的数字。传递返回功能时没有显示任何内容。

user = 0
result = ""
import random
print ("Welcome to Guess My Number Game")

def main():
    #user input
    computer = random.randint(1,100)
    print(computer)
    user=int(input("Guess the number:"))
    return (result)

def results(result):
    computer = random.randint(1,100)
    diff = 0
    diff = user - computer
    if diff < -10:
        result = ("Too Low")
    elif diff > 10:
        result = ("Too High")
    elif diff < 0:
        result = ("Getting warmer, but still low")
    elif diff > 0:
        result = ("Getting warmer, but still high")
    else:
        guesses = str(guesses)
        result = ('Good job, you guessed correctly in,',guesses,'guesses!')

2 个答案:

答案 0 :(得分:1)

你的缩进有几个问题但是,如果我能正确理解逻辑,你可以做类似下面的事情,以便让用户在猜到匹配之前做出猜测;

import random

def results(val):
    guesses = 0
    while True:
        user = int(input("Guess the number: "))
        guesses = guesses + 1
        diff = user - computer
        if diff < -10:
            print("Too Low")
        elif diff > 10:
            print("Too High")
        elif diff < 0:
            print("Getting warmer, but still low")
        elif diff > 0:
            print("Getting warmer, but still high")
        else:
            print('Good job, you guessed correctly in {} guesses!'.format(guesses))
            break
    return guesses

def main():
    computer = random.randint(1, 100)
    number_of_guesses = results(computer)

>>> results()
Guess the number: 2
Too Low
Guess the number: 10
Too Low
Guess the number: 50
Too High
Guess the number: 40
Too High
Guess the number: 30
Getting warmer, but still high
Guess the number: 25
Getting warmer, but still low
Guess the number: 26
Getting warmer, but still low
Guess the number: 28
Getting warmer, but still low
Guess the number: 29
Good job, you guessed correctly in 9 guesses!
9

答案 1 :(得分:0)

我将假设您正在尝试从结果方法

中打印结果变量

如果我的上述陈述是正确的,那么您对return的作用有误解。 return通常放在一个函数中,返回某个值。所以你应该把你的代码放到这里。

computer = random.randint(1,100)
print(computer) #if you print this guessing the number will be very easy
user=int(input("Guess the number:"))
print(results(computer, user))

def results(computer, user):
   results = ""
   # computer = random.randint(1,100) #you wont need this either
   diff = 0
   diff = user - computer
   if diff < -10:
      result = ("Too Low")
   elif diff > 10:
      result = ("Too High")
   elif diff < 0:
      result = ("Getting warmer, but still low")
   elif diff > 0:
      result = ("Getting warmer, but still high")
   else:
      guesses = str(guesses)
      result = ('Good job, you guessed correctly in,',guesses,'guesses!')
   return result