简体   繁体   English

Python不接受我的输入为实数

[英]Python does not accept my input as a real number

# Math Quizzes

import random
import math
import operator

def questions():
    # Gets the name of the user
    name= ("Alz")## input("What is your name")
    for i in range(10):
    #Generates the questions
        number1 = random.randint(0,100)
        number2 = random.randint(1,10)
    #Creates a Dictionary containg the Opernads
        Operands ={'+':operator.add,
                   '-':operator.sub,
                   '*':operator.mul,
                   '/':operator.truediv}
        #Creast a list containing a dictionary with the Operands       
        Ops= random.choice(list(Operands.keys()))
        # Makes the  Answer variable avialabe to the whole program
        global answer
        # Gets the answer
        answer= Operands.get(Ops)(number1,number2)
        # Makes the  Sum variable  avialbe to the whole program
        global Sum
        # Ask the user the question
        Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
        print (Sum)

        global UserAnswer

        UserAnswer= input()

        if UserAnswer == input():
            UserAnswer= float(input())            
        elif UserAnswer != float() :
            print("Please enter a correct input")


def score(Sum,answer):
    score = 0

    for i in range(10):
        correct= answer

        if UserAnswer == correct:
            score +=1

            print("You got it right")
        else:
            return("You got it wrong")


    print ("You got",score,"out of 10")     


questions()
score(Sum,answer)

When I enter a float number into the console the console prints out this: 当我在控制台中输入一个浮点数时,控制台将输出以下内容:

What is 95 * 10 Alz?
950

Please enter a correct input

I'm just curious on how I would make the console not print out the message and the proper number. 我只是对如何使控制台不打印消息和正确的号码感到好奇。

this is a way to make sure you get something that can be interpreted as a float from the user: 这是一种确保您可以从用户处获得可解释为浮动内容的方式:

while True:
    try:
        user_input = float(input('number? '))
        break
    except ValueError:
        print('that was not a float; try again...')

print(user_input)

the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. 想法是尝试将用户输入的字符串转换为浮点数,并在失败的情况下再次询问。 if it checks out, break from the (infinite) loop. 如果检出,请break (无限)循环。

You could structure the conditional if statement such that it cause number types more than just float 您可以构造条件if语句,使它导致数字类型不只是浮动

    if UserAnswer == input():
        UserAnswer= float(input())            
    elif UserAnswer != float() :
        print("Please enter a correct input")

Trace through your code to understand why it doesn't work: 遍历您的代码以了解为什么它不起作用:

 UserAnswer= input() 

This line offers no prompt to the user. 此行不提示用户。 Then it will read characters from standard input until it reaches the end of a line. 然后它将从标准输入中读取字符,直到到达行尾为止。 The characters read are assigned to the variable UserAnswer (as type str ). 读取的字符被分配给变量UserAnswer (类型为str )。

  if UserAnswer == input(): 

Again offer no prompt to the user before reading input. 再次在读取输入之前不提示用户。 The new input is compared to the value in UserAnswer (which was just entered on the previous line). 将新输入与UserAnswer的值进行比较(该值刚在上一行中输入)。 If this new input is equal to the previous input then execute the next block. 如果此新输入等于前一个输入,则执行下一个块。

  UserAnswer= float(input()) 

For a third time in a row, read input without presenting a prompt. 连续第三次读取输入而不显示提示。 Try to parse this third input as a floating point number. 尝试将第三个输入解析为浮点数。 An exception will be raised if this new input can not be parsed. 如果无法解析此新输入,则会引发异常。 If it is parsed it is assigned to UserAnswer . 如果已解析,则将其分配给UserAnswer

  elif UserAnswer != float() : 

This expression is evaluated only when the second input does not equal the first. 仅当第二个输入与第一个输入不相等时才计算该表达式。 If this is confusing, then that is because the code is equally confusing (and probably not what you want). 如果这令人困惑,那是因为代码同样令人困惑(可能不是您想要的)。 The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function. 将第一个输入(它是一个字符串)与一个新创建的float对象进行比较,该对象具有float()函数返回的默认值。

Since a string is never equal to a float this not-equals test will always be true. 由于字符串从不等于浮点数,因此此不等于测试将始终为真。

  print("Please enter a correct input") 

and thus this message is printed. 并因此打印此消息。

Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior): 将整个代码部分更改为类似的内容(但这只是一个代表性的示例,实际上,您可能需要一些不同的行为):

while True:
    try:
        raw_UserAnswer = input("Please enter an answer:")
        UserAnswer = float(raw_UserAnswer)
        break
    except ValueError:
        print("Please enter a correct input")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM