简体   繁体   English

python中是否有一个随机函数可以接受变量?

[英]Is there a random function in python that accepts variables?

I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. 我正在尝试创建一个简单的骰子滚轴,并且希望它创建一个介于1和骰子边数之间的随机数。 However, randint will not accept a variable. 但是, randint将不接受变量。 Is there a way to do what I'm trying to do? 有没有办法做我想做的事?

code below: 下面的代码:

import random
a=0
final=0
working=0

sides = input("How many dice do you want to roll?")

while a<=sides:
    a=a+1
    working=random.randint(1, 4)
    final=final+working

print "Your total is:", final

If looks like you're confused about the number of dice and the number of sides 如果您对骰子数和边数感到困惑

I've changed the code to use raw_input() . 我将代码更改为使用raw_input() input() is not recommended because Python literally evaluates the user input which could be malicious python code 不建议使用input()因为Python实际上会评估用户输入,这可能是恶意python代码

import random
a=0
final=0
working=0

rolls = int(raw_input("How many dice do you want to roll? "))
sides = int(raw_input("How many sides? "))

while a<rolls:
    a=a+1
    working=random.randint(1, sides)
    final=final+working

print "Your total is:", final

you need to pass sides to randint , for example like this: 您需要将双方传递给randint ,例如:

working = random.randint(1, int(sides))

also, it's not the best practice to use input in python-2.x. 同样,在python-2.x中使用input也不是最佳实践。 please, use raw_input instead, you'll need to convert to number yourself, but it's safer. 请改用raw_input ,您需要自己转换为数字,但这更安全。

Try randrange(1, 5) 尝试randrange(1,5)

Generating random numbers in Python 在Python中生成随机数

random.randint accepts a variable as either of its two parameters. random.randint接受一个变量作为其两个参数之一。 I'm not sure exactly what your issue is. 我不确定您的问题到底是什么。

This works for me: 这对我有用:

import random

# generate number between 1 and 6
sides = 6
print random.randint(1, sides)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM