簡體   English   中英

如何使用 python 通過用戶輸入在范圍內打印一定數量的結果?

[英]How do you print certain amount of results in range by user input using python?

我試圖創建一個骰子滾動程序,用戶可以在其中輸入他們想要滾動的一定數量的骰子。 但它不起作用。 我應該怎么辦?

from random import branding
repeat = True
while repeat:
    amount = input('how many dice do you want to roll?')
    for i in range(0, amount):
       print("You rolled",randint(1,6))
    print("Do you want to roll again?")
    repeat = ("y" or "yes") in input().lower()

我是這門語言的新手,但我喜歡它,我打賭你也喜歡,因此我根據你的代碼提出了一個想法,我當然希望這能回答你的問題。 繼續編碼兄弟,Python 很棒!

#First, you only need the random function to get the results you need :)
import  random
#Let us start by getting the response from the user to begin
repeat = input('Would you like to roll the dice [y/n]?\n')

#As long as the user keeps saying yes, we will keep the loop
while repeat != 'n':
# How many dices does the user wants to roll, 2 ,3 ,4 ,5  who knows. let's ask!
    amount = int(input('How many dices would you like to roll? \n'))
# Now let's roll each of those dices and get their results printed on the screen
    for i in range(0, amount):
       diceValue = random.randint(1, 6)
       print(f"Dice {i+1} got a [{diceValue}] on this turn.")
#Now, let's confirm if the user still wants to continue playing.       
    repeat = input('\nWould you like to roll the dice [y/n]?\n')

# Now that the user quit the game, let' say thank you for playing
print('Thank you for playing this game, come back soon!')
# Happy Python Coding, buddy! I hope this answers your question.

在第 4 行,您剛剛做了input() 但是,您需要在輸入周圍添加一個int() function。

這將是您的代碼:

from random import *
repeat = True
while repeat:
    amount = int(input('how many dice do you want to roll?'))
    for i in range(0, amount):
       print("You rolled",randint(1,6))
    print("Do you want to roll again?")
    repeat = ("y" or "yes") in input().lower()

希望這可以幫助!

  1. 您正在從random模塊導入branding ,而不是randint

  2. 調用input() function 時使用int() ,以使range() function 正常工作。

  3. 在最后一行, repeat = ("y" or "yes") in input().lower()("y" or "yes")將評估為 boolean,然后您的檢查將變為True in input().lower()給出不正確和奇怪的結果。 repeat = input().lower() in ("y", "yes")東西。

暫無
暫無

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

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