Home > Net >  Hi, Im new and I want this code to be something that won't accept string as an input
Hi, Im new and I want this code to be something that won't accept string as an input

Time:12-01

myint = []

I want the list in this to only enter an integer and if not the input in is invalid and will create another code that says,"{} is not an integer. Try again." but I can't seems to know how to do that it's been 3 hours already

while 1:
    myint1 = input("Enter an integer: ")
    myint2 = list(map(int, myint))
    myint2.sort(reverse=True)
    myint3 = myint2.isInteger()

    if myint1 == "": >when press enter the code ends and show the sorted list
        print(f"sorted list: {myint2}")
        break
    myint.append(myint1)
# Python
# List
# Input
# Invalid code

CodePudding user response:

You can check whether the user inputs a number by trying to convert the input to an int. You can then use try except to throw an error message if they don't enter an int. See below:

list = [] # create list

while True:
    userInput = input("Enter a number: ") # user enters something

    try:
        number = int(userInput) # try to change the input to a number
        list.append(number) # if successful then append it
    except:
        print("Thats not a number!") # if it doesnt work print
        userInput = input("Enter a number: ") # and get them to re-enter
    print(list)

CodePudding user response:

2

mylist = []

while True:
    myinput = input("Enter an integer: ")
    if myinput == "":
        mylist.sort(reverse=True)
        print(f"\nsorted list: {mylist}")
        break
    try:
        number = int(myinput)
        mylist.append(number)
        
    except:
        print(f"{myinput} is not an integer. Try again: ")
        myinput = input("Enter an integer: ")
        number = int(myinput)
        mylist.append(number)
  • Related