Chapter 14
IN THIS CHAPTER
Understanding Python principles and style
Practicing Python code like assigning variables and using if
statements
Doing a simple Python project
I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python’s Flying Circus).
— GUIDO VAN ROSSUM, CREATOR OF PYTHON
Python is a server-side language created by Guido van Rossum, a developer who was bored during the winter of 1989 and looking for a project to do. At the time, Van Rossum had already helped create one language, called ABC, and the experience had given him many ideas that he thought would appeal to programmers. He executed upon these ideas when he created Python. Although ABC never achieved popularity with programmers, Python was a runaway success. Python is one of the world’s most popular programming languages, used by beginners just starting out and professionals building heavy-duty applications.
In this chapter, you learn Python basics, including the design philosophy behind Python, how to write Python code to perform basic tasks, and steps to create your first Python program.
Python is a general purpose programming language typically used for web development. This may sound similar to the description used for Ruby in the previous chapter, and really both languages are more similar than they are different. Python, like Ruby, allows for storing data after the user has navigated away from the page or closed the browser, unlike HTML, CSS, and JavaScript. Using Python commands you can create, update, store, and retrieve this data in a database. For example, imagine I wanted to create a local search and ratings site like Yelp.com. The reviews users write are stored in a central database. Any review author can exit the browser, turn off the computer, and come back to the website later to find their reviews. Additionally, when others search for venues, this same central database is queried, and the same review is displayed. Storing data in a database is a common task for Python developers, and existing Python libraries include pre-built code to easily create and query databases.
Many highly trafficked websites, such as YouTube, are created using Python. Other websites currently using Python include:
From websites to software to special effects, Python is an extremely versatile language, powerful enough to support a range of applications. In addition, to help spread Python code, Python programmers create libraries, which are stand-alone pre-written code that do certain tasks, and make them publicly available for others to use and improve. For example, a library called Scrapy performs web scaping, while another library called SciPy performs math functions used by scientists and mathematicians. The Python community maintains thousands of libraries like these, and most are free and open-source software.
Python has its own set of design principles that guide how the rest of the language is structured. To implement these principles, every language has its own conventions, like curly braces in JavaScript or opening and closing tags in HTML. Python is no different, and we will cover both design principles and conventions so you can understand what Python code looks like, understand Python’s style, and learn the special keywords and syntax that allow the computer to recognize what you are trying to do. Python, like Ruby and JavaScript, can be very particular about syntax, and misspelling a keyword or forgetting a necessary character will result in the program not running.
There are nineteen design principles that describe how the Python language is organized. Some of the most important principles include
Readability counts: This is possibly Python’s most important design principle. Python code looks almost like English, and even enforces certain formatting, such as indenting, to make the code easier to read. Highly readable code means that six months from now when you revisit your code to fix a bug or add a feature, you will be able to jump in without trying too hard to remember what you did. Readable code also means others can use your code or help debug your code with ease.
Reddit.com is a top-10-most-visited website in the US, and a top-50-most-visited website in the world. Its co-founder, Steve Huffman, initially coded the website in Lisp and switched to Python because Python is “extremely readable, and extremely writeable.”
Python generally uses less punctuation than other programming languages you may have previously tried. Some sample code is included here:
first_name=raw_input("What's your first name?")
first_name=first_name.upper()
if first_name=="NIK":
print "You may enter!"
else:
print "Nothing to see here."
If you ran this code it would do the following:
raw_input(What’s your first name?)
) and save it to the first_name
variable.print
“You may enter!” Otherwise it will print
“Nothing to see here.”Each of these statement types is covered in more detail later in this chapter. For now, as you look at the code, notice some of its styling characteristics:
Whitespace matters: Statements indented to the same level are grouped together. In the example above, notice how the if
and else
align, and the print
statements underneath each are indented the same amount. You can decide the amount of indentation, and whether to use tabs or spaces as long as you are consistent. Generally, four spaces from the left margin is considered the style norm.
See Python style suggestions on indentation, whitespaces, and commenting by visiting https://www.python.org/dev/peps/pep-0008
.
if
statement, is necessary when newlines would suffice. Early user testing with and without the colons showed that beginner programmers better understood the code with the colon.Python, as with other programming languages like Ruby, can do everything from simple text manipulation to designing complex graphics in games. The following basic tasks are explained within a Python context, but they’re foundational in understanding any programming language. Even experienced developers learning a new language, like Apple’s recently released Swift programming language, start by learning these foundational tasks. If you have already read the chapter on Ruby, the code to perform these tasks will look similar.
Start learning some basic Python below, or practice these skills right away by jumping ahead to the “Building a Simple Tip Calculator Using Python” section, later in this chapter.
Variables, like the ones in algebra, are keywords used to store data values for later use. Though the data stored in a variable may change, the variable name will always be the same. Think of a variable as a gym locker — what you store in the locker changes, but the locker number always stays the same.
Variables in Python are named using alphanumeric characters and the underscore (_) character, and they must start with a letter or an underscore. Table 14-1 lists some of the data types that Python can store.
TABLE 14-1 Data Stored by a Variable
Data Type |
Description |
Example |
Numbers |
Positive or negative numbers with or without decimals |
156–101.96 |
Strings |
Printable characters |
Holly NovakSeñor |
Boolean |
Value can either be true or false |
truefalse |
To initially set or change a variable’s value, write the variable name, a single equals sign, and the variable value, as shown in the following example:
myName = "Nik"
pizzaCost = 10
totalCost = pizzaCost * 2
Variable names are case sensitive, so when referring to a variable in your program remember that MyName
is a different variable from myname
. In general, give your variable a name that describes the data being stored.
After you create variables, you may want to do some math on the numerical values stored in those variables. Simple math like addition, subtraction, multiplication, and division is done using operators you already know. Exponentiation (such as, for example, 2 to the power of 3) is done differently in Python than in JavaScript, and uses two asterisks. Examples are shown here:
num1 = 1+1 #equals 2
num2 = 5-1 #equals 4
num3 = 3*4 #equals 12
num4 = 9/3 #equals 3
num5 = 2**3 #equals 8
Advanced math like absolute value, rounding to the nearest decimal, rounding up, or rounding down can be performed using math functions. Python has some functions which are built-in pre-written code that can be referenced to make performing certain tasks easier. The general syntax to use Python math functions is to list the function name, followed by the variable name or value as an argument, as follows:
method(value)
method(variable)
The math functions for absolute value and rounding follow the syntax above, but some math functions, like rounding up or rounding down are stored in a separate math module. To use these math functions you must:
import math
just once in your code before using the math functions in the math module.math.method(value)
or math.method(variable)
.See these math functions with examples in Table 14-2.
TABLE 14-2 Common Python Math Functions
Function Name |
Description |
Example |
Result |
|
Return the absolute value of a number (n) |
|
|
|
Round a number (n) to a number of decimal points (d) |
|
|
|
Round down to the nearest integer |
|
|
|
Round up to the nearest integer |
|
|
Along with numbers, variables in Python can also store strings. To assign a value to a string you can use single or double quotation marks, as follows:
firstname = "Travis"
lastname = 'Kalanick'
Including a single or double quote in your string can be problematic because the quotes inside your string will terminate the string definition prematurely. For example, if I want to store a string with the value ‘I’m on my way home’ Python will assume the '
after the first letter I is the end of the variable assignment, and the remaining characters will cause an error. The solution is to use special characters called escape sequences to indicate when you want to use characters like quotation marks, which normally signal the beginning or end of a string, or other non-printable characters like tabs. Table 14-3 shows some examples of escape sequences.
TABLE 14-3 Common Python Escape Sequences
Special Character |
Description |
Example |
Result |
|
Quotation marks |
|
|
|
Tab |
|
|
|
Newline |
|
|
With data stored in a variable, one common task is to compare the variable’s value to a fixed value or another variable’s value, and then make a decision based on the comparison. If you previously read the chapters on JavaScript or Ruby, the discussion and concepts here are very similar. The general syntax for an if-elif-else
statement is as follows:
if conditional1:
statement1 to execute if conditional1 is true
elif conditional2:
statement2 to execute if conditional2 is true
else:
statement3 to run if all previous conditional are false
The initial if statement
will evaluate to true
or false
. When conditional1
is true
, then statement1
is executed. This is the minimum necessary syntax needed for an if-statement
, and the elif
and else
are optional. When present, the elif
tests for an additional condition when conditional1
is false
. You can test for as many conditions as you like using elif
. Specifying every condition to test for can become tedious, so having a “catch-all” is useful. When present, the else
serves as the “catch-all,” and executes when all previous conditionals are false
.
The conditional in an if
statement compares values using comparison operators, and common comparison operators are described in Table 14-4.
TABLE 14-4 Common Python Comparison Operators
Type |
Operator |
Description |
Example |
Less than |
|
Evaluates whether one value is less than another value |
|
Greater than |
|
Evaluates whether one value is greater than another value |
|
Equality |
|
Evaluates whether two values are equal |
|
Less than or equal to |
|
Evaluates whether one value is less than or equal to another value |
|
Greater than or equal to |
|
Evaluates whether one value is greater than or equal to another value |
|
Inequality |
|
Evaluates whether two values are not equal |
|
Here is an example if
statement.
carSpeed=55
if carSpeed > 55:
print "You are over the speed limit!"
elif carSpeed == 55:
print "You are at the speed limit!"
else:
print "You are under the speed limit!"
As the diagram in Figure 14-1 shows, there are two conditions, each signaled by the diamond, which are evaluated in sequence. In this example, carSpeed
is equal to 55, so the first condition (carSpeed > 55
) is false
, and then the second conditional (carSpeed
==55) is true
and the statement executes printing “You are at the speed limit!” When a conditional is true
, the if
statement stops executing, and the else
is never reached.
Python can collect input from the user, and display output to the user. To collect user input use the raw_input("Prompt")
method, which stores the user input as a string. In the example below, the user enters his full name which is stored in a variable called full_name
.
full_name = raw_input("What's your full name?")
Imagine the user entered his name, “Jeff Bezos.” You can display the value of the variable using print
full_name
and you would see this:
Jeff Bezos
At this point, you may feel like printing variables and values in a Python interpreter console window is very different from dynamically creating web pages with variables created in Python. Integrating Python into a web page to respond to user requests and generate HTML pages is typically done with a Python web framework, like Django or Flask, which have pre-written code to make the process easier. These frameworks typically require some installation and set-up work, and generally separate the data being displayed from templates used to display the page to the user.
Whenever you collect input from users, you need to clean the input to remove errors and inconsistencies. Here are some common data cleaning tasks:
Python includes many built-in methods that make processing strings easy.
Standardizing user input to have proper case and remove extra white space characters is often necessary to easily sort the data later. For example, imagine you are designing a website for the New York Knicks so fans can meet players after the game. The page asks for fans to enter their name, so that team security can later check fan names against this list before entry. Reviewing past fan entries you see that fans enter the same name several ways like “Mark”, “mark”, “marK”, and other similar variants that cause issues when the list is sorted alphabetically. To make the input and these names consistent you could use the string functions described in Table 14-5.
TABLE 14-5 Select Python String Functions
Function Name |
Description |
Example |
Result |
|
Returns all uppercase characters |
|
|
|
Returns all lowercase characters |
|
|
|
Capitalizes first letter, lowercases remaining letters |
|
|
|
Removes leading and trailing whitespaces |
|
|
To insert variable values into strings shown to the user, you can use the string format operator %. Inserted into the string definition, %d is used to specify integers, %s is used to specify strings, and the variables to format (mapping key) are specified in parenthesis after the string is defined. See the example code and result below:
Code:
yearofbirth = 1990
pplinroom = 20
name = "Mary"
print "Your year of birth is %d. Is this correct?" % (yearofbirth)
print 'Your year of birth is %d. Is this correct?' % (yearofbirth)
print "There are %d women in the room born in %d and %s is one of them." % (pplinroom/2, yearofbirth, name)
Result:
Your year of birth is 1990. Is this correct?
Your year of birth is 1990. Is this correct?
There are 10 women in the room born in 1990 and Mary is one of them.
The first string used double quotes and the variable was inserted into the string and displayed to the user. The second string behaved just like the first string, because unlike in Ruby, defining strings with single quotes does not affect the string formatting. The third string shows that code can be evaluated (pplinroom / 2
) and inserted into the string.
Practice your Python online using the Codecademy website. Codecademy is a free website created in 2011 to allow anyone to learn how to code right in the browser, without installing or downloading any software. Practice all of the tags (and a few more) that you learned in this chapter by following these steps:
www.dummies.com/go/codingfd
, and click on the link to Codecademy.Sign in to your Codecademy account.
Signing up is discussed in Chapter 3. Creating an account allows you to save your progress as you work, but it’s optional.
After you have finished completing the instructions, click the Save and Submit Code button.
If you have followed the instructions correctly, a green checkmark appears and you proceed to the next exercise. If an error exists in your code a warning appears with a suggested fix. If you run into a problem, or have a bug you cannot fix, click on the hint, use the Q&A Forum, or tweet me at @nikhilgabraham
and include hashtag #codingFD
.
52.14.130.13