mercredi 18 novembre 2020

Handle errors without hardcoding in python [duplicate]

I have a simple question. Does anyone know how I can do a simple error handling without repeating myself. I want the user to answer a question and if he/she answers in write format I want the next question to pass on with error handling without hardcoding for example:

enter code here
while True:
    try:
        n = input("Please enter an integer: ")
        n = int(n)
        break
except ValueError:
    print("No valid integer! Please try again ...")
if type(n) == int:
    while True:
        try:
            name = input("Enter your name")
            break
        except ValueError:
            print("No valid integer! Please try again ...")

if type(name) == str:
    print("Ok")

I would want to make this code much smoother but I'm obviously new to python and dont know how.

Aucun commentaire:

Enregistrer un commentaire