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)) + '?'
Related
Hi so the question I completed involves while loops and although I finished it and got the expected outcome, I added a random line of code for "fun" to see what it would do, you could call it guessing and checking.
x = int(input())
increase = 0
while x != 0:
increase += x
**x = int(input())**
print(increase)
the line that I guessed has asterisks beside it, can someone please let me know what this simple line does.
If it helps:
My question is to input as many numbers as I please, but when I input the value 0, my code should return the sum of the number I inputted before the zero
x = int(input()) #takes user input string and try to convert to integer data type
increase = 0 # set value to variable increase
while x != 0: # condition
increase += x # it add/sum the value of the variable x to the value of the variable increase
x = int(input()) #takes user input string and try to convert to integer data type inside the while loop
print(increase) # print the value
watch this code in action on pythontutor
The function call input() takes user input from the console and makes it available to your code as a string. int(input()) converts the string input from the user, and tries to cast that value to an integer. That integer is then added to running count you have specified as increase.
Just to point out, you will get an error if a user specifies input that cannot be converted to an int, like typing in 'meow'. It will throw a ValueError.
The while loop waits for you to enter a value. This is done with input(). Because you need an integer (input always returns a string) int() is called on the input, which returns an integer (if possible). Everytime an input is made and converted to an integer the while loop starts the next iteration and checks if the previous input was equal to 0. If so, the while loop stops and (in this case) your print statement is executed.
This is exactly what you wanted to do.
New to Python (2.7). I'm trying to collect a user input that can either be an int or string (I'm assuming this is possible, though I'm not 100% sure). When I get to the statement that I've posted below, any number I enter prints the 'Invalid input' message and prompts me for a user input again, even if it's within the range I want it to be. Entering 'q' still works properly and returns if entered.
I've tried changing that first if statement to read (0 <= collectEyesBlade <= 9) ... with no luck either.
while True:
collectEyesBlade = raw_input(
"\nEnter desired blade number: ")
if collectEyesBlade in [range(0,9)]:
break
elif collectEyesBlade.lower() == 'q':
return
else:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
Since raw_input returns a str, start with the comparison that uses another string. Then, try to convert it to an int. Finally, if that succeeds, try the integer comparision.
while True:
collectEyesBlade = raw_input("\nEnter desired blade number: ")
if collectEyesBlade.lower() == 'q':
return
try:
collectEyesBlade = int(collectEyesBlade)
except ValueError:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
if collectEyesBlade in range(0,9):
break
if collectEyesBlade in [str(x) for x in range(0,9)] - this should work since collectEyesBlade is a string so we need to compare it to a string
You've hit at two of the little quirks of Python. One: a range is itself an iterable, but it's possible to put an iterable inside of another iterable.
In other words, your statement
if collectEyesBlade in [range(0,9)]:
is checking to see whether collectEyesBlade is an item in the list, which has only one item: a range iterable. Since you're not entering a range iterable, it's failing.
You can instead say
if collectEyesBlade in list(range(0,9)):
which will turn the range iterable into an actual list, or just
if collectEyesBlade in range(0,9):
Either should do what you intend.
However, as another answerer has mentioned, that's only half the problem. If your input were actually possibly integer type, the above would be sufficient, but you're asking for a string input. Just because the input is a "1" doesn't mean it's not a string one.
There are a couple of options here. You could do a try-except converting the string input into an integer, and if it fails because the string can't be converted into an integer, move on; or you could convert the range/list of numbers to compare to into strings.
How does input() work as a parameter to range() in Python?
For example:
Say the user inputs multiple numbers 10 and 2 or more literally type "10 2"
for i in range(int(input())):
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
What range does the for loop use then? Is it (0,10), (0,2) or something else? Or, said differently, which number does the range use for the upper limit if the user inputs multiple numbers? More generally, I am trying to understand the purpose of the for loop here and why the code can't just be:
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
input() values will be stored as str.
It all comes down to what the user inputs. The piece of code you provided is very bad, because the user has to guess what to input and when. But the logic works as follows:
If you type in a single value, then int(input()) will convert that value to integer. For example, if you input 2, then input() will hold the string "2" and int("2") will yield integer 2.
If you have multiple values, then you cannot convert to int right away, because what the hell does int("2 10") mean? That is why you have to use .split(), to separate these multiple values in many singular values. For example, if you run x = input() and type in 2 10, then x will hold the string "2 10". Now, "2 10".split() yields the list of strings ["2", "10"].
The piece of code map(int,input().split()) comes in to convert this list of strings to a list of integers. It maps each value to a new value using the function int to transform it.
Now that this is established, it becomes easier to understand how this works in a for loop using range.
The range type, as per docs, may have one parameter stop or three arguments (start, stop [, step]) in its constructor. These arguments are all integers.
Thus, the values from input() have to fit this structure. If you type in 2 10 in input, and try to do range("2 10"), you'll receive an error. Because you are passing one argument of type str. That is why you have to convert to integer first. But you cannot convert "2 10" to integer right away, as we just discussed. That is why you have to split first, and then convert each value to int, and just then pass these as arguments to range().
So, to summarize, given x = input() and you type in 2 10, here is what does not work:
>>> int(x)
>>> range(x)
what does work:
>>> a,b=map(int,input().split())
>>> range(a, b)
The first input() will determine the stop condition of the for loop
Which means the first input() determines the number of time your for loop will be executed
Other input() will assign the values to a and b as string
The above is equivalent to:
stop = input()
stop = int(stop)
for i in range(stop):
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
But if the first input() is given as "10 10" then the code will throw you an error something like the string can not be converted to int
The a,b=map(int,input().split()) means you are expecting an input of two numbers separated by spaces and these inputs will be given exactly stop number of times
This pattern is used when you want to read n lines from the input, for example the input is:
3
1 2
3 4
5 6
The first input will determine how many times the for loop needs to be run to read all the lines.
For a single line of input like "10 2" you don't need to use a loop.
I am trying to create a list where I need to input numbers as strings in one list and I am trying to do it with a while loop.
while input_list[-1] != "":
input_list.append(raw_input())
However when numbers are entered they are returned as u'X', X being the number entered. I cannot perfrom mathematical calculations on these numbers.
I would usually use str() or int() but I cant generalise in this case.
Is there a cleaner way to remove the u' ' prefix than simpley using if statements?
The "u'' prefix" is trying to indicate the type of the value. You have strings here, not numbers. If you want to do math, you need to convert your strings to numbers. If they happen to enter a string that can't be converted to a number, you should tell the user what happened
user_typed = raw_input()
try:
user_number = float(user_typed)
except ValueError:
print "Couldn't convert this to a number, please try again: %r" % user_typed
See also: LBYL and EAFP
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)