Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if input is a number, and do something about it if it isn't?

As the title says, I’m trying to make a guessing game for fun. My only problem is figuring out if they did anything besides a flat number (no decimals, negatives, letters). If it is something besides that, it prints something.

import random
import time
streak = 0
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]



while True:
  answer = random.choice(numbers)
  insultlist = ["bro the real answer was " + answer + ", how are you even that bad?", "bro you suck at this, u werent even close. The correct answer was " + answer + "..", "it's the people like you who make me question the future of this planet. The actual answer was " + answer + ".", "lol u suck, the real answer was " + answer + "."]
  insultchoice = random.choice(insultlist)

  guess = input("Type a number between 1 and 10! ")


  if guess == answer:
    print("lol ur lucky, you guessed it correctly.")
    streak = streak + 1
    streakmsg = f"You're at a streak of {streak}."
    print(streakmsg)
    time.sleep(1)
    print("______________________________________________________")

  else:
    print(insultchoice)
    if streak >0:
      loststreak = f"You lost your streak of {streak}."
      print(loststreak)
      streak = 0
    time.sleep(1)
    print("______________________________________________________")
  

I tried using type(guess) and isnumeric, but they just ended up printing the same thing even if it is or isnt a number.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can just check if the string guess is numeric, and is more efficient than the regex solution.

if not guess.isnumeric():
    print("You didn't enter a number")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading