Home > Enterprise >  C port out to Python
C port out to Python

Time:09-22

Can someone to port out this from C to Python? It's a short program and I tried to do it alone but I can't.

#include <stdio.h>

int main()
{
    float a= 0;
  
    for(int i=0; i<31; i  )
    {
        if(a<4.5)
        {
            a=a 0.5;
         }
     
         else{
         a=0.5;
        }
        printf("%d\t%f\n", i,a);
        
    }
    return 0;
}

I tried something like this but it's not right because the answer is only 31 1.0

a = 0.5

for i in range(31):
    i = i   1

if a < 4.5:
    a = a   0.5
else:
    a = 0.5

print(i, a)

CodePudding user response:

Your if construct is not inside the for. In Python, whitespace and indentation matters.

Also, your initial value for a is different.

CodePudding user response:

There are several issues in your python code:

  1. a is initialized to 0.5 instead of 0.
  2. The check whether a < 4.5 is done out of the loop (in Python indentation maters).
  3. The python for loop is already taking care of incrementing i, so you should not increment is manually with i = i 1.

Fixed Version:

a = 0
  
for i in range(31):
    if a < 4.5:
        a = a   0.5
    else:
        a = 0.5
    print(i,a)        
  • Related