我可以在函数中写if语句吗



我是一个编码初学者,我想创建一个看起来像的函数

a = [1, 2, 3, 4, 5, 6]
n = int(input("What is your age = "))
def prize(a):
for n in range(20, 61):
if 20 < n <= 30:
print('If you are between 20 and 30 years old, you will receive only', a[1], 'prize')

到目前为止,即使我输入了20到30之间的数字,我的代码也不会打印任何内容。我知道我必须使用return语句才能真正运行,但我想知道有没有一种方法可以在函数内部编写多个if语句?他们真的能跑吗?

您忘记调用函数了。

是的,您可以根据需要编写任意多的if语句:

a = [1, 2, 3, 4, 5, 6]
n = int(input("What is your age = "))
def prize(a):
for n in range(20, 61):
if n == 30:
print('You are 30 years old')
elif n == 40:
print('You are 40 years old')
elif 20 < n <= 30:
print('If you are between 20 and 30 years old, you will receive only', a[1], 'prize')
prize(a)

最新更新