If Python Elif Snakes Else Ladders

If Python Elif Snakes Else Ladders

Did you ever play Snakes & Ladders? We had the tame version in America, Chutes and Ladders. It was supposed to teach you morals. But let’s use it to illustrate our next concept: Python elif statements. The elif statement is a portmanteau of else and if. A portmanteau is any word that is a mash-up of two other words. We use elif for if statements that have multiple choices. It’s like saying, “If not this, or this, then that.”

Python elif Statements

In case you’ve never played Snakes (or Chutes) and Ladders, here’s a quick run-down: You play with a board mapping out twisty snakes (or chutes) and ladders, figurines for the players, and a die or a spinner. You roll the die(or spin the spinner) and move that many squares on the board. If the square your game piece lands on is the bottom of a ladder you get to climb up and skip all of the squares in between the base of the ladder and its top rung. But, if the space on which your game piece lands is the head of a snake, you slide down its body, thus losing ground gained towards reaching the end goal.

Let’s write a simple version of this game in Python. But let’s call it ‘Snakes and Pythons’, because learning Python is like climbing a ladder. Open IDLE and create a new file, snakes_pythons.py. First, we import the random module. We’re going to use it’s function, randint, to generate a roll of the die, or a random integer.

Next we declare the roll of our die. Imagine our die has only three sides. Impossible? Not in programming. This is where we use the randint function to randomly generate 0, 1 or 2. Remember that computers start counting at 0.

Now let’s lay out our board. We’ll keep it simple and only use three squares, neutral, ladder, and snake, and nest them inside our if statement.

We don’t need to test our last condition because anything that is not 0 or 1 will be caught by the else statement. Multiple conditions allow you to sort complex choices. Fun, right? If you want to learn more, join us in the next lesson. Elif, don’t. Else, whatever.

If Python Elif Snakes Else Ladders was posted by on . Jared likes to make things. He really wants you to watch The Hello World Program so you can learn the skills you need to build an awesome future. His contributions to the show include puppetry, 3D animation, doodling and speaking in a bad British accent. And yes, that is a fox sitting on his face.

Discuss this article in the Comments below, or and it with your friends. Learn more about Python by subscribing to The Hello World Newsletter .

Join the Discussion

Subscribe to our Mailing List

Stay up to date on the latest videos and tutorials with our monthly newsletter

The email entered is invalid