DEV Community

M-Shkreli21
M-Shkreli21

Posted on

Python If/else statements

Today I decided to tackle one of my first Python labs on conditional statements. At first glance the simpleness of Pythons syntax writing really stands out compared to JavaScript.

In JavaScript a developer has to know operators like "||"(or) as well as "&&"(and), in Python its as simple as using the words and/or. While it doesn't seem like a huge difference maker, when I first started learning JavaScript, I saw that I would often times overlook the operators or forget which were which.

Image description

Even though the examples above are straight forward and not complex, i'm still proud of my ability to translate what I know from JS so easily into writing Python functions. With Python, we don't need parenthesis or curly brackets left and right. If you are like me thats a small difference that can go a long way when writing a lot of code and debugging.

In Python, prior to version 3.10, there was no equivalent to a switch/case statement, we are able to flawlessly integrate a regular if/else statement, as shown with the calculator function example.

One aspect of Python functions that is new to me and I am excited to learn is the use of Dictionary Mapping. With Dictionary Mapping we are able to take a long list of conditions and instead of writing if/else statements until our hands hurt we are able to group all the conditions and values into a dictionary.

`dog = "cuddly

dict_map = {"hungry": "Refilling Bowl",
"Playful": "Play a game",
"Cuddly": "Snuggle"}

owner = dict_map.get(dog, "Reading Newspaper")
`

With this above method, we are able to apply the state of the dog to the dictionary keys and apply the state of the owner to the values of the dictionary.

So far for my first week with Python, I can see why this is considered one of the most popular programming languages, I am excited as I continue down the path of mastering Python!

Top comments (0)