Python Forum
New to the language. What am I doing incorrectly here? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: New to the language. What am I doing incorrectly here? (/thread-27749.html)



New to the language. What am I doing incorrectly here? - christopher3786 - Jun-19-2020

1) I ask the user to input a number as a string.
2) I convert the string to an integer.
3) I perform a comparison to see if the user's number is a multiple of 10.

number = input("Provide a number: ")
user_input = int(number)
if user_input % 10 == 0:
	print("Your number is a multiple of 10.")
else:
	print("Your number is not a multiple of 10.")
I receive the following error:
Error:
Traceback (most recent call last): File "main.py", line 2, in <module> user_input = int(number) ValueError: invalid literal for int() with base 10: 'Provide a number: '



RE: New to the language. What am I doing incorrectly here? - bowlofred - Jun-19-2020

Please use the python tags to show your code. It's much easier to understand.

Python here is declaring that the thing that was input was not an integer. We can't see your session to know what was wrong. If you want to test if it's really an integer rather than exiting if it's not, you can wrap the action in a try/except clause.

Also, you label the raw input as number, and after converting to an int(), you label it user_input. That seems backward to me. Maybe more like this:

import sys
user_input = input("Provide a number: ")
try:
    number = int(user_input)
except ValueError:
    print(f"{user_input} doesn't look like an integer to me.  Exiting")
    sys.exit()
if number % 10 == 0:
    print("Your number is a multiple of 10.")
else:
    print("Your number is not a multiple of 10.")



RE: New to the language. What am I doing incorrectly here? - buran - Jun-20-2020

assuming you enter a number, your code is working as expected.
The error you get, suggest that on line#1 you missed the input, i.e. I think you have line 1 like this:
number = ("Provide a number: ") # with or without the brackets
In other words - I think the code you run is not the same as the one you post here.


of course, as @bowlofred suggested, you can check the user input. No need for the sys.exit()
number = input("Provide a number: ")
try:
    user_input = int(number)
except ValueError:
    print(f"'{number}' is not a valid input.")
else:
    if user_input % 10 == 0:
        print("Your number is a multiple of 10.")
    else:
        print("Your number is not a multiple of 10.")



RE: New to the language. What am I doing incorrectly here? - pyzyx3qwerty - Jun-20-2020

Note: To make your code simpler, you could do
number = int(input("Provide a number: "))