需要使用Python中的全局变量分配提示进行分配

时间:2013-04-04 01:54:03

标签: python

需要这项任务的帮助:

**使用四个全局变量

foundCount  = 0
searchCount = 0
names = [ "Mary", "Liz", "Miles", "Bob", "Fred"]
numbers = [ 4, 17, 19]
def find(item):
    ....
def result():
    ....

编写两个函数体的代码:

find()

获取一个参数,它在全局名称列表中查找,如果在那里找不到,那么它会在数字列表中查找。

总是增加searchCount,无论是否找到该项目

如果找到该项目,它会增加foundCount并根据需要打印“Found in Names”或“Found in Numbers”。

如果找不到项目,

会显示“未找到”

结果() 这没有参数。它打印搜索计数的摘要: 例如“总搜索次数:6,找到的项目:4,未找到:2”**

样品运行

**======= Loading Program =======
>>> find("mary")
 Not found
>>> find("Mary")
 Found in names
>>> find(0)
 Not found
>>> find(19)
 Found in numbers
>>> results()
  ***** Search Results *****
 Total searches:  4
 Total matches :  2
 Total not found: 2**

到目前为止,我所做的是:

**

foundCount  = 0
searchCount = 0
names = [ "Mary", "Liz", "Miles", "Bob", "Fred"]
numbers = [ 4, 17, 19]
def find(item):
    global foundcount
    if item == "Mary":
      printNow("Found in names")
    elif item == "Liz":
      printNow("Found in names")
    elif item == "Miles":
      printNow("Found in names")
    elif item == "Bob":
      printNow("Found in names")
    elif item == "Fred":
      printNow("Found in names")
    elif item == "4":
      printNow("Found in numbers")
    elif item == "17":
      printNow("Found in numbers")
    elif item == "19":
      printNow("Found in numbers")
    else: printNow("Not Found")

def result():

**

我需要def result()函数的帮助,所以我可以在三天内完成这项作业并学习数学考试。 在明天到期时需要帮助完成这项任务:(....

1 个答案:

答案 0 :(得分:1)

使用in运算符:

def find(item):
    global foundcount

    if item in names:
        foundCount += 1
        printNow("Found in names")
    elif item in numbers:
        foundCount += 1
        printNow("Found in numbers")
    else:
        printNow("Not Found")

至于result,您可以使用print功能:

print('Found Items:', foundCount)