TypeError: unsupported operand type(s) for /: 'str' and 'str'
Asked Answered
K

5

31
name = input('Enter name here:')
pyc = input('enter pyc :')
tpy = input('enter tpy:')
percent = (pyc / tpy) * 100;
print (percent)
input('press enter to quit')

whenever i run this program i get this

TypeError: unsupported operand type(s) for /: 'str' and 'str'

what can i do to divide pyc by tpy?

Kettledrum answered 5/3, 2013 at 22:52 Comment(0)
A
35

By turning them into integers instead:

percent = (int(pyc) / int(tpy)) * 100;

In python 3, the input() function returns a string. Always. This is a change from Python 2; the raw_input() function was renamed to input().

Accrual answered 5/3, 2013 at 22:53 Comment(1)
Or, potentially, floats or decimal.Decimals as appropriate, if you need to accept numbers that are not whole integers.Luce
C
19

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100
Compliance answered 5/3, 2013 at 22:53 Comment(0)
C
4

There is another error with the forwars=d slash.

if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']
Commoner answered 24/6, 2020 at 19:32 Comment(1)
essentially - if you're concatenating paths with /, remove spaces between concatenated partsGilder
C
1

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail
Coauthor answered 6/3, 2013 at 2:49 Comment(2)
thanks, im new to programming and i never would have known to do thisKettledrum
If you're going to add in error handling, you probably want an except ValueError clause to handle invalid inputs…Aspergillus
S
-1
name = input ('What is your name?: ')
age = input('How old are you?: ')
date = input ('What year is it?: ')
year = (int(date) - int(age) + 100)

print('You\'ll be 100 in the year ', year)




#That's how I decided to hardcode it. You could get more specific with actual birthdates or else it'll probably be off by a year unless your bday passed.
Styliform answered 10/1, 2022 at 16:31 Comment(1)
This answer is a duplicate of two other answers to the question, and thus doesn't add anything useful to the post.Weal

© 2022 - 2024 — McMap. All rights reserved.