Making Decisions with If Statements

We are going to learn how to write code that has decisions in it, so that the output isn't always the same. The code that gets executed changes depending on what the human enters.

This is your first code where you have to indent some parts! I usually just press Tab once, but other people prefer to just add a few spaces. Use either one, but be consistent about it.

Python programs can sometimes break if you mix up spaces and tabs for indentation.

namelength.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from __future__ import print_function
input = raw_input

print("Please enter your FULL name (first, middle, last, etc).")
name = input("What is your full name? ")

print('"{}" is {} letters long.'.format(name, len(name)))

if len(name) < 18:
    print("Not that long, actually.")
if len(name) > 26:
    print("Pretty long name you got there!")
if len(name) > 42:
    print("Holy cow, {} letters?!?".format(len(name)))
    print("That's the longest name I've ever seen!")

What You Should See

Please enter your FULL name (first, middle, last, etc).
What is your full name? John Felix Anthony Cena Jr.
"John Felix Anthony Cena Jr." is 27 letters long.
Pretty long name you got there!

This is an example of an "if statement". When the statement after the if is true, the indented code underneath gets executed. When the if statement is false, its code gets skipped.

When the indentation goes back to normal, the conditional part is over.

In this assignment, if they put in a really long name, then two of the if statements will be true. The one on line 11 will be true, so the print() statement on line 12 will execute. Then the condition on line 13 will be true, so both lines 14 and 15 will run.

There is also another new thing in this assignment: the len() function. It can tell you the length of a lot of different things. If you pass it a string value, it will tell you how many characters long it is.

Study Drills

  1. Add another if statement.



©2017 Graham Mitchell