首页 > 解决方案 > “TypeError:'str' 对象不能解释为整数”

问题描述

我正在创建 n 个学生的名字,但我不能。我的源代码是:

n= input ("enter number of students")
for I in range(0,n):
    Stud_name=input ("enter the name of students")
    Print(stud_name)

标签: python-3.x

解决方案


用户输入文本,程序需要将其解析为整数。考虑到无法遵循简单说明的用户...

while True:
    try:
        n = int(input("Enter number of students: "))
        break
    except ValueError:
        print("Invalid number")

for i in range(1, n+1):
    stud_name = input("Enter the name of student {}: ".format(i))
    print(stud_name)

推荐阅读