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
My code examples are always for Python >=3.6.0
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
Exclamation question about input, while loop, then print jamie_01 5 386 Sep-30-2021, 12:46 PM
Last Post: Underscore
  How to discard list repeat values akanowhere 7 1,138 Dec-28-2020, 09:14 PM
Last Post: akanowhere
  Loop back through loop based on user input, keeping previous changes loop made? hbkpancakes 2 1,199 Nov-21-2020, 02:35 AM
Last Post: hbkpancakes
  Check all input, easy way! Help pls! bntayfur 2 668 Jul-05-2020, 10:58 PM
Last Post: bntayfur
  input check help! bntayfur 3 976 Jun-02-2020, 11:38 PM
Last Post: bowlofred
  is there a way: repeat key word args Skaperen 2 861 Feb-03-2020, 06:03 PM
Last Post: Skaperen
  if-loop does not respond to input Kmarstein 1 948 Jan-28-2020, 09:29 PM
Last Post: Larz60+
  Nested Loop for user input Ads 2 1,920 Dec-30-2019, 11:44 AM
Last Post: Ads
  How to Loop my calculator input Michael1 2 1,871 Dec-13-2019, 04:57 AM
Last Post: ICanIBB
  MySql - Loop - CHeck File gcclinux 1 884 Nov-30-2019, 11:51 AM
Last Post: ThomasL

Forum Jump:

User Panel Messages

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