简体   繁体   English

关于python3中的循环

[英]Regarding for loop in python3

I gave the input 0 1 5 , the answer should be 5 but it is not showing me ... , 我给了输入0 1 5 ,答案应该是5但没有显示给我...
help me out with the syntax 用语法帮助我

    a, b, c = [int(x) for x in input().split()]
    ans = None
    for i in range(3,c):
        ans=a + (b*b)
        a=b
        b=ans
        print ans

Your loop will run twice for i = 3, and i = 4. 对于i = 3和i = 4,您的循环将运行两次。

The first run: 第一次运行:

ans = 0 + 1 * 1 #1
a = 1
b = 1
print(1)

The second run: 第二次运行:

ans = 1 + 1 * 1 # 2
a = 1
b = 2
print(2)

Now ans is 2. It's not clear why you think it should be 5. 现在ans是2。目前尚不清楚为什么您认为应该是5。

I think this is what you are trying to do: 我认为这是您想要做的:

a, b, c = [int(x) for x in input().split()]
ans = None
for i in range(2,c):
    ans=a + (b*b)
    a=b
    b=ans
print (ans)

Note that for i in range(2,c) i will be 2 then 3 and then 4. It will not be 5 (=c) it stops at c-1. 请注意, for i in range(2,c) i for i in range(2,c)我将是2,然后是3,然后是4。它将不是5(= c),它将在c-1处停止。

Edit: if you just want the loop to run c times you can say for i in range(c) . 编辑:如果只希望循环运行c次,则可以for i in range(c)表示。 This way it will run for i=0,1,2,...,c-1. 这样,它将针对i = 0,1,2,...,c-1运行。

As per Python 3, print command syntax is print('your text') print(variable) print('your text ans: ',ans) Without semi-circular brackets print won't work. 根据Python 3,打印命令语法为print('your text') print(variable) print('your text ans: ',ans)如果没有半圆括号,则print无效。 Refer: https://docs.python.org/3/whatsnew/3.0.html 请参阅: https//docs.python.org/3/whatsnew/3.0.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM