簡體   English   中英

如何讓 python 在 def main() 中只要求用戶輸入一次?

[英]How do I make python only ask for user input once in def main()?

這是代碼

# Number guessing game

# Import any libraries here
from random import randrange

#def user_integer():
 #   ''' get what user's integer here'''
  #  x = int(input("Enter integer to play"))


def random_int(size):
    """ This function takes in an integer size that indicates the
    length of the list of integers beginning at 1 and ending 
    at size, including size. It returns a random integer between 1 and size.
    """
    return randrange(1, size+1)

# Test out the function
#random_int(10)

def new_guess():
    '''user input for a new number'''
    x = input("what's your guess?")
    x = int(x)
    #while x!= -4:
     #   compare(user_num, computer_num)
    return x

def compare(user_num, computer_num):
    ''' compares size of numbers and prints winner'''
    user_num = new_guess()
    computer_num = int(random_int(1000))
    if user_num > computer_num:
        print ("user wins")
    elif user_num == computer_num:
        print ("it's a tie")
    elif user_num < computer_num:
        print ("robots win")
    else:
        print("wrong input")


def main():
    ''' control center, allowing me to use multiple functions to pass information '''
    # Write your algorithm here
    computer_num = random_int(1000)
    user_num = new_guess()
    print("You guessed", user_num)
    print("The robot's number is",computer_num)
    compare(user_num, computer_num)

    
main()

這給了我:

你猜怎么着? 85#輸入

你猜了 85

機器人的編號是540 #random number

你猜怎么着? 85 #它讓用戶再次輸入

機器人贏

所有應該打印的東西都打印出來。 但是,由於我調用了user_num = new_guess() ,它使用戶一次輸入一個數字,然后再次輸入 function compare(user_num, computer_num)

我該怎么做才能讓用戶只輸入一次數字來獲得compare(user_num, computer_num)的響應?

一旦我在 def main() 中得到我的猜測,我應該給 user_num 起一個新名字嗎?

問題是你得到了兩次輸入。 在 main function 中,你得到computer_num隨機數和user_num輸入。 然后你調用compare() function,它有這兩個參數。

您可以從compare() function 中刪除 2 行代碼。它應該如下所示:

def compare(user_num, computer_num):
    ''' compares size of numbers and prints winner'''
    if user_num > computer_num:
        print ("user wins")
    elif user_num == computer_num:
        print ("it's a tie")
    elif user_num < computer_num:
        print ("robots win")
    else:
        print("wrong input")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM