为什么我的python if else语句不能输入HTML?

时间:2019-11-02 21:57:15

标签: python

我正在尝试做到这一点,因此,当用户键入Y时,它将在电子邮件中创建HTML文件。但是每次到达代码中的该部分时,它都不会运行if else语句或HTML文件。

sendLetter = "let's send a letter to your boss and tell him how much you like your job y or n"
letterToBoss = """
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>


<h1>dear Boss/h1>
<p>This is a paragraph.</p>

</body>
</html>
"""

if enjoyJob == "n" or "N":
  print("that's so sad ".join(name))
  input("why do you hate " + job + "?")
if enjoyJob == 'y' or 'Y':
    print("that is awesome").join(name)
    input(sendLetter)
    if sendLetter() == 'y' or 'Y':
      f = open("letter_to_Boss.html", "x")
    f.write(letterToBoss)
    f.read("letter_to_Boss.html")
    f.close()
    if sendLetter() == 'n' or 'N':
        print("awe shucks")

2 个答案:

答案 0 :(得分:3)

1。您缺少输入代码。

enjoyJob = str(input("Do you enjoy your job?"))

2。不能使用or语句进行字符串比较。

if enjoyJob == "n" or "N": # Does not work.
if enjoyJob in ("n", "N"): # Does work.

Python将or语句的每一边视为自己。您的代码等同于执行以下操作:

bool1 = bool(enjoyJob == "n") # Depends on enjoyJob.
bool2 = bool("N") # Is always true, since its not an empty string. 

if bool1 or bool2:
    ....

3。 namejob未定义,.join()并未按照您的想象做。

print("that's so sad ".join(name))
input("why do you hate " + job + "?")
>>> a = "hey"
>>> a.join("lol")
'lheyoheyl'

4。 input(sendLetter)不会创建新变量sendLetter

您必须为输入分配一个变量,并且input函数的参数是输出给用户的内容。正确的用法是:

user_input = input("Please type in some input: ")

5。您必须说明如果用户未指定y,则逻辑必须执行的操作。

注意:

if sendLetter() == 'y' or 'Y':
  f = open("letter_to_Boss.html", "x")
f.write(letterToBoss)
f.read("letter_to_Boss.html")
f.close()

如果用户键入n,则由于文件f从未初始化,程序将崩溃。

6。您不(也不能)从打开的文件中读取。

f = open("letter_to_Boss.html", "x")
f.write(letterToBoss)
f.read("letter_to_Boss.html") # This will return an error. 
f.close()

f.read()不允许您读取文件(必须以读取文件的方式打开文件),并且出于您的目的,它没有用。


最终密码

通过上面的更正,您得到的代码看起来更像这样:

letterToBoss = """<html>"""

name = str(input("What is your name?"))
job = str(input("What is your job?"))
enjoyJob = str(input("Do you enjoy your job?"))

if enjoyJob in ("n", "N"):
    print(f"that's so sad {name}")
    input(f"why do you hate {job}?")
elif enjoyJob in ("y", "Y"):
    print(f"that is awesome {name}")

    sendLetter = input("Would you like to send an email to your boss?")
    if sendLetter == ("y", "Y"):
        f = open("letter_to_Boss.html", "x")
        f.write(letterToBoss)
        f.close()
    elif sendLetter == ("n", "N"):
        print("awe shucks")

答案 1 :(得分:0)

  1. input()返回一个值。您不先调用它,而是调用变量。因此,这是正确的:
if input(sendLetter) == 'y': # here comes the second problem
  1. or检查两个完整表达式是否为真。您不能像a == b or c那样使用它。或者,确切地说,您可以使用它,但是如果c不是None也不是0,则表示True,因此整个表达式都是true。但是,相反,如果要检查多个值,可以使用in
if input(sendLetter) in ('y', 'Y'):
    # code here