user3763437
user3763437

Reputation: 359

Python ValueError when multiplying integers

I searched for this error, but I didn't find answer. Simple calc program:

import sys
from sys import argv

first = int(sys.argv[1]) 
operation = sys.argv[2]
second = int(sys.argv[3])

if operation == '+':
    total = first + second        
if operation == '-':
    total = first - second
if operation == '*':
    total = first * second
if operation == '/':
    total = first / second

print "%d %s %d = %d" % (first, operation, second, total) 

When I enter: python first.py 2 / 2 I get correct output, same with - and +, but when I enter python first.py 2 * 2 I get:

Traceback (most recent call last):
  File "first.py", line 7, in <module>
    second = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 'first.py'`

Upvotes: 0

Views: 47

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121196

* is a shell meta character, meaning: list all the files in the current directory here.

As a result, sys.argv does not get set to ['first.py', '2', '*', '2'] but to ['first.py', '2', 'some-filename.txt', 'first.py', 'another-filename.py', '2'] or similar, because the shell has expanded * to all filenames first, then called Python with those names.

Escape the * in the shell:

python first.py 2 \* 2

Upvotes: 3

Related Questions