【问题标题】:How could I use the except function with a for loop如何使用带有 for 循环的 except 函数
【发布时间】:2015-10-23 22:00:00
【问题描述】:

当有错误答案时,我希望显示所有操作员的预设消息。

可能是这样的:

while True:
    try:
        user_ans = int(input()) 
    except ValueError: 
        print ("That is not a valid answer")
        continue 
    else:
        break

但在 for 循环中。

我的目标是提出数字问题,然后保存到文件中。

首先,我需要询问用户他们上的是什么数学课,然后问 10 个随机生成的问题。

#Imports
import random
from time import sleep

#List & Definitions#
operators = ("-","+","X")
score = 0
QA = 0 

#Intro#
print ("Hello and Welcome")
print ("What is your name?")
name = input ()
print ("Do you want to Play (Yes/No)?")
choice = input()
if choice =="Yes":
    print ("Excellent")

if choice == "No":
    print ("Okey, bye...")
    end()
    quit()

print ("Please input your class")
cn = input ()
print ("Let's start the quiz!")
sleep(2) 

#Asking Questions
for QA in range (0, 10): 
    numb1 = random.randint(1,10)
    numb2 = random.randint(1,10)
    randOp = random.choice(operators)
    #Addition
    if randOp == "+" :
        print (str(numb1) + "+" + str(numb2))
        answer = numb1 + numb2

        print ("Please input your answer")
        UserAns = int(input ())
        if UserAns == answer :
            print ("well done that was correct")
            score = score + 1
        if UserAns != answer: 
              print("that's wrong")

        else:
            print ("Oops!  That was no valid number.  Try again...")

    #Subtracting        
    if randOp == "-" : 
        if numb2 > numb1 :
          print (str(numb2) + "-" + str(numb1))
          answer = numb2 - numb1
          print ("Please input your answer")
          UserAns = int(input ())
          if UserAns == answer :
              print ("woah again Correct")
          if UserAns != answer: 
              print("that's wrong")


              score = score + 1
        elif numb1 > numb2 :
            print(str(numb1) + "-" + str(numb2))
            answer = numb1 - numb2
            print ("Please input your answer")
            UserAns = int(input ())
            if UserAns == answer :
                  print ("Correct :) ")
                  score = score + 1
            if UserAns != answer: 
              print("that's wrong")

    #Multiplication
    if randOp == "*" :
        print (str(numb1) + "X" + str(numb2))
        ans = numb1 * numb2
        sleep(1)
        print ("Please input your answer")
        UserAns = int(input ())
        if ans == UserAns :
            print ("Correct")
            score = score + 1
        if UserAns != answer: 
              print("that's wrong")    

    #Displaying Score
    QA = QA + 1 
    if QA == 10 : 
        print ("Your score is " + str(score) + " out of ten")

#Saving & Writing to File
savePath = "Results\Class " + str(cn) + "\\" + name.lower() +".txt"
file = open(savePath, "a")
file.close()
file = open(savePath, "r")
if file.read() == "":
    file.close()
    file = open(savePath, "a")
    file.write(name + "\n\n")
    file.close()
file.close() 
file = open(savePath, "a")
file.write(str(score))
file.write("\n") 
file.close()

【问题讨论】:

  • 第二个sn-p代码的目的是什么?
  • 删除它;这是不需要的。
  • 这与javascript有什么关系?您是否基本上想要进行输入验证并处理用户输入“abc”而不是数字的情况?您的第一个 code-sn-p 中的方法是否有特别的地方不起作用?帮助我们帮助您。

标签: python validation input


【解决方案1】:

只是做更好的输入功能..

def input_with_choices(prompt, choices):
   while True:
      choice = input('{} (choices are: {}) '.format(prompt, ','.join(choices)))
      if choice in choices:
         return choice
      else:
         print("That's not a valid choice.")

def input_int(prompt):
   while True:
      try:
         return int(input(prompt))
      except ValueError:
         print("That's not an integer.")

等等

然后您可以使用它们在 for 循环中验证您的输入。

【讨论】:

    【解决方案2】:

    您的问题不是很容易理解,但是,我认为您正在寻找的是:

    accepted = False
    while not accepted:
        try:
            UserAns = int(input())
            accepted = True
        except:
            pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 2021-07-01
      • 1970-01-01
      • 2017-07-26
      相关资源
      最近更新 更多