Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何调用列表中的项目?_Python - Fatal编程技术网

Python 如何调用列表中的项目?

Python 如何调用列表中的项目?,python,Python,我的代码有什么问题?目前,它只是在问关于名字的问题,而不是别的问题?我认为这是一种从列表中调用项目的方式;我用了字符串,但我认为这是不正确的。有人能帮我做什么吗 subs=["Multiplication" , "Addition" , "Subtraction"] import random score=0 def addition_sub1(): a=random.randint(1,20) b=random.randint(1,20) question1=int(i

我的代码有什么问题?目前,它只是在问关于名字的问题,而不是别的问题?我认为这是一种从列表中调用项目的方式;我用了字符串,但我认为这是不正确的。有人能帮我做什么吗

subs=["Multiplication" , "Addition" , "Subtraction"]
import random
score=0
def addition_sub1():
    a=random.randint(1,20)
    b=random.randint(1,20)
    question1=int(input("What is" +str(a)+ "+" +str(b)+ ""))
    c=(a+b)
    if question == c:
        print("Correct!")
        score=score+1
    else:
        print("Incorrect!")
        return score

def subtraction_sub1():
    d=random.randint(1,20)
    e=random.randint(1,20)
    question2=int(input("What is" +str(a)+ "+" +str(b)+ ""))
    f=(d+e)
    if question2 == f:
        print("Correct!")
        score=score+1
    else:
        print("Incorrect!")
        return score

def Multiplication_sub1():
    g=random.randint(1,20)
    h=random.randint(1,20)
    question2=int(input("What is" +str(a)+ "+" +str(b)+ ""))
    i=(d+e)
    if question2 == i:
        print("Correct!")
        score=score+1
    else:
        print("Incorrect!")
        return score

name=input("What is your name? ")
print("Welcome to my quiz " +name)
for i in range(0,9):
    op=random.choice(subs)
    if op == str(0):
        Multiplication_sub1()
    if op == str(1):
        addition_sub1()
    if op == str(2):
        subtraction_sub1()
random.choice将从列表中返回一个随机元素。因此,代码应该是:

if op == "Multiplication":
    Multiplication_sub1()
if op == "Addition":
    addition_sub1()
if op == "Subtraction":
    subtraction_sub1()
然而,我想给你一些建议

在不同的函数中可以使用相同名称的变量。您可以在所有函数中称它们为a、b和问题

因为这三个if条件是互斥的,所以应该用elif替换底部的两个条件


str0=='0',因此永远不会等于random.choicesubs。你可以把函数放在一个随机的列表中。选择[加法,减法,乘法]会随机调用一个。输入不是更清楚地被称为答案吗?令人困惑