2016-03-21 9 views
2

こんにちは私はコーディングに新しいです、ここで私はユーザーの入力に基づいて簡単なコードを書いています。すべてのifとelifの応答を得ることはできますが、入力が整数でない場合はプログラムが失敗します。Python 3.1私のコードの "Else:"の問題

def tables_bussed(): 
    tables = input("How many tables can you bus per hour? (I can only read numbers.)") 
    if int(tables) > 80: 
     print ("That\'s rediculous, you lying twit.") 
     tables_bussed() 
    elif int(tables) > 60: 
     print ("If what you are saying is true then you have quite a talent!") 
    elif int(tables) > 30: 
     print ("Impressive! Yet there\'s always room for improvement, now isn\'t there.") 
    elif int(tables) > 0: 
     print ("How sad.") 
    else: 
     print ("Are you dumb or just daft.") 
     tables_bussed() 

tables_bussed() 

私のelse節には何かがありませんか?

+0

正確なエラーは何ですか?あなたの最終的な印刷はインデントされていませんが、コピー貼り付けの問題だと思いますか? – srowland

+2

インデントがありません – Sharad

+0

あなたのインデントがあなたのelseステートメントのように見えません。 – Loufylouf

答えて

3

あなたはexcept節試みを必要とする、私はあなたのプログラムを再実行したいが、ここで私はあなたが持っていないのtry句の整数としてテーブルを定義するので、一般的な概念

def tables_bussed(): 
    tables = input("How many tables can you bus per hour? (I can only read numbers.)") 
    try: 
     tables = int(tables) 
    except ValueError: 
     print ('Sorry dude, you must input a number that is an integer') 
     tables_bussed() 

ありませんint型(テーブル)ステートメントを使用repeatedyし、あなただけの値

のためのテストは、あなたがテーブルを定義した直後に置くことができます(あなたがあなたのコード内のいくつかのインデントの問題はなく、おそらくないを持って注意してください)

プログラムがしようとしますsuccessfuでない場合は、整数としてテーブルを解決するリットル、それは多くの条項を除き、試しについてそこにあり

再試行を促すだろう、彼らはあなただけで、whileループでそれをすべて入れ

+0

ありがとう作品!決してtry節の先頭にはいませんが、これは私の3日目の自分自身を教えています –

+2

これは効果的に再帰的ですwhileループはこの場合より良いオプションです – gkusner

+0

なぜそれが良いと思われる理由を説明してください私の答えの下にコメントをする。アサーションは、新しいプログラマにとってあまり有用ではありません。あなたは明らかにその事件を明らかにするべきです。あなたには例がありますが、私は一般的なループを嫌いですし、何が起こっているのか理解するのを手助けすると、ユーザーは最大の利益を得るでしょう。 – PyNEwbie

1

を持っているかもしれないユーザー入力の問題やその他の問題をキャッチするために非常に有用です:

def tables_bussed(): 
    while True: 
     tables = input("How many tables can you bus per hour? (I can only read numbers.)") 
     if tables.isdigit(): 
      if int(tables) > 80: 
       print ("That\'s rediculous, you lying twit.") 
       continue 
      elif int(tables) > 60: 
       print ("If what you are saying is true then you have quite a talent!") 
      elif int(tables) > 30: 
       print ("Impressive! Yet there\'s always room for improvement, now isn\'t there.") 
      elif int(tables) > 0: 
       print ("How sad.") 
      break 
     else: 
      print ("Are you dumb or just daft.") 

tables_bussed()