如果没有立即执行,则不能将.write设置为变量

问题描述 投票:0回答:2

我是新人,作为我的第一个为期一周的项目,我决定创建一个不太好的随机网站,但从来没有一个随机的网站。所以在这里我一开始就陷入困境,因为显然,我不能将.write("something")指定为变量而不立即执行任何帮助是受欢迎的。

我尝试删除.write并像这样使用它

a = "some HTML code"
b = "more HTML code"
choice = [a,b]
randomchoice = random.choice(choice)
f.write(randomchoice)

但这只是在程序中写入a或b

问题:

f.write("""<head>
""")

choices = [ "a", "b" ]

a = f.write("</head>")
b = f.write("<title> A random program </title>")

randomchoice = random.choice(choices)

while randomchoice != "a":
    randomchoice

输出应该是</head><title> A random program </title>然后</head>,但输出同时编辑:f是文件打开名称。

python python-3.x
2个回答
0
投票

如上所述,f.write立即执行,只返回写入文件的字符数。我相信这将更符合您的要求。你的第一个片段接近于此。

f.write("""<head>
""")

a = "</head>"
b = "<title> A random program </title>"
choices = [a, b]  # actually use the variables as choices, not strings refering to those variables.

randomchoice = random.choice(choices)

while randomchoice != a:  # again use the variable to check, not the string.
    f.write(randomchoice)
    randomchoice = random.choice(choices)  # get the next random choice  

请注意,此设置永远不会实际将</head>写入文件,因为我们只是写入文件,如果它不是那个值。但就目前而言,这是我能解决的问题。


1
投票

线a = f.write("</head>")没有做你认为它做的。任何Python表达式都将执行赋值右侧的内容(在本例中将写入输出),然后将结果存储在变量中。

这也意味着一旦你将randomchoice设置为一个随机值,它将永远保持设置为该值,你的循环永远不会结束。考虑一下,再次开始你的程序。

© www.soinside.com 2019 - 2024. All rights reserved.