【问题标题】:Using for loop within if statements in Python在 Python 中的 if 语句中使用 for 循环
【发布时间】:2017-03-19 18:29:39
【问题描述】:

对于python的循环语句我真的很难,请看下面:

我想让它检查用户的年龄,所以如果他们超过 18 岁,它会说“足够大,如果他们超过 16 岁,它会说“差不多”,如果他们比这更年轻,它会说“对不起,你太年轻了”

我得到以下代码:

age = int(raw_input("Enter your age:"))

if age >= 18:
    print "You are old enough!"
elif age >= 16:
    print "Almost there"
else:
    print "You're just too young"

我的问题是,如何编写包含 if 语句和 for 循环的代码,以打印出从 0 开始小于用户输入年龄的所有数字?

我说:

for age in range (0,num) 
    if num <= age
    print ....
else:
    print...

请帮忙。我是新手,还在学习:(

【问题讨论】:

  • 提示:在循环中切换 agenum。 (你也不需要另一个if..else

标签: python-2.7


【解决方案1】:

因此,您可以构造一个包含小于用户年龄的数字列表的变量。您可以使用 python 的 range 函数构造它;像range(age) 这样的东西会很好地做到这一点。

然后您需要使用for loop 循环所有这些数字并将它们打印到命令行。像for x in range(age) 这样的东西会是一个不错的起点。

然后,在循环中,您只需使用 str() 函数将 x 从整数转换为字符串,并将其打印到命令行。

所以作为伪代码:

if the age is greater than 18:
    print that they're old enough
else if the age is greater than 16:
    print that they're nearly old enough 
otherwise:
    print that they're not old enough.

for each number between 0 and age:
    print the number

当你有一些代码时回来,我们可以帮助你解决你遇到的任何问题。

【讨论】:

  • 您也可以在一行中打印该数字:print ' '.join([x for x in xrange(age)])
  • 我只是想向他们展示最简单易懂的方式,因为他们是初学者,但这当然是一个很好的了解。
猜你喜欢
  • 2023-01-13
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多