2014-10-07 43 views
0

當我運行這個腳本時,它跳過了第8行的打印功能。我找不到爲什麼我的生活。我已經嘗試了很多東西來完成這個工作,但我似乎無法弄清楚這裏的問題。我對Python非常陌生,所以如果這是一個非常簡單的問題,請原諒我。打印在if語句中不起作用

編輯:woops,忘了實際的代碼! 捂臉那就是:

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) 
+2

看起來你忘了,包括腳本... – dano 2014-10-08 00:00:08

+0

哈哈只要我張貼意識到這點。現在修好! – HardenedMidget 2014-10-08 00:01:57

+3

您是否知道['raw_input'](http://docs.python.org/library/functions.html#raw_input)(或['input'](https://docs.python.org/3/library) /functions.html#input)在Python 3)?顯然你在這裏要求用戶輸入,所以最好使用這些方法而不是'sys.stdin.readline'。 – 2014-10-08 00:10:34

回答

5

當你鍵入'start'成標準輸入,然後按下回車鍵,整個字符串包括換行符最終被存儲在line1。所以在現實中,line1 == 'start\n'。在進行比較之前,您需要從字符串的末尾刪除\n。一個簡單的方法來做到這一點是使用str.rstrip

if line1.rstrip() == start: 
    print('What website do you want to open?') 

編輯:

由於阿什維尼·喬杜裏在評論中指出的,你真的應該僅僅是用Python 3.x的使用raw_input(或input如果)而不是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) 
+0

很好玩先生..好眼睛.. – brunsgaard 2014-10-08 00:05:02

+0

非常感謝,它現在的作品! – HardenedMidget 2014-10-08 00:09:11