Python 3.8 32 位。从用户输入创建任务管理器

所以我有这段代码,我试图从中创建一个任务管理器,它接受用户输入并将其放在新文件内的列表中。当我运行它并键入 exit 时,它给了我这个错误:TypeError: '<' not supported between 'str' and 'int' instnaces。


这是代码:


print('WELCOME TO YOUR TASK MANAGER!')


filename = input('What would you like your filename to be: \n(Please type \'.txt\' at the end of the 

name)');


tasks = []

with open(filename, 'w+') as f:

prompt = 'Please enter what you need to do: \n(separated by commas and a space. Ex: laundry, clean) \n When you are done puting in tasks please type \'exit\' '

user_input = f.write(input(prompt).strip())


while (user_input != 'exit'):

    tasks.append(user_input)

    user_input = input(prompt).strip()



tasks.sort()


print('\nAlphabetical order:')

for task in tasks:

    print(task)

有想法该怎么解决这个吗?


DIEA
浏览 63回答 2
2回答

牛魔王的故事

在这一行:user_input = f.write(input(prompt).strip())您将 的返回值f.write,即写入文件 (an int) 的字符数分配给user_input。然后,在第一个循环中,将此 int 附加到tasks.之后,您将字符串附加到此列表中。因此,当您尝试对其进行排序时,会出现错误,因为您无法比较整数和字符串。您可能的意思是,而不是user_input = f.write(input(prompt).strip()):user_input = input(prompt).strip()f.write(user_input)

慕婉清6462132

您正在分配一个变量f.write(input(prompt).strip())它返回写入文件的字符数,它是一个整数。因此,当您调用tasks.sort()您正在尝试对导致错误的整数和字符串进行排序。你可能打算做user_input&nbsp;=&nbsp;input(prompt).strip() f.write(iuser_input)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python