FatRhabbit
FatRhabbit

Reputation: 11

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?

Upvotes: 1

Views: 111

Answers (3)

Freddy Mcloughlan
Freddy Mcloughlan

Reputation: 4496

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

https://www.w3schools.com/python/python_try_except.asp

Upvotes: 1

gozly
gozly

Reputation: 21

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

Upvotes: 1

carlosdafield
carlosdafield

Reputation: 1537

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

Upvotes: 2

Related Questions