首页 > 解决方案 > 在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 女

标签: python-3.xwhile-loop

解决方案


您可以使用if,else语句来做到这一点。

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

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 = ' '.


推荐阅读