0

Another newbie question:
I'm trying to add a statement inside a while loop that if the person enters anything except integer it will repeat the input but I didn't figure out how to do that without ruining the program. Whenever I enter anything i get the following error: "ValueError: invalid literal for int() with base 10" What is needed to be added to my code?

Here is my code:

import random

#Playing dice game against the computer

num = int(input("Enter a number between 1 and 6 please: "))

while not int(num) in range(1, 7):
    num = int(input("Please choose a number between 1 and 6: "))

def roll_dice(num):
    computer_dice = random.randint(1, 6)
    if num > computer_dice:
        print("Congratulations you win! Your opponent's dice is:", computer_dice)
    elif num < computer_dice:
        print("Sorry but you lose! Your opponent's dice is:", computer_dice)
    else:
        print("Draw. Your opponent's dice is:", computer_dice)

roll_dice(num)

Thank you in advance!

Muratek
  • 11
  • 3
  • You need to catch the `ValueError` that's raised when a string that can't be converted to an integer is entered. Kevin's answer shows how to do that. – PM 2Ring Sep 02 '18 at 00:09
  • Try using this code (recognizes non-numeric inputs and numeric inputs): [code](https://repl.it/repls/PhysicalSunnyOpentracker) – U13-Forward Sep 02 '18 at 00:20
  • Thank you U9-Forward for the code example. "num.isdigit()==0" trick works nicely. – Muratek Sep 02 '18 at 09:01
  • PM-2ring I actually saw Kevin's answer before but since I wasn't sure how to implement his solution to my code, I wanted to ask here also. Thank you anyways. So try and expect functions inside While True statements are always used for these purposes? – Muratek Sep 02 '18 at 09:14

1 Answers1

0

I think the problem is that you are trying an empty string to an integer. Same problem when you type in alphabetical characters. You can use try and except to try the conversion of the input to an integer and then when it failed you run the loop again and when the conversion was successfully you have your number.

juliushuck
  • 1,398
  • 1
  • 11
  • 25