# 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)
当我在控制台中输入一个浮点数时,控制台会打印出以下内容:
^{pr2}$我只是好奇如何让控制台不打印出消息和正确的号码。在
跟踪代码以了解它为什么不起作用:
此行不向用户提供提示。然后它将从标准输入中读取字符,直到到达行尾。读取的字符被分配给变量
UserAnswer
(作为类型str
)。在同样,在读取输入之前不向用户提供提示。新输入将与
UserAnswer
中的值(刚刚在上一行中输入)进行比较。如果这个新输入等于上一个输入,则执行下一个块。在连续第三次读取输入而不显示提示。尝试将第三个输入解析为浮点数。如果无法解析此新输入,将引发异常。如果它被解析,它被分配给
UserAnswer
。在仅当第二个输入不等于第一个输入时才计算此表达式。如果这令人困惑,那是因为代码同样令人困惑(可能不是您想要的)。第一个输入(它是一个字符串)与一个新创建的float对象进行比较,该对象具有
float()
函数返回的默认值。在因为字符串永远不等于浮点,所以“不等于”测试将始终为真。在
因此,这条信息就被打印出来了。在
将整个代码部分更改为如下所示(但这只是一个典型的示例,实际上,您可能需要一些不同的行为):
这是一种确保从用户处获得可解释为浮点值的方法:
它的想法是尝试将用户输入的字符串转换为一个float,然后在失败时再请求一次。如果它签出,
break
来自(无限)循环。在您可以构造条件if语句,使其产生的数字类型不仅仅是float
相关问题 更多 >
编程相关推荐