简体   繁体   中英

str() doesn't work in the body of my function

I am trying to write a simple function where I need to concatenate a string and an integer converted into a string. My code is as follows:

def bonus_time(salary, bonus):
    total_Salary = 0

    if bonus == True:
        total_Salary = salary * 10
    else:
        total_Salary = salary

    print(total_Salary)    
    str(total_Salary)        
    return "$" + total_Salary

print(bonus_time(1000, True))

The error I get is that python cannot concatenate string and int, even though I am using str() to convert the int to a string.

Many thanks for any help.

You do not reassign the converted value. Simply change your return statement to

return "$" + str(total_Salary)

and omit the previous call to str(). Additionally, total_Salary = 0 has no influence as you're changing the variable afterwards.


Summing up, you could write:

def bonus_time(salary, bonus):
    total_Salary = salary * 10 if bonus else salary
    return "${}".format(total_Salary)

Or - even shorter, using the ternary operator:

 def bonus_time(salary, bonus): total_Salary = salary * 10 if bonus else salary return "${}".format(total_Salary)

I'd argue though that your first if/else expression is more readable and should be used instead.

replace :

str(total_Salary)

return "$" + total_Salary

with

return "$" + str(total_Salary)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM