1

Fairly new to the Pythonic Way, but the below code doesn't work as expected, anyone know why? If I input 143.22 I get "not an int" response, rather than the expected collatz(143) e.g., int(143.22). BTW, this is one basic exercise in the Automate the Boring Stuff with Python beginners book (chapter 3 exercise on using functions). Thanks!

def collatz(myint) :
    print(myint)   
    if myint % 2 == 0 :
        myint = int(myint / 2)
    else:
        myint = int(myint *3 +1)
    if myint == 1 :
        print(myint)
        return myint
    else:
        collatz(myint)

try:
    x=input('Input a non-negative integer between 1 and infinity: ')
    val = int(x)
    if int(x) == abs(int(x)) :
        print("Yes input string is an Integer.")
        collatz(val)
    else:
        print('I did say NON negative!')
except ValueError:
    print("That's not a positive int!")
5
  • 1
    Indeed 143.22 isn't a positive int, it is a float. Do you want your program to handle both floats (by rounding?) and ints? Commented Dec 7, 2019 at 21:08
  • 3
    the error is caused from val = int(x). You can apply int(143.22), but you are not allowed to int('143.22'). Read more docs.python.org/3.8/library/functions.html#int Commented Dec 7, 2019 at 21:13
  • Also, you can replace int(x) == abs(int(x)) by val == abs(val). Commented Dec 7, 2019 at 21:17
  • 1
    It seems to me like your program is working fine. You are asking for a non-negative integer, and when giving it 143.22 it shouts "that's not an int". What seems to be the problem? Commented Dec 7, 2019 at 21:20
  • I believe @facehugger has it nailed; removing that (val=int(x)) line makes no difference in the functioning of the routine, so I consider this a learning exercise in type conversion/casting as well. Commented Dec 23, 2019 at 18:05

1 Answer 1

1

You are trying to run int('143.22')

For me, this yields:

Traceback (most recent call last):
File "main.py", line 1, in <module>
    int('143.22')
ValueError: invalid literal for int() with base 10: '143.22'

However, int(143.22) works fine.

A quick solution for your use case may be to cast it as a float.

float('143.22')

int(float('143.22'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Python appears to be somewhere a 'strongly typed' and 'loosely typed' language, my background with both Perl and C# seems to make the learning curve a bit longer, but ... worth the journey!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.