.write必须立即执行才能设置为变量

时间:2019-04-18 09:54:22

标签: python python-3.x

我是新手,作为我第一个为期1周的项目,我决定我可以创建一个不太好的随机网站,但永远不会少于一个随机网站。因此,在这里我一开始就陷入了困境,因为很明显,如果不能立即执行.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是文件打开名称。

2 个答案:

答案 0 :(得分:1)

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

这还意味着,一旦将randomchoice设置为随机值,它将永远设置为该值,并且循环将永远不会结束。考虑一下,然后重新开始您的程序。

答案 1 :(得分: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>写入文件,因为我们只是在不是该值的情况下才写入文件。但这是我目前所能解决的问题。