[英]why does this python program automatically close?
該程序在打印第一行后退出,並且似乎沒有進入while循環。 我在這里死胡同,任何幫助將不勝感激。 它的設計是在不同目錄下創建具有相同名稱的文件
print ("What is the name of the command to create?: ")
#loops until program is done
exit = "placeholder"
while exit != exit:
#filename to use for directory creation
cmd = input()
#combines cmd name with directory
cmdDir = "/usr/bin/" + cmd
#makes sure something was entered as a cmd name
if cmdDir == "/usr/bin/":
print ("Command name invalid. Try again: ")
else:
#creates file at directory with cmd name
open (cmdDir, 'a')
print ("Will this command have a python extension?: ")
#loops until program is done
while exit != exit:
decision = input()
#combines cmd name with python directory
pythonDir = "/root/python/" + cmd + ".py"
if decision == "yes":
#creates directory
open (pythonDir, 'a')
print ("Command directories " + cmdDir + " and" + pythonDir + " created. ")
#sets program to exit while loops
exit = "exit"
elif decision == "no":
print ("Command directory " + cmdDir + "created. ")
#sets program to exit while loops
exit = "exit"
else:
print ("Enter yes or no: ")
ps:使用4空格縮進手動格式化該格式很麻煩,自動縮進如何工作?
while exit != exit:
exit
始終等於exit
,因為它們是相同的變量(在某些情況下此規則有例外,但在Python中不是字符串類型)。 這樣該表達式將始終為false,並且您將永遠不會進入循環的主體。
您可能打算這樣做:
while exit != 'exit':
它將變量與固定的字符串常量進行比較。
while exit != exit:
是什么讓你煩惱。 由於它們是相同的變量,所以exit
始終等於exit
。 由於exit
是字符串,因此無法解決。
因此,您可能要使用的代碼可能是while exit != 'exit':
這將阻止程序在第1行退出。其原因是,如果變量exit
不具有'exit'
值,則程序將運行。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.