Wrapping Your Head around Python - Developing Your Coding Skills Further - Coding For Dummies (2015)

Coding For Dummies (2015)

Part IV. Developing Your Coding Skills Further

Chapter 14. Wrapping Your Head around Python

In This Chapter

arrow Understanding Python principles and style

arrow Practicing Python code like assigning variables and using if statements

arrow 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.

What Does Python Do?

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.

technicalstuff.eps SQLite is one free lightweight database commonly used by Python programmers to store data.

Many highly trafficked websites, such as YouTube, are created using Python. Other websites currently using Python include:

· Quora for its community question and answer site.

· Spotify for internal data analysis.

· Dropbox for its desktop client software.

· Reddit for generating crowd-sourced news.

· Industrial Light & Magic and Disney Animation for creating film special effects.

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.

tip.eps You can generally confirm the front-end programming language used by any major website with BuiltWith available at www.builtwith.com. After entering the website address in the search bar, look under the Frameworks section for Python. Note that websites may use Python for backend services not visible to BuiltWith.

Defining Python Structure

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.

Understanding the Zen of Python

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.

technicalstuff.eps 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”.

· There should be one — and preferably only one — obvious way to do it: This principle is directly opposite to Perl’s motto, “There’s more than one way to do it.” In Python, two different programmers may approach the same problem and write two different programs, but the ideal is that the code will be similar and easy to read, adopt, and understand. Although Python does allow multiple ways to do a task — as, for example, when combining two strings — if an obvious and common option exists, it should be used.

· If the implementation is hard to explain, it’s a bad idea: Historically, programmers were known to write esoteric code to increase performance. However, Python was designed not to be the fastest language, and this principle reminds programmers that easy-to-understand implementations are preferable over faster but harder-to-explain ones.

tip.eps Access the full list by design principles, which is in the form of a poem, by typing import this; into any Python interpreter, or by visiting https://www.python.org/dev/peps/pep-0020. These principles, written by Tim Peters, a Python community member, were meant to describe the intentions of Python’s creator, Van Rossum, who is also referred to as the Benevolent Dictator for Life (BDFL).

Styling and spacing

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."

technicalstuff.eps The examples in this book are written for Python 2.7. There are two popular version of Python currently in use — Python 2.7 and Python 3. Python 3 is the latest version of the language but it is not backwards-compatible, so code written using Python 2.7 syntax does not work when using a Python 3 interpreter. Initially, Python 2.7 had more external libraries and support than Python 3, but this is changing. For more about the differences between versions see https://wiki.python.org/moin/Python2orPython3.

If you ran this code it would do the following:

· Print a line asking for your first name.

· Take user input (raw_input(What’s your first name?)) and save it to the first_name variable.

· Transform any inputted text into uppercase.

· Test the user input. If it equals “NIK,” then it will 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:

· Less punctuation: Unlike JavaScript, Python has no curly braces, and unlike HTML, no angle brackets.

· 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.

tip.eps See Python style suggestions on indentation, whitespaces, and commenting by visiting https://www.python.org/dev/peps/pep-0008.

· Newlines indicate the end of statements: Although you can use semi-colons to put more than one statement on a line, the preferred and more common method is to put each statement on its own line.

· Colons separate code blocks: New Python programmers sometimes ask why using colons to indicate code blocks, like the one at the end of the 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.

Coding Common Python Tasks and Commands

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.

tip.eps Millions of people have learned Python before you, so it’s easy to find answers to questions that might arise while learning simply by conducting an Internet search. The odds are in your favor that someone has asked your question before.

Defining data types and variables

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

tip.eps Avoid starting your variable names with the number one (1), a lowercase “L” (l), or uppercase i (I). Depending on the font used these characters can all look the same, causing confusion for you or others later!

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.

Computing simple and advanced math

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

tip.eps The # symbol indicates a comment in Python.

tip.eps Don’t just read these commands, try them! Go to http://repl.it/languages/Python for a lightweight in-browser Python interpreter that you can use right in your browser without downloading or installing any software.

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:

· Write the statement import math just once in your code before using the math functions in the math module.

· Reference the math module, as follows: math.method(value) or math.method(variable).

See these math functions with examples in Table 14-2.

technicalstuff.eps Modules are separate files that contain Python code, and the module must be referenced or imported before any code from the module can be used.

1402

tip.eps See all the function in the math module by visiting https://docs.python.org/2/library/math.html.

Using strings and special characters

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'

remember.eps Variables can also store numbers as strings instead of numbers. However, even though the string looks like a number, Python will not be able to add, subtract, or divide strings and numbers. For example, consider amountdue = "18" + 24 — running this code as is would result in an error. Python does multiply strings but in an interesting way — print ‘Ha’ * 3 results in ‘HaHaHa’.

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.

1403

tip.eps Escape sequences are interpreted only for strings with double quotation marks. For a full list of escape sequences see the table under Section 2.4 "Literals" at http://docs.python.org/2/reference/lexical_analysis.html.

Deciding with conditionals: If, elif, else

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

tip.eps Notice there are no curly brackets or semi-colons, but don’t forget the colons and to indent your statements!

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.

tip.eps You cannot have an elif or an else by itself, without a preceding if statement. You can include many elif statements, but one and only one else statement.

The conditional in an if statement compares values using comparison operators, and common comparison operators are described in Table 14-4.

1404

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 trueand 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.

Input and output

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?")

9781118951309-fg1401.tif

Figure 14-1: An if-else statement with an elif.

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

tip.eps Python, unlike Ruby, does not store the newline \n escape sequence after user input.

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.

Shaping Your Strings

Whenever you collect input from users, you need to clean the input to remove errors and inconsistencies. Here are some common data cleaning tasks:

· Standardizing strings to have consistent upper and lower case

· Removing white space from user input

· Inserting a variable’s value in strings displayed to the user

Python includes many built-in methods that make processing strings easy.

Dot notation with upper(), lower(), capitalize(), and strip()

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.

1405

String formatting with %

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.

technicalstuff.eps The string.format() method is another way to format strings in Python.

Building a Simple Tip Calculator Using Python

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:

1. Open your browser, go to www.dummies.com/go/codingfd, and click on the link to Codecademy.

2. 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.

3. Navigate to and click on Python Syntax to practice some basic Python commands.

4. Background information is presented in the upper left portion of the site, and instructions are presented in the lower left portion of the site.

5. Complete the instructions in the main coding window.

6. 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.