0

I am trying to run a simple program to check a number to see if it is prime or not. I am having the user provide the number to check. But, I keep getting the following error when I run the program:

Traceback (most recent call last):
  File "HelloWorld.py", line 6, in <module>
    if num % test == 0 and num != test:
TypeError: not all arguments converted during string formatting

The following is my code:

num = input('Please choose a number between 2 and 9:')
prime = True 

for test in range(2,10):

    if num % test == 0 and num != test:
        print(num,'equals',test, 'x', num/test)
        prime = False

if prime:
    print(num, 'is a prime number!')
else:
    print(num, 'is not a prime number!')

I am using Python 3. Please let me know what I am doing wrong and how to understand why my program isn't running properly. Thanks in advance!

1
  • 2
    in Python 3 input() always returns text so you have to convert num into int - ie. num = int(num) Commented Dec 29, 2016 at 3:07

2 Answers 2

1

In Python 3 input() always returns string so you have to convert num into int - ie. num = int(num).

Now num % test means some_string % some_int and Python treats it as string formatting. It tries to use some_int as argument in string some_string but it can't find special place for this some_int and you get error.

BTW: https://pyformat.info

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That seems like an obvious thing that I must have overlooked.
0

Because input() returns a str object, num holds a string instead of an integer. When using the modulus operator on a string, Python assumes that you are trying to do c-style string formatting, but finds no speical formatting characters in your string, and raises an exception. '

If you want python to correctly interpret your program, you need to convert num to an int object instead of a str object:

num = int(input('Please choose a number between 2 and 9:'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.