简体   繁体   English

str() 在我的函数体中不起作用

[英]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.我得到的错误是 python 无法连接 string 和 int,即使我使用str()将 int 转换为字符串。

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().并省略先前对 str() 的调用。 Additionally, total_Salary = 0 has no influence as you're changing the variable afterwards.此外, total_Salary = 0没有影响,因为您之后要更改变量。


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.我认为你的第一个 if/else 表达式更具可读性,应该改用。

replace :代替 :

str(total_Salary)

return "$" + total_Salary

with

return "$" + str(total_Salary)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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