输入任意数量的课程名称和百分比等级并将其写入文件

时间:2017-11-19 15:58:58

标签: python

这是我到目前为止所做的尝试,但是我很难在循环输入并继续获取 TypeError:+:' int'不支持的操作数类型和' str'

def main():
#lists
    courses=[]
    grade=[]

#Entering input
    courses.append(input('Enter course or press Enter to quit '))
    grade.append(int(input('Enter percent achieved ')))

    grades=open("grades.txt",'w')



#loop to write to file
    for element in courses:
        grades.write(element + '\n')

    for element in grade:
        grades.write(element + '\n')





#close file and print

        return
if input==''
print('File was created and closed')  


main()

这是一个程序应该如何运行的例子

SAMPLE RUN

Enter course or Enter to quit math

Enter percent achieved 88

Enter course or Enter to quit comm

Enter percent achieved 93

Enter course or Enter to quit chem

Enter percent achieved 80

Enter course or Enter to quit ethics

Enter percent achieved 96

Enter course or Enter to quit 

File was created and closed

1 个答案:

答案 0 :(得分:0)

目前的问题是这一行:

grade.append(int(input('Enter percent achieved ')))

input()将userinput作为字符串返回,但是将其转换为整数。您不能简单地添加字符串和整数,因此您会收到错误。既然看起来除了将其写入文件之外,您实际上并没有使用等级做任何事情,最简单的解决方法是删除int():

grade.append(input('Enter percent achieved '))

这样脚本按预期工作(希望如此)并且文件写成功。如果你计划用它做其他(mathy)操作,你只需要将等级作为整数。如果你真的想因任何原因使用整数,你必须在编写文件时将其变回一个字符串,例如

grades.write(str(element) + '\n')
# str() to turn the grade into a string, 

编辑:循环使用多个输入:

循环输入的两种可能性。两者都是无限循环,因此脚本一直要求分级,直到用户故意退出。如果要限制迭代次数,也可以实现计数器,最大值或使用for循环。如果你愿意,我可以添加一个例子,但是现在它们似乎没必要。

版本1使用try除外。 当输入留空时,它会引发一个KeyboardInterrupt,它被except捕获并用于退出while循环。这不是最好的主意,因为它会捕获任何KeyboardInterrupt并让脚本继续,即使用户实际上试图阻止它。

版本2使用不同的输入来打破循环,避免了KeyboardInterrupt的问题。

# This will loop infinitely until the user exits by pressing enter on a blank input.
# Downside: This catches any KeyboardInterrupt including user's attempts to stop the 
# script.
while True:
    try: 
        courses.append(input('Enter course or press Enter to quit '))
    except KeyboardInterrupt:
        break

    try:
        grade.append(int(input('Enter percent achieved ')))
    except KeyboardInterrupt:
        break

    # Alternative: User enters x (or any other string you choose) to exit. 
while True:

    course = input('Enter course or enter x to quit ')
    grade =  int(input('Enter percent achieved '))

    if course.strip() == 'x' or grade.strip() == 'x':
        break
    # Exit the loop if x was entered. The strip removes any unwanted whitespace.
    # e.g. '   x' will still be recognised. ('X' will not though)

    courses.append(course)
    grade.append(grade)
    # Small advantage: If the user exits after entering a course, that course 
    # is not added to the file. In the other case you might have a course without grade.