在Python中将str更改为int

kev*_*pah 1 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
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:AttributeError:类型对象'int'没有属性'getLevel'除了将str更改为int之外,我是否使用任何不良技术?我真的想改进我的编程思想和代码编写.谢谢 :)

Gar*_*tty 8

int()是一种类型,所以要实例化它,你需要做int(getLevel),而不是int.getLevel.

查看文档以获取示例等.

另请注意,这getLevel是变量的奇怪名称,因为它意味着它是一个给出级别的函数.一个更好的名字就是level.

值得注意的是,input()将输入评估为Python代码(在Python 2.x中,在3.x中它与raw_input()旧版本中的作用相同),因此getLevel已经是一个数字,但我建议使用,raw_input()而是保持转换字符串为整数,因为它不允许任意执行代码,这要好得多.