當input輸入內容的時候,許多情況下輸入回車鍵另起一行輸入,但是這時候Pycharm就執行程序,然后結束,導致無法繼續輸入內容。
原因:Python默認遇到回車的時候,輸入結束。所以我們需要更改這個提示符,在遇到其他字符的時候,輸入才結束。
比如有一個任務:
請輸入文件名:憫農.txt
請輸入內容【單獨輸入‘:q‘保存退出】:
鋤禾日當午,汗滴禾下土。
誰知盤中餐,粒粒皆辛苦。
代碼如下:
# -*- coding: utf-8 -*-file_name=input("請輸入文件名:")file_name=file_name+".txt"something_file=open(file_name,"w")stopword=":q"file_content=""print("請輸入內容【單獨輸入‘:q‘保存退出】:")for line in iter(input,stopword): file_content=file_content+line+"/n"print (file_content,file=something_file)something_file.close()
或者:
# -*- coding: utf-8 -*-def file_write(file_name): f = open(file_name, 'w') print('請輸入內容【單獨輸入/':q/'保存退出】:') while True: file_content = input() if file_content != ':q': f.write('%s/n' % file_content) else: break f.close()file_name = input('請輸入文件名:')file_write(file_name)
以上這篇python將回車作為輸入內容的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答