Some of my functions and loops gets ignored

Hey guys! I started learning the basics of Python and programming in general and ran into a problem (look at the picture). I need to add integers to those lists and ignore any floating numbers. I do not understand why check_int (line 7) keeps getting False even when the number is an integer, and its completely ignores the condition I set in the while loop. How can I fix this? Is there a better way to do it? Thanks for help.

This problem lies with how input() works. If you use type() on the value of calling input() you will see it always returns a string value:

>>> type(input())
1
<class 'str'>

And a string value will not be equal to an integer value:

>>> '1' == 1
False

Assuming your user will always enter an integer value you can convert your input() to an integer value with int() before using the value.


Do note however this will result in a ValueError if the string is not the equivalent of an integer:

>>> int('d')
ValueError: invalid literal for int() with base 10: 'd'

You may not have learned about them yet, but in this case you can use a try/except statement to prevent an error from being thrown when you try to convert the value:

num = input()

try:
    num = int(num)
except ValueError:
    print('Please only enter a whole number')

This will also weed out any floats because you canโ€™t convert a string containing a period to an integer:

>>> int('1.0')
ValueError: invalid literal for int() with base 10: '1.0'
4 Likes

Thanks mate ,you solved my problem. But now I have another problem (unrelated to the previous one). The last digit I put in the negative numbers list doubles itself in the list. Do you have any idea why this is happening?

1 Like

the code continues running after you handled the exception. Which means the previous number (before the exception) gets added to the list again

you could add the conditional (if/else) to the try clause. Then the rest of the code doesnโ€™t run when an exception occurs

being able to โ€œwalk throughโ€ the flow of your code and program is a valuable thing, thankfully there are tools to help us:

Python Tutor - Visualize Python, Java, JavaScript, C, C++, Ruby code execution

line 7 also seems redundant. You already cast to integer, so why do it again?

4 Likes

thanks man my code is working now
appreciate the help guys

didnโ€™t noticed that lol