Reputation: 21
Sup guys and gals, I'm in the very beginnings of learning to code with python and am building a very basic percentage calculator to get the gears turning mentally.
I am having an issue with running a successful flow-through with the program:
#Percentage Calculator
print('Enter value of percent: ') #prompt user for input of percent value
percent = input() #gain user input about percent *stored as 'str'
percent = int(percent) #store and convert user input into an 'int' from 'str' for use in line 11
print('Enter value of percentaged number: ') #prompt user for input of percentaged number value
percentagedNum = input() #gain user input on percentaged number *stored as 'str'
percentagedNum = int(percentagedNum) #store and convert value from 'str' into 'int'
answer = percent / percentagedNum #calculate percentage formula
print(percent + '% of ' + percentagedNum + ' is ' + answer) #prompt user with answer
Also, the traceback:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1438, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Custom/PycharmProjects/PercentageCalculator/main", line 12, in <module>
print(percent + '% of ' + percentagedNum + ' is ' + answer)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I feel it's a concatenation issue with mixing strings, integers, and floats in the final print() function call.
Getting some good eyes on this would be greatly appreciated and thanks for all you guys do to help out the community. Much love.
Upvotes: 2
Views: 1584
Reputation: 444
you need to first cast the numbers as strings. you can do this explicitly:
print(str(percent) + '% of ' + str(percentagedNum) + ' is ' + str(answer))
or you can let Python f-strings take care of it:
print(f'{percent} % of {percentagedNum} is {answer}')
the reason what you were trying didn't work is that the +
operator has different results depending on what was given to it. If it has strings on either side, it concatenates:
>>> "foo" + "bar"
"foobar"
if it has integers on either side, it adds them:
>>> 5 + 3
8
When you mix the input types, it's not sure what it's supposed to do.
Upvotes: 1
Reputation: 23149
In your print
statement, make sure that you turn variables that contain numbers into strings by using str()
: str(percent)
and so on.
Indeed it's a classic error when you begin Python.
Upvotes: 0