2013-12-14 38 views
-1

所以,我只是在python中混戰,而且我有一點小錯誤。腳本應該要求1,2或3.我的問題是,當用戶放入1,2或3以外的東西時,我會崩潰。就像,如果用戶放入4或ROTFLOLMFAO,它會崩潰。python - 試圖處理意外輸入時發生崩潰

編輯:好的,將它切換爲int(input())。但問題仍然存在 下面是代碼

#IMPORTS 
import time 
#VARIABLES 
current = 1 
running = True 
string = "" 
next = 0 
#FUNCTIONS 
#MAIN GAME 
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER") 
#while running == True: 
if current == 1: 
    next = 0 
    time.sleep(0.5) 
    print("You wake up.") 
    time.sleep(0.5) 
    print("") 
    print("1) Go back to sleep") 
    print("2) Get out of bed") 
    print("3) Smash alarm clock") 
    while next == 0: 
     next = int(input()) 
     if next == 1: 
      current = 2 
     elif next == 2: 
      current = 3 
     elif next == 3: 
      current = 4 
     else: 
      print("invalid input") 
      next = 0 
+1

你可以請發佈完整的stacktrace嗎? – thefourtheye

+0

我在python 2.7上測試過,用raw_input替換輸入。它不會崩潰,但總是發佈無效的輸入。(因爲接下來是str不是int) –

+0

@Herrington Darkholme:對不起,對Python很新。我試過了,但我怎樣才能讓下一個int?它不是已經被設置爲頂部的整數嗎? – lando111

回答

0

使用raw_input()input()後者EVAL所進行的輸入爲代碼。

而且也許只是建立一個問功能

def ask(question, choices): 
    print(question) 
    for k, v in choices.items(): 
     print(str(k)+') '+str(v)) 
    a = None 
    while a not in choices: 
     a = raw_input("Choose: ") 
    return a 

未經測試雖然

0

因爲輸入()爲您提供的字符串值,接下來是一個整數,可能是事故發生的,你的情況是因爲這種衝突。嘗試next = int(input()),我希望它能爲你工作:)