[英]How do you print certain amount of results in range by user input using python?
I was trying to create a dice rolling program where the user enters how much a certain amount of dice they want to roll.我试图创建一个骰子滚动程序,用户可以在其中输入他们想要滚动的一定数量的骰子。 But it is not working.但它不起作用。 What should I do?我应该怎么办?
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()
I am new to this language, but I love it and I bet you do too, hence I put together an idea based on your code, I certainly hope this answers your question.我是这门语言的新手,但我喜欢它,我打赌你也喜欢,因此我根据你的代码提出了一个想法,我当然希望这能回答你的问题。 Keep coding bro, Python is great!继续编码兄弟,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.
On the 4th line, you just did input()
.在第 4 行,您刚刚做了input()
。 However, you need to add an int()
function around the input.但是,您需要在输入周围添加一个int()
function。
This would be your code:这将是您的代码:
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()
Hope this helps!希望这可以帮助!
You're importing branding
from the random
module, not randint
.您正在从random
模块导入branding
,而不是randint
。
Use int()
when calling the input()
function, for the range()
function to work properly.调用input()
function 时使用int()
,以使range()
function 正常工作。
In the last line, repeat = ("y" or "yes") in input().lower()
, ("y" or "yes")
will evaluate to a boolean, and then your check will become something like True in input().lower()
which gives incorrect, and bizarre results.在最后一行, repeat = ("y" or "yes") in input().lower()
, ("y" or "yes")
将评估为 boolean,然后您的检查将变为True in input().lower()
给出不正确和奇怪的结果。 Use something like repeat = input().lower() in ("y", "yes")
instead. repeat = input().lower() in ("y", "yes")
东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.