将for循环应用于条件语句

时间:2017-07-19 10:00:27

标签: python

以下是一个示例(来自http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html的代码段):

if weight > 50:
    print("There is a $25 charge for luggage that heavy.")
print("Thank you for your business.")

我想将整个代码放入" for"环。使用for(..){上面的代码来到这里}会非常容易。 我仍然无法通过这种方式找到方法,我需要编写for循环并缩进下面的整个块。我想我在这里错过了一些东西......

2 个答案:

答案 0 :(得分:4)

您可以根据需要在Python中使用尽可能多的括号,尤其是对于if语句:

if(( (True) )
   and (1==1) ):
    print("It's really true")

编辑:原始问题已经过大量修改,因此此答案可能不再适用于修改后的问题。

答案 1 :(得分:1)

你无法逃脱python的缩进。你能做的就是把你的代码块放在一个函数中,你只需要用函数调用缩进单行。
而不是

if condition:
   # code
   # code 
   # code...

有一个功能

def my_code_block():
   if condition:
       # code
       # code 
       # code...

然后,在调用者函数中

for i in xrange(10):
    my_code_block( ... )

你只缩进一行......

相关问题