Barbaro
Barbaro

Reputation: 3

Program error TypeError: not all arguments converted during string formatting

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!

Upvotes: 0

Views: 1103

Answers (2)

Chris
Chris

Reputation: 22953

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:'))

Upvotes: 0

furas
furas

Reputation: 142641

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

Upvotes: 1

Related Questions