简体   繁体   中英

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.

You could structure the conditional if statement such that it cause number types more than just float

    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 ).

  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). 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 .

  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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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