lundi 4 février 2019

Python if conditions are being skipped yet they work in C#

I would like to know why the python code below is not setting the right variable in the array according to the condition I have given it. Consider the code below whose purpose is simply to detect if it is "day" or "night" depending on the value of i for all hours in a year:

len_hrs=8760
daynight=[0]*len_hrs
i=0
j=0
cas="day"
while (j < len_hrs):
    if(i>=7 & i<19):
        daynight[j]=1
        cas="day"
        print (i , " ", cas)
    elif(i>=19 & i<=23):
        daynight[j]=0
        cas="night"
        print (i , " ", cas)
    elif(i>=0 & i< 7):
        daynight[j]=0  
        cas="night"
        print (i , " ", cas)
    i=i+1
    j=j+1
    if(i>23):
        i=0

The value of i is incremented from 0 until it's greater than 23 and the cycle repeats. But the print statement always assigns "day" to the value of cas and all elements of daylight are equal to 1.

I am scratching my head over this because in C#, the same code works perfectly.

using System;

public class Program
{
    public static void Main()
    {
        int len_hrs=8760;
        int [] daynight= new int[len_hrs]; 
        int i=0,j=0;
        string cas="day";
        while (j < len_hrs)
        {
            if(i>=7 & i<19)
            {
                daynight[j]=1;
                cas="day";
                Console.WriteLine(i + " "+ cas);
            }
            else if(i>=19 & i<=23)
            {
                daynight[j]=0;
                cas="night";
                Console.WriteLine(i + " "+ cas);
            }
            else if(i>=0 & i< 7)
            {
                daynight[j]=0; 
                cas="night";
                Console.WriteLine(i + " "+ cas);
            }
            i=i+1;
            j=j+1;
            if(i>23)
                i=0;
        }
    }
}

I am new to Python after years .NET development so I may have messed up something. I'd like to know what that something is!

Aucun commentaire:

Enregistrer un commentaire