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
#1
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
Reply
#2
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]")
HLD202 likes this post
Reply
#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
#4
@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.
Reply
#5
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
HLD202 likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


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 317 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  How to automate loop test check on Network device jpc230 1 544 Oct-09-2023, 09:54 PM
Last Post: Larz60+
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 990 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,258 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Code won't break While loop or go back to the input? MrKnd94 2 906 Oct-26-2022, 10:10 AM
Last Post: Larz60+
  Repeat request by else stsxbel 2 1,150 Jul-30-2022, 03:34 PM
Last Post: stsxbel
  get out of while loop and stop repeat Frankduc 11 2,866 Apr-26-2022, 10:09 PM
Last Post: deanhystad
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,434 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  Avoid multiple repeat in indent Frankduc 8 2,789 Jan-18-2022, 05:46 PM
Last Post: Frankduc
Exclamation question about input, while loop, then print jamie_01 5 2,616 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