2017-07-17 59 views
-1

我正在尋找for循環類似於其他語言PERL/TCL/C++在Python中。TCL喜歡for循環在python

下面像TCL是在Python for循環

for { set i 0 } { $i < $n } { incr i} { 

#I like to increment i value manually too like 
if certain condition is true then increment 
set i = [expr i+1] # in some cases 
print i 

我有同樣的方式了。在蟒蛇下面我所知道的是for循環語法

for i in var1 
#How to increment var1 index manually in some scenarios 
+1

在你的例子中用'range(0,n,1)' –

+0

替換'var1' @DaleWilson:每次增加1。但如果我們想根據條件增加一些場景,例如增加2 – Nitesh

+1

[我如何在Python中使用C風格的循環?](https://stackoverflow.com/questions/9450446/how-do -i-use-ac-style-for-loop-in-python) – Aurora0001

回答

2

用途:

for i in range(0, n): 
# Do something 

此外,您還可以使用:

i = 0 
while i<n: 
# Do something 
i+=1 
+0

如果我們想在循環內部手動跳過一些迭代,我們可以這樣做 – Nitesh

+0

是的,但是你會有下一個數字。 – VIX

+0

把if語句放在需要的地方。 – VIX

1

Python的range功能,被稱爲像range(b, e, i)將產生整數開始與b和結束於e,每次增加i

+0

如果在某些條件爲真時如何遞增 – Nitesh

+0

爲每次迭代添加一個if if塊。如果條件未評估爲True,則可以使用「continue」移至下一次迭代。 – Lgiro

+0

這聽起來像是,如果你還想要手動增加'i',則使用'while'循環 – Lgiro

1

Python沒有那種風格的for循環,所以使用while循環。

i = 0 
while i < n: 
    # ... 
    if some_condition: # Extra increment 
     i += 1 
    i += 1 # normal increment 
+0

是的,當我知道循環時。我認爲我缺少的for循環中有一些東西。感謝您的澄清 – Nitesh