Home > Software design >  the else block in the following code isn't working and only the if statement is being executed
the else block in the following code isn't working and only the if statement is being executed

Time:06-17

def volume(df):

for i in range(len(df['depth'])):
  if df['depth'][i] > 60 :
     df['volume']=df['x']*df['y']*df['z']
  else:
     df['volume'] = 8 
return df

I am working to calculate volume of a diamond dataset where dimensions x,y,z and depth are given and I have to calculate volume = xyz when depth >60 else volume is to be set to 8 but the code I have written is not assigning volume =8 when depth <60 and simply calculates volume = xyz , perhaps the code isn't taking the else condtion initially is what i thought so I used a counter a which incremented by one when else block was executed and I printed its value successfully (my debug attempt) . Can you guys help me out in this ? Thanks in advance

CodePudding user response:

Instead of looping, try this code:

import numpy as np
df['volume']=np.where(df['depth']>60, df['x']*df['y']*df['z'], 8)
  • Related