'Why can't I print a random number from 1 to a variable?
I was making a python program where you type in an input, and it finds a random number from 1 to that input. It won't work for me for whatever reason.
I tried using something like this
import random
a = input('pick a number: ')
print(random.randint(1, a))
input("Press enter to exit")
but it won't work for me, because as soon as it starts to print it, cmd prompt just closes. does anyone know how to fix this?
Solution 1:[1]
randInt() takes in two int data types, input() returns a String. So all you need to do is convert a into an int.
So do this
import random
a = input('pick a number: ')
print(random.randint(1, int(a)))
input("Press enter to exit")
Solution 2:[2]
randint does not take a string, but you can use try. If there is an error with a number, then write a message that int is needed. Sorry for my English.
import random;
try:
a = int(input("pick a number: "))
print(random.randint(1, a))
input("Press enter to exit")
except ValueError:
print("You need to write a number.")
Solution 3:[3]
You are most likely getting a TypeError. As input saves the terminal data entered by the user as a str (string). You need to cast that string into an integer (int) to be recognised as a number by Python
import random
# a is a string here
a = input('pick a number: ')
# a is converted to an int here (if it can be)
a = int(a)
print(random.randint(1, a))
input("Press enter to exit")
Here's how you can force the user to enter a number:
import random
while True:
# a is a string here
a = input('pick a number: ')
try:
# Try and convert a to an int
a = int(a)
# Exit this loop if you didn't get an error
break
except (TypeError, ValueError):
print("That's not a number!")
print(random.randint(1, a))
input("Press enter to exit")
If you have an error converting your input to an int in the try loop, it will go to the except part, and will keep looping until it works correctly
Further reading here, for learning sake :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | carlosdafield |
| Solution 2 | gozly |
| Solution 3 |
