gpt4 book ai didi

python - python3 中输出 "w"和循环的问题

转载 作者:行者123 更新时间:2023-11-30 23:32:05 26 4
gpt4 key购买 nike

我当前正在编写的程序有问题。

代码如下:

def main():

print ("This program let you create your own HTML-page,\nwith the necessary tags allready included")

t = ("<!DOCTYPE html>", "<html>", " <head>", " </head>", "<body>", "</html>") #Spaces for the indentation in the HTML-code.

menu = input("Press 1 to enter the file name for the html-page\nPress 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")

while True:
if menu == "1":
name = input("Enter the name for your HTML-page: ")
#with open(name + ".html", 'w') as doc:
#Here is the first problem, indenterror if uncommented, otherwise elif gets syntax error.
#And this is crucial to get the code into the HTML-document.
#The error without (with open(name + ".html", 'w') as doc:) will be "global name "doc" is not defined".
menu = input("Press 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
elif menu == "2":
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
doc.write(title)
print (t[3], file=doc) #</head>
menu = input("Press 3 to start entering code in body ")
elif menu == "3":
print(t[4], file=doc) #<body>
code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n")
doc.write('{0}\n'.format(code)) #For newline to get the HTML-code cleaner.
while code != "</body>":
code = input("")
doc.write('{0}\n'.format(code))
if code == "</body>":
print ("Congratulations! You have successfully created your own HTML-page by using this python program.")
print (t[5], file=doc) #</html>
#somewhere in the loop above is the second error, I want the </body> to end the program,
#but it loops line 25 (code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n"))


main ()

现在讨论问题。正如您所看到的,我正在尝试编写一个菜单,供用户从 3 个不同的任务中进行选择。他们所做的一切都应该输出到 .html 文档。

如您所见,我已在代码中评论了我的问题。

我不知道如何获取with open(name + ".html", 'w') as doc:没有 elif 的缩进变得困惑,或者我只是得到 elif 的语法错误。

第二个问题是我最后的循环。我希望命令退出程序,因为它还输出 .html 文档的正确结束代码,但它循环 code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n")我也搞不懂。

最佳答案

def main():

(...)
while True:
if menu == "1":
name = input("Enter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
menu = input("Press 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")

(...)
doc.close()


main ()

您可以像这样打开文件:doc = open(name + ".html", 'w'),但使用完毕后不要忘记关闭它,就像这样doc.close()

关于python - python3 中输出 "w"和循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com