有没有办法更改输入数据类型?

我在 python 中编码,我想知道是否有办法更改输入的数据类型。我设计了一个代码来表示我的问题:


        menu= input("test>>> ")

    if (menu)==("forprint"):

    fortimes= input ("range>>>>")

    forprintwhat= input ("print>>>>>")

    for x in range (fortimes):

        print (forprintwhat)

现在很明显,我得到了这个错误:


Traceback (most recent call last):

File "C:/Users/vas71/AppData/Local/Programs/Python/Python38/leaf.py", line 15, in <module>

for x in range (fortimes):

TypeError: 'str' object cannot be interpreted as an integer

注意:错误消息显示“第 15 行”,因为我是从较大的文本中复制它。我的问题是,如何使字符串成为整数以便我的代码工作?是否可以?感谢您的帮助!


慕无忌1623718
浏览 112回答 1
1回答

长风秋雁

您可以将输入转换为整数:fortimes = int(input("range>>>>"))请允许我建议您使用 try-except 块进行输入验证。像这样简单的东西:while True:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; fortimes = int(input("range>>>>"))&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; print("Enter valid range (numeric)")以防用户输入无效的范围输入。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python