Generating random numbers in python - python

I'm trying to make a basic dice roller. When i run this program in Codeskulptor, it throws an error on the randint function. Can I not set the range for it using raw_input plugged into variables? Is there a different function I should use?
"""Program to roll random numbers within the ranges set."""
import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
else:
print "What do you want then?"

raw_input() returns a string, not an integer. To convert it to an integer type, use int():
sides_of_die = int(raw_input("Enter how many sides your die has: "))
number_of_dice = int(raw_input("Enter number of dice you have: "))
What's happening in your code is, you may input "6" and "2", so when you do total = sides_of_die * number_of_dice, you're getting a TypeError

This is just because raw_input returns a string, not a number, while randint accept two numbers as arguments
so you should do
total = int(raw_input(..))
Point is, this is not always secure. Exceptions are very likely to be thrown, so you might want to use a try block; but for the time being, I think it's okay (I'm assuming you're just learning Python).
Another thing, which is rather important:
Look at the exception! If you'd read it, you would have known exactly what the problem was.

Beside the raw_input() problem pointed out by the others, #Mark Ransom's comment is important: the sum of dice value eventually follows normal distribution. See: http://en.wikipedia.org/wiki/Dice#Probability
Your:
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
should be changed to
if rollinputcap =="Y":
sum_dice=[]
for i in range(number_of_dice):
sum_dice.append(random.randint(1, sides_of_dice))
print sum(sum_dice)

Related

Guess the Number game isn't working as intented [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last year.
Random Number Generator - Guess It
Did a much more complex variant of this. (250+ lines) But when I tested it, even if I guessed the number correctly(it was between 1-20) it didn't accept it. Every stage, I programmed the computer to tell me a statement about the number, using if, elif and else commands. When I guessed the number, it just said the number is incorrect and told me a new statement about number. Could someone help, please? In this mini variant as well, if I get the correct answer, it still responds to the if statement.
import random
list = [1,2,3]
target = print(random.choice(list))
guess = input("What is the target number?")
if guess == target :
print("Well done.")
else:
print("The number you have guessed isn't correct.")
You need to convert the guess into an integer before comparison. and remove the print statement from the variable definition. You also need to rename the list variable as it is a protected name.
import random
listNumbers = [1,2,3]
target = random.choice(listNumbers)
guess = int(input("What is the target number?"))
if guess == target :
print("Well done.")
else:
print("The number you have guessed isn't correct.")

How do you use a variable as an index when slicing integers in Python?

so im learning programming (python, visual studio community) and im trying to write a game in python and the best way of describing it is mastermind (a chosen length of numbers are randomly generated, you guess and it tells you if there are correct numbers in the correct position but not which position they are in) it seems as if everything else in this works so far apart from the fact that because this program will be able to do an infinite length i must check these numbers using a variable that increases by 1 each time if guess[y]==randomnumber[y]:, every time i run this i get the error msg:"'int' object is not subscriptable".
here is the full code:
length=int(input("what length do you want: "))
import random
if length==0:
length=int(input("what length do you want: "))
if length!=0:
x=0
while x!=length:
randomnumber=[int(random.randint(0,9))]
x=x+1
x=0
game_over=0
while game_over==0:
guess=int(input("your guess: "))
y=0
round_score=0
y=int(y)
while y!=length:
if guess[y]==randomnumber[y]:
round_score=round_score+1
y=y+1
if round_score==length:
game_over=1
You want to convert the guess to a list of ints.
Get input as string:
guess = input("your guess: ")
Sequence of characters (aka string) to int list:
guess = [int(c) for c in guess]
This could be written in one line but I think it is more clear this way.

How can an average equation be added to this?

I am taking GCSE programming and have be set a task to create a program which takes "n" amount of numbers and works out the average.
#presets for varibles
nCount = 0
total = 0
average = 0.0
Numbers = []
ValidInt = False
#start of string
nCount = (input("How many numbers? "))
print(nCount)
while not ValidInt:
try:
int(nCount)
ValidInt = True
except:
nCount = input("Please Enter An Interger Number")
#validation loops untill an interger is entered
for x in range (int(nCount)):
Numbers.append(input("Please Enter The Next Number"))
This is what i have so far but cannot think how i can code it to work out an average from this information? Any help is much appreciated, Thank you(i am not looking for answers just help in what function as i should use)
You're really close to the answer. Looks like you've got everything setup and ready to calculate the average, so very good job.
Python's got two built-in functions sum and len which can be used to calculate the sum of all the numbers, then divide that sum by how many numbers have been collected. Add this as the last line in your program and check the output.
Note: Since inputs were taken as integers (whole numbers) and the average will usually be a non-whole number, we make one of the numbers a float before calculating the average:
print(sum(Numbers)/float(len(Numbers)))
Edit: Or, since you've got a variable that already holds how many numbers the user has input, nCount, we can use this calculation, which will give the same answer:
print(sum(Numbers)/float(nCount)).
Try both and choose one or make your own.

While-loop not exiting in python

I'm trying to teach myself python right now, and I'm using exercises from "Learn Python The Hard Way" to do so.
Right now, I'm working on an exercise involving while loops, where I take a working while loop from a script, convert it to a function, and then call the function in another script. The only purpose of the final program is to add items to a list and then print the list as it goes.
My issue is that once I call the function, the embedded loop decides to continue infinitely.
I've analyzed my code (see below) a number of times, and can't find anything overtly wrong.
def append_numbers(counter):
i = 0
numbers = []
while i < counter:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
count = raw_input("Enter number of cycles: ")
print count
raw_input()
append_numbers(count)
I believe you want this.
count = int(raw_input("Enter number of cycles: "))
Without converting the input to integer, you end up with a string in the count variable, i.e. if you enter 1 when the program asks for input, what goes into count is '1'.
A comparison between string and integer turns out to be False. So the condition in while i < counter: is always False because i is an integer while counter is a string in your program.
In your program, you could have debugged this yourself if you had used print repr(count) instead to check what the value in count variable is. For your program, it would show '1' when you enter 1. With the fix I have suggested, it would show just 1.
convert the input string to integer... count=int(count)
Above has been cleared why the while looped for ever. It loops for a lot(=ASCII code which is really big)
But to fix the while you can simply:
while i<int(counter):
print "At the top i is %d" % i
numbers.append(i)
raw_input returns a string, but i is an integer. Try using input instead of raw_input.

Is there any way to use raw_input variables in random.randint?

I'm making a game where the "Computer" tries to guess a number you think of.
Here's a couple snippets of code:
askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.
Any suggestions?
It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.
However here is what you want to do:
askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))
You save it as a number and not as a string.
As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str(); instead, you can convert it to an integer using int(). Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:
def int_raw_input(prompt):
while True:
try:
# if the call to int() raises an
# exception, this won't return here
return int(raw_input(prompt))
except ValueError:
# simply ignore the error and retry
# the loop body (i.e. prompt again)
pass
You can then substitute this for your calls to raw_input.
The range numbers were stored as strings. Try this:
askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'

Categories

Resources