Python Forum
I want to check if the input is str or is int & if it's str repeat the loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I want to check if the input is str or is int & if it's str repeat the loop (/thread-31105.html)



I want to check if the input is str or is int & if it's str repeat the loop - HLD202 - Nov-23-2020

I want to check if The input is 'str' or it's 'int' and if it's 'str' repeat the loop...
but i don't know how to check if the input was for example: dds

while True:
    rows_input = input("Enter Rows: " )
    cols_input = input("Enter Cols: " )
    
    if int(rows_input) and int(cols_input): #here i'm trying to check it but i get error
        # i want to check if it's possible to convert the str to int then close the loop but i can't
        break
    else:
        print("you have to Enter a Number not string... [Try again]")
# Here are inputs
>>> Enter Rows: dds
>>> Enter Cols: 2
Error:
Traceback (most recent call last): File "Matrix_Calculator.py", line 5, in <module> if int(rows_input) and int(cols_input): #here i'm trying to check it but i get error ValueError: invalid literal for int() with base 10: 'dds'
but if the inputs be int, there's no problem and no error and the loop ends
>>> Enter Rows: 2
>>> Enter Cols: 2
Error:
No Error



RE: I want to check if the input is str or is int & if it's str repeat the loop - GOTO10 - Nov-23-2020

Check out this link to read about exception handling. In a nutshell, you can use try to attempt code that may cause an exception, and except to execute code only if an exception is encountered.

The example below will exit the while loop if both input variables are successfully converted to integers, but will print the try again message if a ValueError exception occurs.

while True:
    rows_input = input("Enter Rows: " )
    cols_input = input("Enter Cols: " )

    try:
        rows = int(rows_input)
        cols = int(cols_input)
        break

    except ValueError:
        print("you have to Enter a Number not string... [Try again]")



RE: I want to check if the input is str or is int & if it's str repeat the loop - DeaD_EyE - Nov-23-2020

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.


RE: I want to check if the input is str or is int & if it's str repeat the loop - jefsummers - Nov-23-2020

@GOTO10 approach is best, but if you are trying to avoid try-except blocks (?why), consider - input yields a string. You can loop through the input string to check to see if each character is between 0 and 9 (this does not work for negatives). If you find a character outside that range the input is not an integer.


RE: I want to check if the input is str or is int & if it's str repeat the loop - perfringo - Nov-23-2020

I just observe that converting to int is probably not the only problem. I assume that some sort of matrice or table would be constructed based on number of rows and columns. Quite obviously one will have problems constructing such with negative or 0 values. int() will happily accept these values:

>>> int('-42')     # does -42 rows make sense?
-42
>>> int('0')       # does 0 columns make sense?
0