打印在if语句中不起作用

0 python printing if-statement

当我运行这个脚本时,它会跳过第8行的打印功能.我无法弄清楚为什么我的生活.我已经尝试了很多东西来使这个工作,但我似乎无法弄清楚这里的问题.我是Python的新手,请原谅我这是一个非常简单的问题.

编辑:woops,忘了实际代码!facepalm在这里是:

import webbrowser
import sys
b = webbrowser.get('windows-default')
print('Type start')
line1 = sys.stdin.readline()
start = 'start'
if line1 == start:
    print('What website do you want to open?')
line2 = sys.stdin.readline()
b.open(line2)
Run Code Online (Sandbox Code Playgroud)

dan*_*ano 5

当您键入'start'stdin然后按Enter键时,包含换行符的整个字符串最终会被存储line1.所以实际上,line1 == 'start\n'.\n在进行比较之前,您需要从字符串的末尾删除它.一种简单的方法是使用str.rstrip:

if line1.rstrip() == start:
    print('What website do you want to open?')
Run Code Online (Sandbox Code Playgroud)

编辑:

正如Ashwini Chaudhary在评论中指出的那样,你应该真正使用raw_input(或者input如果使用Python 3.x)而不是sys.stdin.readline.它会缩短您的代码,并且无需完全删除尾随换行符:

line1 = raw_input('Type start')
start = 'start'
if line1 == start:
    line2 = raw_input('What website do you want to open?')
    b.open(line2)
Run Code Online (Sandbox Code Playgroud)