【问题标题】:Letters inside "int(input(())"“int(input(())”中的字母
【发布时间】:2015-03-20 12:06:14
【问题描述】:
def multiply():                                                                                     #starts sub program when 'multiply()' is called
num1 = random.randint(1,12)                                                                     #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
    ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))          #asks question and requires a user input
    correct = (ans == num1 * num2)
    if correct:
        print("You are correct! ")
        break                                                                                   #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
    else:
        print("Wrong, please try again. ")
    loop == False                                                                               #if the answer is wrong, it loops back to when 'loop' was last 'True'

我想知道是否有办法让我包含一行代码,让我显示“这不是一个选项!”当在代码的第 5 行输入除数字以外的符号时。

【问题讨论】:

  • @user5061 由于他们print 语句的语法和使用input 而不是raw_input,我将假设3.x

标签: python numbers integer


【解决方案1】:

使用异常捕获意外输入。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random

def multiply():

    # Randomly generates a number between 1 and 12
    num1 = random.randint(1,12)
    num2 = random.randint(1,12)

    while True:

        i = input("What is the answer to {} x {} ".format(
            str(num1), str(num2)))

        try:
            ans = int(i)
        except ValueError:
            print('That is not an option!')
            continue

        if ans == num1 * num2:
            print("You are correct!")
            break
        else:
            print("Wrong, please try again.")

if __name__ == "__main__":

    multiply()

【讨论】:

    【解决方案2】:

    当您转换为int 时,他们可能会输入一个非整数值,因此转换将失败,因此您可以使用try/except

    def multiply():                                                                                     #starts sub program when 'multiply()' is called
        num1 = random.randint(1,12)                                                                     #randomly generates a number between 1 and 12
        num2 = random.randint(1,12)
        while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
            try:
                ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))          #asks question and requires a user input
                correct = (ans == num1 * num2)
                if correct:
                    print("You are correct! ")
                    break                                                                                   #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
                else:
                    print("Wrong, please try again. ")
                loop == False   
            except ValueError:
                print("That is not an option")
    

    请注意,您之前的代码现在嵌套在 try 块中。如果int() 因为输入错误而失败,它会抛出一个ValueError,您可以捕获并通知他们。

    作为旁注,另一种格式化您的问题的方式是

    'What is the answer to {} x {}?'.format(num1, num2)
    

    这是生成带有注入变量值的字符串的好方法。

    【讨论】:

    • 使用.format() 语法而不是%(num1,num2) 是否有区别/推荐?
    • @Trengot 请看this post
    猜你喜欢
    • 2018-01-26
    • 2017-09-24
    • 2014-07-24
    • 1970-01-01
    • 2015-09-13
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多