python-3.x - 在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 女
解决方案
您可以使用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 = ' '
.
推荐阅读
- javascript - Discord bot 意外结束输入
- python - 模型子类化忽略附加到 Python 列表的 Keras 层的权重
- python - 如何在 Jupyter 中将图形图像导出为 pdf?
- matlab - (0:2):4 和 0:(2:4) 有什么区别?
- c# - 禁用面板中的按钮会触发面板中单选按钮上的 CheckedChanged 事件
- css - CSS - 如何在内容垂直扩展时扩展英雄背景 div/图像的大小
- c# - 使用 MySqlConnector 的 MySqlBulkCopy 将数据表上传到 MySql。抛出异常
- java - 在 IntelliJ IDEA 中创建数据库
- javascript - 使用请求模块发布表单数据 - Nodejs & Express
- r - 在 for 循环中向 R 数据框添加新行而不使用 NROW()