Python Forum
I want to check if the input is str or is int & if it's str repeat the loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I want to check if the input is str or is int & if it's str repeat the loop
#3
Make a function to ask for integers, floats, etc...

from functools import partial


def ask(question, dtype=str, error_msg=None):
    while True:
        user_input = input(question)
        try:
            value = dtype(user_input)
        except ValueError:
            if error_msg:
                print(error_msg)
        else:
            return value


ask_int = partial(ask, dtype=int, error_msg="Please enter a valid integer.")
ask_float = partial(ask, dtype=float, error_msg="Please enter a valid float.")
ask_complex = partial(ask, dtype=complex, error_msg="Please enter a valid complex")
ask_int("How old are you? ")
Output:
In [26]: ask_int("How old are you? ") How old are you? 128 Out[26]: 128 In [27]: ask_int("How old are you? ") How old are you? 12.5 Please enter a valid integer. How old are you? aaaaaa Please enter a valid integer.
Just try following in the repl:

int("AAA")
You'll get a:
Error:
In [28]: int("AAA") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-28-ac34db391e65> in <module> ----> 1 int("AAA") ValueError: invalid literal for int() with base 10: 'AAA'
An illegal value for int raises the ValueError.
You can catch this Exception and continue.

try:
    value = int(input("Value: "))
except ValueError:
    print("Wrong value")
else:
    # all fine, no exception at all
    print(value)
Finally, I put this block in a while-True loop and the while-True loop in a function.
The else-block returns the value. In the case a ValueError happens, the else-block is not executed.
The function will not return the value and ask the user again for input.
HLD202 likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: I want to check if the input is str or is int & if it's str repeat the loop - by DeaD_EyE - Nov-23-2020, 03:55 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with to check an Input list data with a data read from an external source sacharyya 3 421 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  How to automate loop test check on Network device jpc230 1 589 Oct-09-2023, 09:54 PM
Last Post: Larz60+
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 1,074 Oct-01-2023, 07:36 PM
Last Post: ayodele_martins1
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,358 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Code won't break While loop or go back to the input? MrKnd94 2 967 Oct-26-2022, 10:10 AM
Last Post: Larz60+
  Repeat request by else stsxbel 2 1,185 Jul-30-2022, 03:34 PM
Last Post: stsxbel
  get out of while loop and stop repeat Frankduc 11 3,001 Apr-26-2022, 10:09 PM
Last Post: deanhystad
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,497 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  Avoid multiple repeat in indent Frankduc 8 2,908 Jan-18-2022, 05:46 PM
Last Post: Frankduc
Exclamation question about input, while loop, then print jamie_01 5 2,687 Sep-30-2021, 12:46 PM
Last Post: Underscore

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020