2016-02-04 106 views
-3

我無法允許用戶鍵入除整數以外的任何內容,因爲這樣做會使程序崩潰並且不打印我想要的文本。 **Click me to view**允許單詞輸入的Python

這是終端程序。 **Click me to view**

+4

請複製並粘貼實際的代碼。不要只鏈接到圖片 - 這是煩人的,沒有必要。 – viraptor

+0

爲python 2使用'raw_input'而不是'input'! –

回答

1

您需要使用的raw_input()爲Python 2.x的

guess = raw_input() 

而且代碼

elif: #Need help here! 

在語法上不有效 - 它需要一個條件子句。但是看着你的代碼,你可能會刪除「elif:」到「break」,因爲它只是複製下面的代碼。

0

線6 & 20,你應該使用

print 'No its '+str(ans) 
0
from random import randint 
import sys 

# Python version compatibility shim 
if sys.hexversion < 0x3000000: 
    # Python 2.x 
    inp = raw_input 
    rng = xrange 
else: 
    # Python 3.x 
    inp = input 
    rng = range 

TRIES = 10 

def main(): 
    print("Welcome to the Math Challenge!") 
    correct = 0 
    for m in rng(1, TRIES + 1): 
     n = randint(1, 16) 
     answer = m * n 
     guess = inp("What is {} x {}? ".format(m, n)) 
     try: 
      guess = int(guess) 
      if guess == answer: 
       print("That's right") 
       correct += 1 
      else: 
       print("Sorry, it's actually {}".format(answer)) 
     except ValueError: 
      # guess is not an int value 
      guess = guess.strip().lower() 
      if guess == "skip": 
       print("Skipping...") 
       continue 
      elif guess == "stop": 
       print("Stopping...") 
       break 
    print("You got {} correct out of {}!".format(correct, TRIES)) 

if __name__ == "__main__": 
    main()