else
/ elif
used after return
PYL-R1705469 try:
470 student = Student.objects.get(uid=request.POST['id'])
471 transcript = Transcript.objects.filter(student=student)
472 if len(transcript) > 1:473 json_transcript = TranscriptSerilazer(transcript, many=True)
474 return JsonResponse(json_transcript.data, safe=False)
475
213class StudentSignupView(View):
214 def post(self, request):
215 form = StudentFormValidate(request.POST)
216 if form.is_valid():217 print(form.cleaned_data)
218 form.save()
219 return JsonResponse({'status': "Success", 'message': 'Student Sign Up Successful.'})
361 return JsonResponse({'status': 'success', 'message': 'No User Logged in', 'condtion': True})
362
363 def get(self, request):
364 if request.user.is_authenticated:365 logout(request)
366 return JsonResponse({'status': 'success', 'message': 'User Logged Out', 'condtion': True})
367 else:
354class StudentLogoutView(View):
355
356 def post(self, request):
357 if request.user.is_authenticated:358 logout(request)
359 return JsonResponse({'status': 'success', 'message': 'User Logged Out', 'condtion': True})
360 else:
240 return JsonResponse({'message': 'User is Not a Student',
241 'condtion': False, 'status': 'failure'}, status=401)
242
243 if user is not None:244 login(request, user)
245 dict_user = model_to_dict(user)
246 dict_user.pop('groups', None)
The use of else
or elif
becomes redundant and can be dropped if the last statement under the leading if
/ elif
block is a return
statement.
In the case of an elif
after return
, it can be written as a separate if
block.
For else
blocks after return
, the statements can be shifted out of else
. Please refer to the examples below for reference.
Refactoring the code this way can improve code-readability and make it easier to maintain.
def classify_number(x):
if x % 2 == 0:
return 'Even'
else:
return 'Odd'
def what_is_this_number(x):
if x % 2 == 0 and x >= 0:
return 'Even'
elif x % 2 == 0 and x < 0:
return 'Even and Negative'
elif x % 2 != 0 and x < 0:
return 'Odd and Negative.'
else:
return 'Odd'
def classify_number(x):
if x % 2 == 0:
return 'Even'
return 'Odd'
def what_is_this_number(x):
if x % 2 == 0 and x >= 0:
return 'Even'
if x % 2 == 0 and x < 0:
return 'Even and Negative'
if x % 2 != 0 and x < 0:
return 'Odd and Negative'
return 'Odd'