Th e keywords if , elif and else are used in conditional statements . Conditional statements are a type of control structure : a block of code that can make decisions by analyzing the values of variables. A conditional statement is code that is able to execute additional code circumstantially. Here is an example in pseudocode (fake code used to illustrate an example) to help clarify how this works:
If (expression) Then (code_area1) Else
(code_area2)
This pseudocode explains that you can define two conditional statements that work together. If the expression defined in the first conditional statement is True , all of the code defined in code_area1 gets executed. If the expression defined in the first conditional statement is False , all of the code defined in code_area2 gets executed. The first part of the example is called an if statement , and the latter is called an else statement . Together, they form an if else
statement: a way for programmers to say “if this happens do this, otherwise do that”. Here is an example of an if else statement in Python:
# https://goo.gl/uYp6ha
country = "America"
if country == "America" : print ( "Hello, America!" ) else :
print ( "Hello, Canada!" ) >> Hello, America!
Lines 2 and 3 form an if statement. An if statement is made up of a line of code starting with the if keyword followed by an expression, a colon, an indentation and one or more lines of code to be executed if the expression in the first line evaluates to True . Lines 3 and 4 form an else statement. An else statement starts with the else keyword, followed by a colon, an
indentation and one or more lines of code to execute if the expression in the if statement evaluates to False .
Together they form an if else statement. This example prints Hello, America! because the expression in the if statement evaluates to True . If we change the variable country to
Canada , the expression in the if statement will evaluate to False , the else statement’s code will execute and our program will print Hello Canada! instead.
# https://goo.gl/bd4LVW
country = "Canada"
if country == "America" : print ( "Hello, America!" ) else :
print ( "Hello, Canada!" ) >> Hello Canada!
An if statement can be used on its own:
# https://goo.gl/jOlzVl country = "America"
if country == "America" : print ( "Hello, America!" ) >> Hello, America!
You can have multiple if statements in a row:
# https://goo.gl/WBoKWA x = 2
if x == 2 :
print ( "The number is 2." ) if x % 2 == 0 :
print ( "The number is even." ) if x % 2 != 0:
print ( "The number is not odd." ) >> The number is 2.
>> The number is even.
Each if statement will execute its code only if its expression evaluates to True . In this case, the first two expressions evaluate to True , so their code is executed, but the third expression evaluates to False , so its code is not executed.
If you really want to get crazy, you can even put an if statement inside of another if statement. This is called nesting:
# https://goo.gl/S6Z9rp x = 10
y = 11 if x == 10 : if y == 11 : print (x + y) >> 21
In this case x + y will only print if the expressions in both if statements evaluate to True . An else statement cannot be used on its own; it can only be used at the end of an if else statement.
We use the elif keyword to create elif statements . elif stands for else if, and elif statements can be indefinitely added to an if else statement to allow it to make additional decisions.
If an if else statement has elif statements in it, the if statement expression gets evaluated first. If the expression in that statement evaluates to True , its code is executed and no other code is executed. However, if it evaluates to False , each consecutive elif statement is
evaluated. As soon as an expression in an elif statement evaluates to True , its code is executed and no more code executes. If none of the elif statements evaluate to True , the code in the else statement is executed. Here is an example of an if else statement with elif statements in it:
# https://goo.gl/L0OorN country = "Thailand"
if country == "Japan" : print ( "Hello, Japan!" ) elif country == "Thailand" : print ( "Hello, Thailand!" ) elif country == "India" : print ( "Hello, India!" ) elif country == "China" : print ( "Hello, China!" ) else :
print ( "Hello, world!" )
>> Hello, Thailand!
Here is an example where none of the expressions in the elif statements evaluate to True , and the code in the else statement is executed:
# https://goo.gl/Qwb5OD
country = "Mars"
if country == "America" : print ( "Hello, America!" ) elif country == "Canada" : print ( "Hello, Canada!" ) elif country == "Thailand" : print ( "Hello, Thailand!" ) elif country == "Mexico" : print ( "Hello, Mexico!" ) else :
print ( "Hello, world!" )
>> Hello, World!
Finally, you can have multiple if statements and elif statements in a row:
# https://goo.gl/tgcmXN x = 100
if x == 10 : print ( "10!" ) elif x == 20 : print ( "20!" ) else :
print ( "I don’t know what x is!" ) if x == 100 :
print ( "x is 100!" ) if x % 2 == 0:
print ( "x is even!" ) else :
print ( "x is odd!" )
>> I don’t know what x is!
>> x is 100!
>> x is even!
Statements
A statement is a technical term that describes various parts of the Python language.
You can think of a Python statement as a command or a calculation. This will become more clear as we take a look at examples of different kinds of Python statements . In this section we will also take a detailed look at the syntax of statements. Don't worry if some of this seems confusing at first. Spend as much time as necessary rereading this section and go back to the earlier examples and compare them with what you are learning here. It might take a while to understand the syntax of statements, but it will start to make more sense the more time you spend practicing Python and will help you understand several programming concepts.
Python has two kinds of statements: simple statements and compound statements . Simple statements can be expressed in one line of code, whereas compound statements
generally span multiple lines (but can be written in one line in some circumstances). Here are some examples of simple statements:
print ( "Hello, World!" )
>> ‘Hello, World!”
2 + 2
>> 4
Compound statement s generally span more than one line of code. You’ve already seen multiple examples of compound statements: if statements, if else statements and the first
program we wrote in this chapter that printed “Hello, World!” one hundred times are all examples of compound statements.
Compound statements are made up of one or more clause . A clause consists of two or more lines of code: a header followed by a suite (s). A header is a line of code in a clause that contains a keyword followed by a colon and a sequence of one or more lines of indented code. After the indent there are one or more suites. A suite is just a line of code in a clause.
The suites are controlled by the header. Our program that prints “Hello, World!” a hundred times is made up of a single compound statement:
# https://goo.gl/rKQedq for i in range ( 100 ):
print ( "Hello, World!" )
>> Hello World
>> Hello World
>> Hello World
…
The first line of the program is the header. It’s made up of a keyword— for —followed by a colon and an indent ed line of code. After the indentation is a suite — print(“Hello, World!”) . In this case, the header uses the suite to print Hello, World! a hundred times. This is called a loop, which you learn more about in Chapter 7. This code only has one clause.
A compound statement can also be made up of multiple clauses. You already saw this with if else statements. Anytime an if statement is followed by an else statement, the result is a compound statement with multiple clauses. When a compound statement has multiple clauses, the header clauses work together. In the case of an if else compound statement, when the if statement evaluates to True , the if statement’s suites execute and the else statement’s suites do not execute. When the if statement evaluates to False , the if statement’s suites do not execute and the else statement’s suites execute instead. The last example from the previous section has three compound statements:
# https://goo.gl/tgcmXN x = 100
if x == 10 : print ( "10!" ) elif x == 20 :
print ( "20!" ) else :
print ( "I don’t know what x is!" ) if x == 100 :
print ( "x is 100!" ) if x % 2 == 0:
print ( "x is even!" ) else :
print ( "x is odd!" )
>> I don’t know what x is!
>> x is 100!
>> x is even!
The first compound statement has three clauses, the second compound statement has one clause and the last compound statement has two clauses.
One last thing about statements, statements can have spaces between them. Space
between statements does not affect the code. Sometimes spaces are used between statements to make code more readable:
print ( "Michael" ) print ( "Jordan" )
>> Michael
>> Jordan
Vocabulary
comment : A line (or part of a line) of code written in English (or another language) preceded by a special symbol that lets the programming language you are using know it should ignore that line (or part of a line) of code.
keyword : A word with a special meaning in Python. You can see all of Python’s keywords at http://zetcode.com/lang/python/keywords
constant : A value that never changes.
variable : A name assigned to a value using the assignment operator assignment operator : The = sign.
increment : Increasing the value of a variable.
decrement : Decreasing the value of a variable.
data type : A category of data.
object : A data value in Python with three properties: an identity, a data type and a value.
string : An object with a data type str. Its value is a sequence of one or more characters surrounded by quotes.
integer : An object with a data type int. Its value is a whole number.
float : An object with a data type float. Its value is a fractional number.
boolean : An object with a data type bool. Its value is either True or False . nonetype : An object with a data type NoneType. Its value is always None .
syntax : T he set of rules, principles, and processes that govern the structure of sentences in a given language, specifically word order . 70
syntax error : A fatal programming error caused by violating a programming language’s syntax.
exception : A nonfatal programming error.
operator : Symbols used with operands in an expression.
arithmetic operator : A category of operators used in arithmetic expressions.
operand : A value on either side of an operator.
expression : Code with an operator surrounded by two operands.
order of operations : A set of rules used in mathematical calculations to evaluate an expression.
comparison operator : A category of operators used in expression that evaluate to either True or False .
logical operator : A category of operators that evaluate two expressions and return either True or False
control structure : A block of code that makes decisions by analyzing the values of variables
conditional statement : Code that is able to execute additional code circumstantially.
if else statement : A way for programmers to say “if this happens do this, otherwise do that.”
if statement : The first part of an if else statement.
else statement : The second part of an if else statement.
elif statement : S tatements that can be indefinitely added to an if else statement to allow it to make additional decisions.
statement : A command or a calculation.
simple statement : A statement that can be expressed in one line of code
compound statement : A statements that generally spans multiple lines (but can be written in one line in some circumstances).
clause : The building blocks of compound statements. A clause is made up of two or more lines of code: a header followed by a suite (s) .
header : A header is a line of code in a clause containing a keyword followed by a colon and a sequence of one or more lines of indented code.
suite : A line of code in a clause controlled by a header.
Challeng e
Write a program with a variable called age assigned to an integer that prints different strings depending on what integer age is.
Chapter 4. Functions
“Functions should do one thing. They should do it well. They should do it only.”
— Robert C. Martin
A function is a compound statement that can take input, execute instructions, and optionally return an output. Calling a function means giving the function the input it needs toso it can execute its instructions and optionally return an output. Functions in Python are similar to functions in math. If you don’t remember functions from algebra, here is an example:
# the following is algebra, not Python code f(x) = x * 2
The left half of the equation defines a function f —that takes one parameter— x . A parameter is data passedyou pass into a function when its called. A function can have one parameter, multiple parameters or no parameters. A function’s parameters are its input.
The right half of the equation is the definition of the function (the instructions it
executes when called). The right hand side of the equation usesis able to use the parameter that was passed in ( x ) to make a calculation and return the result (the output). In this case, our function takes a parameter ( x); , multiplies it by 2; and returns the result.
In both Python and algebra, you call a function with the following syntax:
[function_name]([parameters_seperated_by_commas] ) . You call a function by putting parentheses after the function name. TYou put the parameters go inside the parenthesis with each parameter separated by a comma. If we call the function we just defined above (?) and pass in the parameter 4 , we get the following result:
# the following is algebra, not Python code f(4)
>> 8
If we pass in 10 as a parameter we get 20:
f(10) >> 20
In our first example, we called our function with 4 as a parameter ( x ). Our function executed its code, x * 2 , and returned the result — 8 . In our second example, we called our function with 10 as a parameter ( x ). Our function executed its code, x * 2 , and returned the result — 20 .