Home > front end >  How to prevent letters from being entered in the input module?
How to prevent letters from being entered in the input module?

Time:04-21

Sorry for bad english, I use google translator. I'm beginner Python programmist and i need to make it so that only numbers can be entered in the input (a and b), or that an error is displayed when entering letters. Thanks in advance for your reply. Here is my code:

from colorama import init 
init() 
from colorama import Fore, Back, Style
povt = True

print(Fore.GREEN   "\nMAX-calc")

while povt == True:
    

    what = input(Fore.WHITE   "\nAction "   Fore.GREEN   "( ,-, ×, /): "   Fore.YELLOW)
    
    a = input (Fore.WHITE   "First number: "   Fore.YELLOW)

    b = input(Fore.WHITE   "Second number: "   Fore.YELLOW) 
    
    psh = input("Enter y: ")
    if psh == "y":
        if not a:
            a=0
        if not b:
            b=0
   
    if what == " ":
            c=float(a) float(b)
            print(Back.YELLOW   Fore.BLACK   "Addition result:"   str(c))
    
    elif what == "-":
        c=float(a)-float(b)
        print(Back.YELLOW   Fore.BLACK  "Subtraction result:"   str(c))
        
    elif what == "×":
        c=float(a)*float(b)
        print(Back.YELLOW   Fore.BLACK  "Multiplication result:"   str(c))
        
    elif what == "/":
        c=float(a)/float(b)
        print(Back.YELLOW   Fore.BLACK  "Division result:"   str(c))
    
    else:
        print(Back.RED   Fore.BLACK   "Sorry, I don't know what a "   what   ", is, but I'll try to figure it out > ͜ 0 ")
        
    povto = input("Retry? (y, n): "   Back.BLACK   Fore.YELLOW)
    
    if povto == "n":
        povt = False
        
    elif povto == "y":
        povt = True
        
    else:
        povt = False
        print(Back.RED   Fore.BLACK   "OK... we will assume that the "   povto   " - means no > ͜ 0```

CodePudding user response:

A potential way of solving this would be:

keep_asking = True
while keep_asking:
    a = input("Please input a number: ")
    try:
        a = int(a)
    except ValueError:
        pass
    else:
        keep_asking = False

Essentially, this means that the binary variable keep_asking will remain True (and hence the loop will keep asking) as long as the type casting via int() fails, but as soon as it succeeds that variable will flip to False, and the loop will not be executed further.

CodePudding user response:

You can try to do this inside your input-loop:

while True:
    try:
        a = float(input(Fore.WHITE   "First number: "   Fore.YELLOW))
    except:
        print(Fore.RED   "Please enter a number!")
    else:
        break

This tries to cast the input to float (or any other type you want) and will only move on if you input a number.

  • Related