Python Input Value Integer Determination Function Basic Question

Asked 2 years ago, Updated 2 years ago, 140 views

Hello, I'm a beginner who recently started learning Python. I want to create a function that returns True or False by writing def and then returns a different value according to the returned True/False, but I don't know what to do.

For example,

def isInt(x):
    if int(x) == x:
        return True
    else:
        return False

x = input("Enter an integer: ")

Here, we want to create the next function that determines whether x is an integer or not, and if we get a False value back (unless it is an integer), we want to make sure that the character is entered again until the user enters the correct integer.

What should I do? I'd appreciate your help.

python def input

2022-09-22 08:31

2 Answers

Try it yourself. It's not difficult if you look at each line by line.

In [22]: def isInt(n): 
    ...:     ...:     return n.isnumeric() 
    ...:         

In [23]: def InputInt(): 
    ...:     ...:     while True: 
    ...:         ...:         i = input("Enter an integer: ") 
    ...:         ...:         if isInt(i): break 
    ...:     ...:     return i 
    ...:  

In [24]: a = InputInt()                                                                                                                     
Enter an integer: f
Enter an integer: 4

In [25]: a                                                                                                                                  
Out[25]: '4'


2022-09-22 08:31

Please run the sample below.

In [1]: i = None 

In [2]: while True: 
    ...:     ...:     i = input("Enter an integer: ") 
    ...:     ...:     if i.isnumeric(): break; 
    ...:                                                                                                                           
Enter an integer: d
Enter an integer: a
Enter an integer: 3

In [3]: i                                                                                                                                  
Out[3]: '3'


2022-09-22 08:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.