Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

The code works fine but the only problem I encountered an error is:

 bad operand type for unary +: 'str'.

This is my code:

express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}

for x,y in express_file.items():

    print(x,'runs through',+y+ '.')

print('The following Expressway are included in this data set:')

for x in express_file.keys():

    print(x)

print('\nThe following Provinces are included in this data set:')

for x in express_file.values():

    print(x)

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-5-782fcd7b686e> in <module>

      1 express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}

      2 for x,y in express_file.items():

----> 3 print(x,'runs through',+y+ '.')

      4 print('The following Expressway are included in this data set:')

      5 for x in express_file.keys():

TypeError: bad operand type for unary +: 'str'

1 Answer

0 votes
by (36.8k points)
edited by

Use the print with an f-string

# replace print(x,'runs through',+y+ '.')

# with

print(f'{x} runs through {y}.'

# or with

print(x,'runs through ' +y+ '.') # note the added space after through and the removal of the ,

Updated script

express_file = {'TPLEX':'Pangasinan', 'SLEX':'Subic', 'Cavitex':'Bacoor,Cavite','MCX':'Muntinlupa','Star Tollway':'Laguna'}

for x,y in express_file.items():

    print(f'{x} runs through {y}.')

print('The following Expressway are included in this data set:')

for x in express_file.keys():

print(x)

print('\nThe following Provinces are included in this data set:')

for x in express_file.values():

print(x)

[out]:

TPLEX runs through Pangasinan.

SLEX runs through Subic.

Cavitex runs through Bacoor,Cavite.

MCX runs through Muntinlupa.

Star Tollway runs through Laguna.

The following Expressway is included in this data set:

TPLEX

SLEX

Cavitex

MCX

Star Tollway

The following Provinces are included in this data set:

Pangasinan

Subic

Bacoor,Cavite

Muntinlupa

Laguna

Do check out Data Science with Python Course which helps you understand from scratch.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...