1

Building a simple calculator for my first Python project and encountered a question shown in the comments below:

special_keys = ["`", "~", "!", "@", " ", "#", "$"]

while True:
    num1 = input("Enter First Number: ")
    if num1.isalpha():
        print("Invalid, Try Again.")
        continue

     # elif num1 contains an element or part of an
     # element in special_keys do the following:
         # print("Invalid, Try Again.")
         # continue

    else:
    num1 = float(num1)
    break
Stef
  • 13,242
  • 2
  • 17
  • 28
Mike S.
  • 35
  • 1
  • 5
  • Does this answer your question? [How do I check if a string is a number (float)?](https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float) – Stef Nov 01 '20 at 14:39

3 Answers3

2

All of this is not necessary. You can simply try to convert the input to a float. If it throws an error, it means that the input is not a valid number. You can catch this error using a try-except block and print Invalid:

while True:
    num1 = input("Enter First Number: ")
    try:
        num1 = float(num1)
        break 
    except ValueError:
        print("Invalid")

Output:

Enter First Number: >? 1`
Invalid
Enter First Number: >? 1-0-0
Invalid
Enter First Number: >? 100
Sushil
  • 5,440
  • 1
  • 8
  • 26
0

Instead of checking whether the string contains an alphabetic character or a special character, you can check directly whether it represents a number or not:

def input_number(prompt_msg, err_msg):
  we_got_a_number = False
  while not we_got_a_number:
    num_string = input(prompt_msg)
    try:
      num = int(num_string)
      we_got_a_number = True
    except ValueError:
      print(err_msg)
  return num

num1 = input_number("Enter First Number: ", "Invalid, Try Again.")

If you want to use floats instead of ints, just replace int(num_string) with float(num_string).

Stef
  • 13,242
  • 2
  • 17
  • 28
0

Instead of warn for alpha, you can warn for non digit :

if !num1.isisdigit():
    print("Invalid, Try Again.")
    continue
dspr
  • 2,383
  • 2
  • 15
  • 19
  • What if the user enters a negative number? What if we want to extend the functionality to decimal numbers, or use scientific notation? – Stef Nov 01 '20 at 14:26