-1
num = input('Select faces of Dice between [4, 6, 8, 12, 20].\n')
my_dice=Dice(int(num))
com_dice=Dice(int(num))

In class Dice, the __init__ method compares num with [4,6,8,12,20], and if there isn't a match, it prints an error message. I tried but it always print error message even if I enter 4 or 6. I thought input get its argument with type str, so I changed Dice(num) into Dice(int(num)) then it worked.

I want to know how I can get its argument type int when I enter it.

I'm using repl.it, with Python 3.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
하현호
  • 13
  • 4
  • 1
    So it printed an error message - but you somehow didn't think that the *exact text* of that message was relevant? It would, at the very least, tell you *where* the error occurred - which I suspect is in `Dice()`, rather than the code you posted. – jasonharper Apr 15 '20 at 08:12
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – dspencer Apr 15 '20 at 08:31

2 Answers2

0

According to python documentation here https://docs.python.org/3/library/functions.html#input

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>>
>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

It will convert it to string by default so you may continue to convert it after accepting the input. I hope this will be helpful to understand.

D.Malim
  • 86
  • 6
0

The input function always returns a string. This is a lot better than sometimes returning different types, depending on the text entered by the user! Python 2's input worked that way and it was a mess.

If you want num to be an integer, you can convert the string returned by input into an int directly:

num = int(input('Select faces of Dice between [4, 6, 8, 12, 20].\n'))

This is a little fragile though, as it will raise an exception if the user enters a non-integer value. If you want to print a nicer error message, you'll either need to write exception handling code, or you will want to save the string first, and check if it's numeric before attempting to convert it.

Blckknght
  • 100,903
  • 11
  • 120
  • 169