Learning Python — starting with conditionals

Charles Butler Jr
3 min readJul 23, 2021

Python first appeared in 1991 and is a general-purpose programing language. It is object oriented & functionally structured, with a basis on readable code and big emphasis on indentation. It is consistently viewed as one of the most popular programming languages in modern computer science.

Coming from a Ruby & RoR background transitioning over to python was a bit easier than expected. Utilizing HackerRanks application platform for practice it was quick to realize the similarities python shared with ruby especially when it comes to naming conventions / syntax of functions. Today we’re going to look at the 3rd problem in the Hacker Rank python introduction course: Python If-Else

Given an integer we’re to create a function that determines if it is weird or not. The preferred output will either be a string saying ‘Weird’ or ‘Not Weird’.

For my first attempt I utilized the equality operator like in ruby. This operator == returns true if both objects can be considered the same. Unfortunately this isn’t the case in python and my code only passed 5 / 8 test cases.

Looking at the specifications each conditional needs to include the even statement. Here I moved to another option of adding the ‘and’ operator to include the even notation. Unfortunately && doesn’t work like it does in ruby and upon a quick ‘google-search’ into the python docs ! and && aren’t utilized in python conditionals. Instead I had to work use AND as well as NOT.

Changing these increased my test passing to all but one. Looking deeper into refactoring my code, i noticed that I not only was using && incorrectly, I once again used the bang operator as well as equality for the range.
The new if-statement should be ‘n in range(x,y)’

if n in range(2, 6):
print(‘Not Weird’)
elif n in range(6, 21):
print(‘Weird’)
elif n > 20:
print(‘Not Weird’)

With these in place we can condense the modulus conditional (%) into one line and using that ‘if’ statement add another conditional inside of it.

Success! Running this function allows all tests to pass and with a smaller footprint. Thanks for joining my first python algorithm in hacker Rank!

--

--

Charles Butler Jr
Charles Butler Jr

Written by Charles Butler Jr

Pre-Med student turned software engineer. Hoping to make code make sense & make sense out of all my code.