在 while 循环中附加变量值的最佳方法



我有以下python 3.8代码:

def main():
father_year = int(1988)
c_year = int(2020)
x = 3
f_female = str("female")
m_male = str("male")
while father_year < c_year:
print(father_year + x)
father_year += x

它输出: 1991 1994 1997 2000 2003 2006 2009 2012 2015 2018 2021

年每次添加数字 3 时添加女性和男性的最佳方法是什么?

想要的输出: 1991 女 1994 男 1997 女 2000 男 2003 女 2006 男 2009 女 2012 男 2015 女 2018 男 2021 女

您可以使用ifelse语句来执行此操作。

如果要在同一行中打印所有内容,则:

def main():
father_year = int(1988)
c_year = int(2020)
x = 3
f_female = str("female")
m_male = str("male")
while father_year < c_year:
if father_year % 2 == 0:
print(father_year + x, 'Female', end = ' ')
father_year += x
else:
print(father_year + x, 'Male', end = ' ')
father_year += x
main()

输出:

1991 Female 1994 Male 1997 Female 2000 Male 2003 Female 2006 Male 2009 Female 2012 Male 2015 Female 2018 Male 2021 Female

如果您希望它们在不同的行中,请删除end = ' '.

最新更新