TypeError:无法连接“str"和“int"对象有人可以帮助新手使用他们的代码吗? [英] TypeError: cannot concatenate 'str' and 'int' objects Can someone please help a newbie with their code?

查看:49
本文介绍了TypeError:无法连接“str"和“int"对象有人可以帮助新手使用他们的代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢任何帮助,还有任何大缺陷或您在我格式化的方式或一些基本的东西中看到的东西,请指出.谢谢!

Any help is appreciated, also any big flaws or something you see in the way im formatting or something basic, please point it out. Thanks!

day = raw_input("How many days?")
locations = raw_input("Where to?")
days = str(day)
location = str(locations)
spendingMoney = 100


def hotel(days):
    return 140 * days

def destination(location):
    if location == "los angeles":
        return 300
    if location == "boston":
        return 400

def rental(days):
    if days < 2:
        return 40 * days
    if days >= 2 and days <= 6:
        return days * 30
     if days >= 7:
        return days * 25

def total_cost(days, location):
    return hotel(days) + destination(location) + rental(days)


print total_cost(days, location)

推荐答案

首先要理解的是 raw_input 返回一个字符串,因此之后无需将结果转换为字符串.

First thing to understand is that raw_input returns a string, so there's no need to cast the result to a string afterwards.

>

您想要(我认为)是将 day 转换为 int,因此您需要更改顶部.

What you want (I think) is to cast day to an int, so you need to change the top part.

day = raw_input("How many days?")
location = raw_input("Where to?")
days = int(day)
spendingMoney = 100

在您的原始代码中,days 是一个字符串,因此您试图将字符串添加到整数(这引发了错误).

In your original code, days was a string, and so you were trying to add a string to and integer (which raised the error).

将字符串乘以整数是完全有效的,因为它只是简单地将原始字符串重复数次.

Multiplying a string by an integer is perfectly valid, as it simply repeats the original string several times over.

print 'foobar' * 5
# foobarfoobarfoobarfoobarfoobar

这篇关于TypeError:无法连接“str"和“int"对象有人可以帮助新手使用他们的代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆