using function and random numbers - python

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.

Related

how do you make something loop a specific amount of times in python?

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.

How can i sort a function?

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()))

How to implement a numeric guessing game with loops in Python

So I'm creating this game where the computer guesses a number, and based on the reply, it splits and re-selects a number. I've had little problems so far, but now I'm quite stuck on the loop. I know what I have to do, I just can't figure out how to do it properly, and have it function.
lowest = int(input( "What is the lowest number you will think of?: "))
highest = int(input( "What is the highest number you will think of?: "))
print("So you're thinking of a number between",lowest,"and",highest)
x=[]
for number in range(lowest,highest):
x.append(number)
middleIndex = (len(x))//2
print ("is it "+str(x[middleIndex])+"?")
answer = input("")
if answer == "lower":
x = (x[:len(x)//2])
else:
x = (x[len(x)//2:])
I know it has to go after the
x.append(number)
but I can't get it to work using for or while loops.
The entire for loop is kind of pointless, with the x.append line especially so. range() gives you a list anyway (in Python 3 it gives you a range object which can be converted to a list using the list function).
You could replace that with:
x=list(range(lowest, highest))
Also, this is more convention than anything technically incorrect, but in Python I think camel case is generally reserved for class names; for this reason, I would rename middleIndex to middle_index.
And finally, you don't have anything for the case when the computer guesses the right number!
What you're looking for is basically an interactive binary search algorithm that runs over a range of numbers. You don't actually need to use range or a list, because you can calculate the average of your min and max values instead of finding the middle_index.
Here is an example implementation:
def main():
print("What range will your guessed number fall within?")
min = int(input("Min: "))
max = int(input("Max: "))
print("Ok; think of a number between {0} and {1}.".format(min, max))
while min <= max:
mid = (min + max) // 2
if input("Is it {0}? (Y/N) ".format(mid)) == "Y":
print("It is!? Well, that was fun.")
return
elif input("Darn. Is it higher than {0}? (Y/N) ".format(mid)) == "Y":
min = mid + 1
else:
max = mid - 1
print("Well, it looks like you were dishonest somewhere along the line.")
print("I've exhausted every possibility!")
main()

python: if statement, not responding properly to value from dice roll

so i have been working on a input based dungeon game in python that is fairly rudimentary. I wanted to put a dice roll condition in the game and decide if a player will die or live on a path. However my if statement will not properly respond to the roll in the number generator i have in the program, it will print the number and then carry on whether or not the condition was met. How can i fix this, and why is this happening?
if direction == 1:
import random
from random import *
num = 6
def d6(num):
rolls = []
for x in range(num):
rolls.append(randint(1,6))
return rolls
rolls = d6(1)
print rolls
if rolls is 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
elif rolls is not 3:
print "you are back at the start which way will you go?\n"
path3 =float(input("forward, or right?"))
is and is not are reserved for special comparisons in python. You need == and !=. Also you can change it to a simple if/else instead of if/elif with no else. Also, it looks like your d6 function returns a list instead of a single number. Try adjusting that to return a single number instead:
from random import randint
def d6():
return randint(1,6)
rolls = d6()
if rolls == 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
else:
print "you are back at the start which way will you go?\n"

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. 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)

Categories