2015-02-06 107 views
0

我想編寫一個小腳本來告訴我從用戶輸入來看低音電平是否正常。Python 3.4用戶輸入

我剛學用戶輸入,這是我到目前爲止有:

def crisp(): 
    bass = input("Enter bass level on a scale of 1 to 5>>") 
    print ("Bass level is at") + bass 
    if bass >=4: 
     print ("Bass is crisp")  
    elif bass < 4: 
     print ("Bass is not so crisp") 
+1

什麼問題您有?從外觀上看,你需要將'低音'轉換爲一個整數。你的第一個'print'語句也需要包含括號中的所有內容。 – Holloway 2015-02-06 16:08:57

+0

問題是什麼? – 2015-02-06 16:31:38

回答

-1

我真的沒有在這裏看到一個問題,但只是一個簡單的程序,這樣做,只有這樣會這樣:

a=1 
while a==1: 
    try: 
     bass = input('Enter Bass Level: ') 
     print('Bass level is at ' + str(bass)) 
     if bass >=4: 
      print("Bass is crisp") 
     elif bass < 4: 
      print('Bass is not so crisp') 
     a=0 
    except ValueError: 
     print('Invalid Entry') 
     a=1 

與功能沒有太大的區別:

def Bass(): 
    a=1 
    while a==0: 
     try: 
      bass = input('Enter Bass Level: ') 
      print('Bass level is at ' + str(bass)) 
      if int(bass) >=4: 
       print("Bass is crisp") 
      elif bass < 4: 
       print('Bass is not so crisp') 
      a=0 
    except ValueError: 
     print('Invalid Entry') 
     a=1 
+2

您的代碼與Python 2.x有關。在Python 3.x中,來自2.x的'raw_input'是3.x中'input'的默認行爲。考慮到標題提到3.4,這個答案在技術上是錯誤的,但仍然可能有幫助。對於未來的觀衆:**出於安全原因,在Python 2.x代碼中使用'raw_input'而不是'input'。 – Poik 2015-02-06 16:28:48

+0

感謝您的解釋。我還沒有用過「嘗試」。我會看看。 – jahrich 2015-02-06 16:41:40

+0

非常有用。因爲我正在學習2並使用3個IDLE解釋器。 – jahrich 2015-02-06 16:43:04

0

轉換爲整數:

bass = int(input("Enter bass level on a scale of 1 to 5>>")) 
+0

謝謝你,我沒有將低音定義爲int。 :) – jahrich 2015-02-06 16:42:11

+0

請務必upvote或標記爲答案。 – 2015-02-06 18:13:59

1

當您通過內置函數獲取input()時,它將輸入視爲字符串。

>>> x = input('Input: ') 
Input: 1 
>>> x 
"1" 

相反,投int()input()

>>> x = int(input('Input: ')) 
Input: 1 
>>> x 
1 

否則,在你的代碼,你正在檢查if "4" == 4:,這是不正確的。

因此,這裏是你編輯的代碼:

def crisp(): 
    bass = int(input("Enter bass level on a scale of 1 to 5>>")) 
    print ("Bass level is at") + bass 
    if bass >=4: 
     print ("Bass is crisp")  
    elif bass < 4: 
     print ("Bass is not so crisp") 
+2

如果您使用的是Python 2.x,[不要使用'input',請始終使用'raw_input'](http://stackoverflow.com/a/7710959/786020)。 – Poik 2015-02-06 16:42:48

+0

是的,@BenMorris,但在[標籤:python-2.x]我會建議使用'raw_input()':) – 2015-02-06 16:43:29

+0

@Poik正確,謝謝:) – 2015-02-06 16:43:45