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. However, randint will not accept a variable. 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(). input()is not recommended because Python
literally evaluates the user input which could be malicious python code
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:
working = random.randint(1, int(sides))
also, it's not the best practice to use input in python-2.x. please, use raw_input instead, you'll need to convert to number yourself, but it's safer.
Try randrange(1, 5)
Generating random numbers in Python
random.randint accepts a variable as either of its two parameters. 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)
Related
hello I am trying to make a warhammer 40k dice roller and I made this code however it does not roll the right amount of dice I would appreceate help on how to make it work
import random
count = 0
dice_to_roll=input("how many dice are you rolling? ")
hit = input("what do you hit on? ")
print("rolling dice!!!!!!")
while str(count) < dice_to_roll:
die = random.randint(1, 6)
count = count + 1
if str(die) >= hit:
print(die)
else:
print("done")
input is returning a string. Making the other one a string and checking equality is comparing the lengths of the string, not the values. To make yours work, use int(input(...)) and remove the str() casts that you're doing.
Code:
import random
dice_to_roll = int(input("how many dice are you rolling? "))
hit = int(input("what do you hit on? "))
print ("rolling dice!!!!!!")
for i in range(dice_to_roll):
die = random.randint(1,6)
if die>=hit:
print(f"dice result:{die},hit:{hit},hit success!")
else:
print(f"dice result:{die},hit:{hit},hit failed!")
print("done")
Result:
how many dice are you rolling? 1
what do you hit on? 3
rolling dice!!!!!!
dice result:6,hit:3,hit success!
done
Instead of converting your count to a string try and convert your input dice_to_roll to an int.
What i want to do with this code is roll 'n' number of dice and then find the lower quartile of it.
so far i have:
from random import randint
#Rolling the Die
numofdie = int(input("Please input the number of dice u want to roll: "))
if numofdie < 1:
print ("PLease enter 1 or more")
quit()
if numofdie > 100:
print ("PLease enter a number less than 100")
quit()
#Sum
def dicerolls():
return [randint(1,6) for _ in range(numofdie)]
print (dicerolls())
Then i used the string.sort() function to try and sort the dicerolls() but realised that it will not work as it is a function. How can i fix this and consequently be able to find the lower quartile.
Thanks
Put the result in a variable, then sort that.
rolls = dicerolls()
rolls.sort()
print(rolls)
Or use the sorted() function:
print(sorted(dicerolls())
The built-in sorted() function will return a sorted version of whatever list you give it. Since dicerolls() returns a list, you can add that list right in:
print(sorted(dicerolls()))
I have a question:
When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
This is what I have done so far:
import random
x = random.randint(1,6)
print("You roll a die ", x)
new_try = input("\n\n Do you want to roll a die again?")
if str(new_try) == 'yes':
print("You roll a die ", x)
else:
print("Cool game!")
I am still getting same numbers :(
You aren't changing x the second time, and merely printing it out again, giving the same result. Here is the code for a fixed version:
import random
x = random.randint(1, 6)
print("You roll a die", x)
new_try = input("\n\n Do you want to roll again? ")
if new_try == 'yes':
x = random.randint(1, 6)
print("You roll a die", x)
else:
print("Cool game!")
If you want to use a function for it, you can do it over multiple times:
import random
def roll_dice():
x = random.randint(1, 6)
print("Dice was rolled: " + str(x))
try_again = input("Do you want to try again? ")
if try_again == 'yes':
roll_dice()
roll_dice()
I reckon what you can do is set a different seed each time you run a new try.
x is not the diceroll, that is random.randint(1,6). So after x = random.randint(1,6), x stores the result of a single diceroll which happened earlier, and available to provide that single result any time in the future. So x stores a number, not the fact that it should be generated randomly.
If you want a function for rolling a dice, that would be def for first attempts:
def diceroll():
return random.randint(1,6)
having this function, any subsequent print(diceroll()) (note that it is a function call, diceroll()) would print the result of a different roll (and results could be equal only by coincidence). Or, you could again store the result of a single diceroll as x=diceroll(), so it could be re-used multiple times in the future (let's say you want to compare it to the user's guess and also print it)
Side note: technically you can store functions in variables too, x=diceroll would store the function, so x would not be a number, but the act of rolling the dice, and would have to be called as a function, like print(x()).
If you want to produce different numbers at different times, you have to use a seed value. Here is an example to explain:
import random
random.seed( 3 )
print "Random number with seed 3 :", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()
I will not make the program for you. I have explained you the concept. Now just implement it.
I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.
import random
def main():
uinput()
def uinput():
times = int(input('How many numbers do you want generated?'))
number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
rnumber = random.randint(number1, number2)
print (rnumber)
main()
I am messing around in Python, and I want my program to generate random numbers. As you can see I have already accomplished this. The next thing I want to do is have it generate multiple random numbers, depending on how many numbers the "user" wants generated. How would I go about doing this? I am assuming a loop would be required.
This will produce a list of random integers in range number1 to number2
rnumber = [random.randint(number1, number2) for x in range(times)]
For more information, look at List Comprehension.
I would recommend using a loop that simply adds to an existing string:
import random
from random import randint
list=""
number1=input("Put in the first number: ")
number2=input("Put in the second number: ")
total=input("Put in how many numbers generated: ")
times_run=0
while times_run<=total:
gen1=random.randint(number1, number2)
list=str(list)+str(gen1)+" "
times_run+=1
print list
Use a "for" loop. For example:
for i in xrange(times):
# generate random number and print it
Use generators and iterators:
import random
from itertools import islice
def genRandom(a, b):
while True:
yield random.randint(a, b)
number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
total = int(input('Put in how many numbers generated:'))
rnumberIterator = islice(genRandom(number1, number2), total)
You can define a function to take user input to generate numbers in a given range. You can return the function or print the function.
import random
def ran_nums():
low_range = int(input('Enter the low end of the range: '))
high_range = int(input('Enter the high end of the range: '))
times = int(input('How many numbers do you want to generate? '))
for num in range(times):
print(random.randint(low_range,high_range))
This code chooses a random number:
import random
x = (random.randint(1, 50))
print ("The number is ", x)
Repeat the code 6 times to choose 6 random numbers.