如果if语句不在函数中,是否可以将else放入函数中?

时间:2018-09-20 17:02:58

标签: python

因此,我试图为作业创建测验,但我在每次提问后都编写if和else来查看其是否正确,因此我很累,所以我决定尝试制作一个函数。

问题是if语句不能进入函数内部,因为它需要检查用户答案。 我尝试做的事情看起来像

def result():
                    print("Correct")
              else:
                    print("Wrong")

我想在if语句之后插入该函数,但是每当我尝试运行它时,我都会收到语法错误,因为在该函数中else之前没有if语句。

有什么办法可以解决这个问题?

4 个答案:

答案 0 :(得分:2)

听起来像是一遍又一遍地写着这样的东西:

if ask_question():
  print("Correct")
else:
  print("Wrong")

可以确实将这种重复的逻辑移到一个函数中!那是编程的中心前提。但是功能(通常来说)是隔离的工作单元,因为它们是在一个地方定义的,然后在其他地方调用。因此,正如您所发现的,您不能在if语句的中途定义函数。

但是,您可以做的是将整个if语句移到您的函数中!考虑:

def print_result(result):
  if result:
    print("Correct")
  else:
    print("Wrong")

您可以将TrueFalse的值传递到其中以触发不同的路径,例如print_result(True)print_result(False)

也许您可以找出从这里出发的地方:)

答案 1 :(得分:1)

为什么不只是将两个变量传递给函数?

def result(entry, answer):
    if entry == answer:
        print('Correct')
    else:
        print('Wrong')

result(20, 10)
result('bird', 'bird')
result('cat', 'dog')
result(5, 5)

我还将设置一个字典,为您提供一些实际的实用工具:

def result(entry, answer):
    if entry == answer:
        print('Correct')
        scores['correct'] += 1
    else:
        print('Wrong')
        scores['wrong'] += 1
    scores['total'] += 1

scores = {'total': 0, 'correct': 0, 'wrong': 0}

result(20, 20)
result('bird', 'bird')
result('cat', 'dog')
percent = round((scores['correct']/scores['total'])*100, 2)
grade = print('Correct: {}'.format(scores['correct']) +
              '\nWrong: {}'.format(scores['wrong']) +
              '\nPercent: {}'.format(percent))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 helping.py 
Correct
Correct
Wrong
Correct: 2
Wrong: 1
Percent: 66.67

答案 2 :(得分:1)

您的意思是这样的吗?

def result(answer, right_answer):
    if answer == right_answer: print("Correct")
    else: print("Wrong")

>result("goose", "goose")
Correct

>result("cat", "goose")
Wrong

答案 3 :(得分:1)

您可以做的是将条件作为参数传递,如下所示

def result(cond):
    if cond:
        print('Correct')
    else:
        print('Wrong')

这样做是什么,它将使您的函数保持独立,即,您无需关心传递的条件,条件求值的条件,也许以后就可以重用该函数。

示例用法包括,仅使用条件调用函数;像-

result(answer == 'answer placehoder')
相关问题