在Python中将str改为int

2024-06-13 09:45:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我正在做一个小的elavator程序。

代码:

import time
elavator = True
# 0 is B floor // basement
elavatorFloors = [0,1,2,3,4,5]

while elavator == True:
    getLevel = input ("Which floor would you like to visit? ( 1 - 5) ")
    time.sleep(2)
    print "you're now at floor, " +int.getLevel

我得到这个错误:attribute error:type对象“int”没有属性“getLevel” 除了将str改为int之外,我是否使用了任何不好的技术?我真的想改进我的编程思维和代码编写。谢谢:)


Tags: 代码import程序youtrueinputtimeis
2条回答

下面是修改的示例代码:

import time
elevator = "false"
# 0 is B floor // basement
elavatorFloors = [0,1,2,3,4,5]
getLevel = input("Which floor would you like to visit? ( 1 - 5) ")
for x in elavatorFloors:
    if x == getLevel:
        time.sleep(getLevel)
        print "you're now at floor, " + str(getLevel)
        elevator = "true"
        pass
    else:
        pass
if (elevator == "false"):
    print "There is no floor: " +  str(getLevel)

int()是一个类型,因此要实例化它,需要执行int(getLevel),而不是int.getLevel

检查the docs以获取示例和更多信息。

还要注意getLevel是变量的一个奇怪名称,因为它意味着它是一个给出级别的函数。一个更好的名字应该是level

值得注意的是,input()将输入作为Python代码进行计算(在Python 2.x中,在3.x中,它的作用与在旧版本中的raw_input()相同),因此getLevel将已经是一个数字,尽管我建议使用raw_input(),并保持从字符串到整数的转换,因为它不允许任意执行代码,这样好多了。

相关问题 更多 >