【问题标题】:Getting back type error when trying to make user input calculator尝试使用户输入计算器时返回类型错误
【发布时间】:2020-07-16 23:03:47
【问题描述】:

我正在尝试制作工资单计算器,但我无法让输入值相乘。我想我正确地将代码转换为 int() 但是当我尝试将它们乘以不同的 var 时,它会在第 6 行返回一个“TypeError: can only concatenate str (not "int") to str"。我会喜欢一些反馈到似乎是什么问题。

hours = input("Enter number of hours you work: ")
hours = int(hours)
rate = input('Enter how much you make per hour: ')
rate = int(rate)
pay = hours * rate
print('You make $' + pay + ' a day')
days = input('Enter how many days you work a week: ')
days = int(days)
week = pay * days
print('You make $' + week + ' per week!')
month = week * 4
print('You make $' + month + ' a month!')
year = month * 12
print('You make $' + year + ' a year!!' )

【问题讨论】:

标签: python python-3.x


【解决方案1】:

print('You make $' + pay + ' a day') 这一行的错误是因为pay 是一个int 变量,但它被连接 到字符串。
在 print 语句中输入 cast pay 到 str,如下所示:

print('You make $' + str(pay) + ' a day')  

或者您可以使用逗号, 而不是串联+

print('You make $', pay, 'a day')

请注意,此方法将在打印时在变量周围添加一个空格。

理想

您应该使用 python 提供的格式。
f 字符串格式:

print(f'You make $ {pay} a day')

使用.format

print('You make ${} a day'.format(pay))

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多