English 中文(简体)
是否有办法将这一变量变成一个经营人[复制]
原标题:Is there a way i could turn this variable into an operator [duplicate]
  • 时间:2024-05-13 00:43:11
  •  标签:
  • python
t = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
t2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

number1 = int(t[randint(0, 9)])  
number2 = int(t2[randint(0, 9)])
operator = buttonbox ("What do you want your questions to be?",choices = ["+","*","/","-"])
question = integerbox("What is " + str(number1) + operator + str(number2) + " ?")
    
if question == number1 operator number2:

我期望它将经营者的选择变成一个适当的变量。

问题回答

I suggest to use a mapping of operator strings to corresponding functions:

operator_mapping = {
    "+": lambda x, y: x + y,
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y,
    "-": lambda x, y: x - y
}

之后,你可以利用:

operator_function = operator_mapping[operator_choice]

• 尽可能:

question = integerbox("What is " + str(number1) + " " + operator_choice + " " + str(number2) + " ?")

# Calculate the expected answer
expected_answer = operator_function(number1, number2)

# Check if the user s answer is correct
if question == expected_answer:
    print("Correct!")
else:
    print("Incorrect. The answer is", expected_answer)

遵循你想要达到的完全法典:

from random import randint
from easygui import buttonbox, integerbox

number1 = randint(1, 10)  
number2 = randint(1, 10)

operator_choice = buttonbox("What do you want your questions to be?", choices=["+", "*", "/", "-"])

# Mapping operator strings to corresponding functions
operator_mapping = {
    "+": lambda x, y: x + y,
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y,
    "-": lambda x, y: x - y
}

# Get the function corresponding to the selected operator
operator_function = operator_mapping[operator_choice]

# Construct the question
question = integerbox("What is " + str(number1) + " " + operator_choice + " " + str(number2) + " ?")

# Calculate the expected answer
expected_answer = operator_function(number1, number2)

# Check if the user s answer is correct
if question == expected_answer:
    print("Correct!")
    buttonbox("Correct")
else:
    print("Incorrect. The answer is", expected_answer)
    buttonbox("Try next one ...")

请注意,按照本法典的规定,我有点使用了从愤怒到扼杀的转换,然后又回到愤怒状态。


为使《守则》成为从1到10号基本业务的培训员,这一版本使得有可能在不需要重新启动的情况下继续实施,允许在不正确的情况下作出多重答复,并解决在结果不是仓促价值或负面的情况下,就划分和减员提出问题:

from random import randint
from easygui import buttonbox, integerbox, textbox

msgBoxSampleText =  "This is a sample text.
You can display multiple lines using the newline character."
msgBoxWindowTitle = "Sample Text Input Box"
#print ( textbox(msgBoxSampleText, msgBoxWindowTitle) )
#exit()

alternative_to_operator_mapping_using_lambda ="""
import operator
operator_mapping = {
     +  : operator.add,
     -  : operator.sub,
     *  : operator.mul,
     /  : operator.truediv,
     %  : operator.mod,
     **  : operator.pow,
     //  : operator.itruediv
}"""
# Mapping operator strings to corresponding functions
operator_mapping = {
    "+": lambda x, y: x + y,
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y,
    "-": lambda x, y: x - y
}
response = "Next one please ..."

while response == "Next one please ..." :

    operator_choice = buttonbox("What do you want your questions to be?", choices=["+", "*", "/", "-"], default_choice="+")
    if operator_choice is None :
        break

    # Get the function corresponding to the selected operator
    operator_function = operator_mapping[operator_choice]

    modulo = 1
    while modulo  != 0 : 
        number1 = randint(1, 10)  
        number2 = randint(1, 10)
        if operator_choice == "/":
            modulo = number1 % number2
        elif operator_choice == "-" :
            if number2 > number1: 
                modulo = 1
            else:
                modulo = 0
        else :  
            modulo = 0

    # Construct the question
    question = integerbox("What is " + str(number1) + " " + operator_choice + " " + str(number2) + " ?")

    # Calculate the expected answer
    expected_answer = operator_function(number1, number2)

    if question == expected_answer :
        print("Correct!")
        print( f"{response=}" )
    else:
        while question  != expected_answer  :
            print("Incorrect. The answer is", int(expected_answer))
            buttonbox("Try once again ...", choices=["OK"], default_choice="OK")
            question = integerbox("What is " + str(number1) + " " + operator_choice + " " + str(number2) + " ?")
    response = buttonbox("Correct", choices=["OK", "Next one please ..."], default_choice="Next one please ..." )

每个运营商在<代码>operator模块中都有功能等同。 例如,

from operator import add

assert add(3, 5) == 3 + 5

You can build a dictionary mapping strings to such functions.

ops = {"+": add}
assert ops["+"](3, 5) == 3 + 5




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签