The Basics - Python Bootcamp: The Crash Course for Understanding the Basics of Python Computer Language (2016)

Python Bootcamp: The Crash Course for Understanding the Basics of Python Computer Language (2016)

Chapter 3. The Basics

In this section, you’ll learn about the basics of the Python programming language. The following pages will teach you how to create programs using Python. Additionally, you’ll know about the different parts of Python statements such as strings and variables. Study this chapter carefully because it can help you become a great Python user.

How to Create Python Programs

In general, programs created using Python are just ordinary text files. That means you can edit them with typical text editors. Use your favorite editor: you can create or improve Python programs using any text editing software. However, it would be great if you can use one that has syntax highlighting for Python statements.

Your First Program

Inexperienced programmers start their Python journey by writing the“Hello, World!” program. Here, the program simply states“Hello, World!” and then closes itself. Try this simple exercise:

1. Access your favorite text editor.

2. Create a file and save it as“hello.py.” Inside that file, enter the following line:

The“Hello, World!” program utilizes PRINT, a function that sends the parameters of a statement to the machine’s terminal. The PRINT function adds a newline character to the statement’s output. Thus, it automatically transfers the cursor to the subsequent line.

Important Note: For Python version 2, PRINT is considered as a statement instead of a function. That means you may use it without any parenthesis. In this situation, PRINT does two things:

· It sends the whole line to the terminal

· It allows users to indicate multiline statements by placing a comma after the last character.

You’ve just completed your own program. Now, you are ready to run it using Python. Notice that this procedure differs based on the OS (i.e. operating system) you are using.

For Windows computers:

1. Create a new folder. You should only use this folder for Python computer programs. Save the hello.py file in this folder. For this exercise, let’s assume that you named the folder:“C:\pythonfiles

2. Access the Start menu and choose“Run…”

3. Open the OS’ terminal by typing“cmd” in the dialogue box.

4. Type cd \pythonfiles and hit Enter. This action will set the pythonfiles folder as the directory.

5. Run the program by typing hello.py(i.e. the program’s filename).

For Mac computers:

· Create a folder that will be used for Python programs only. For this exercise, name this folder“pythonfiles” and save it in your computer’s Home folder (i.e. the one that holds folders for Music, Movies, Pictures, Documents, etc.).

· Save the hello.py program into the pythonfiles folder.

· Access the Applications section of your computer, go to Utilities, and activate the Terminal software.

· Enter cd pythonfiles into the dialogue box and press Enter.

· Run the Hello, World! program by typing“python ./hello.py.”

For Linux computers:

· Create a folder and name it“pythonfiles.” Then, save the hello.py file in it.

· Activate the computer’s terminal program. Follow these instructions:

o For KDE users– go to the main menu and choose“Run Command…”

o For GNOME users– go to the main menu, access the Applications section, open Accessories, and choose Terminal.

· Enter“cd ~/pythonpractice.”

· Run the program by typing“python. .hello.py.”

The Outcome

The screen must show:

Hello, World!

That’s it. If your computer screen shows this message, you did an excellent job. You’re one step closer to being a great Python programmer.

The Variables and Strings in the Python Language

This section will focus on strings and variables. As a beginner, you should know that these two types of data play a huge role in the Python programming language.

The Variables

Basically, variables are things that hold changeable values. That means you can consider variables as boxes that can hold different kinds of stuff. Keep in mind that you can use variables to keep different things. For now, however, let’s use them for storing numbers. Check the screenshot below:

The code above generates a variable named“lucky.” Afterward, it assigns the variable to a number (i.e. 7). If you’ll“ask” Python about the data stored in lucky, you’ll get 7 as the response.

You may also edit the value inside variables. For instance:

With the codes above, you saved a variable named“changing,” assigned the number 3 to it, and confirmed that the first statement is correct. Afterward, you assigned the number 9 to the variable, and asked the system about the new content. The Python language replaced 3 with 9.

Then, you created a new variable named“different.” You assigned the number 12 for this variable. That means you currently have two different variables, namely: changing and different. These variables hold different data– setting another value for one of them won’t affect the other.

Python allows you to assign the value of an existing variable to a different one. For instance:

To prevent confusion, remember that the variable’s name is always shown on the left side of the assignment operator (i.e. the“=” sign). The variable’s value, on the other hand, is displayed on the operator’s right side. That means for each variable, you’ll see the name first followed by the value.

At first, the code created two variables: red and blue. Then it assigned different values for each: 5 and 10, respectively. Notice that you can place different arguments on the PRINT function to make it show several items in a single line. As the result shows, red holds 5 while blue stores 10.

Then, the code created another variable and named it“yellow.” Afterward, the code instructed Python that yellow’s value should be identical to that of red. Because of that, Python assigned the number 5 to yellow.

Next, the code instructed Python that red’s value must be changed so that it is equal to that of blue. The value of blue is 10 so Python assigns that number to red (the number 5 is“thrown away”). At the last part of the screenshot, Python indicates the value of red, blue and yellow: 10, 10, 5, respectively.

Wait! The code told Python that the value of yellow must be equal to that of red, didn’t it? Why does the screenshot show that yellow’s value is 5 even though red’s is 10? It’s simple. The code instructed the Python language that yellow should have red’s value at the moment it was coded. The connection between red and yellow stopped as soon as Python assigned a value to the latter. Yellow received 5 - and 5 will stay regardless of what happens to its original source (unless a new statement is given).

The Strings

Basically, strings are lists of characters that follow a certain arrangement.

What is a“character?” Let’s relate this concept with a physical object: the keyboard. Anything you can enter using a keyboard is considered as a character (e.g. numbers, letters, punctuation marks, etc.).

For instance,“Birthday” and“Halloween” are strings. These strings are formed by letters (i.e. characters). You can also add spaces in your strings:“good morning” contains 12 characters: good = 4, space = 1, morning = 7. Currently, you can include any number of characters in your Python strings. That means there are no limits when it comes to the quantity of characters that you can use. Actually, you can even create a string that has no character in it (programmers call it an“empty string.”).

With Python, you can declare strings in three different ways:

1. (‘)– Using single quotation marks

2. (“)– Using double quotation marks

3. (“””)– Using triple quotation marks

You can use any of these methods. However, make sure that you will be consistent regarding your string declarations. Begin and end your strings using the same declaration. Check the screenshot below:

As you can see, quotation marks start and end strings. By default, Python will consider the quotation marks in your statements as markers for the beginning or end of strings.

In some situations, however, you have to include quotation marks in your statements. That means you must stop Python from ending your statements prematurely (i.e. when it sees the quotation marks in your codes). You can accomplish this using a backslash. By adding a backslash right before the quotation marks, you’re telling Python that those marks are included in the string. The act of putting a backslash before a different symbol is known as“escaping” that particular symbol.

Important Note: When adding a backslash to your Python strings, you still need to“escape” it (i.e. place a backslash before the needed backslash). This action will inform Python that the backslash must be used as an ordinary symbol. Analyze the screenshot below:

After analyzing the examples above, you’ll realize that only the characters used to quote strings must be escaped. This simple rule makes Python statements easy to read.

To help you understand strings further, let’s visit your first Python program:

Well, it seems you have used strings even before you learned about them. You may also concatenate strings in the Python programming language. Concatenation is the process of combining two different strings by adding a“+” sign between them. Let’s use the same program again:

In the example above,“Hello,” and“world!” are entered as separate strings. This is done by enclosing both strings in quotation marks. Then, the“+” sign is added between the strings to combine (i.e. concatenate) them. Did you see the space between the comma and the quotation mark? That space is mandatory: without it, you’ll get the following string:

Python also allows you to repeat strings. That means you won’t have to type the same thing several times. To repeat strings, just use the asterisk:

Lastly, you can utilize“len()” to count the characters that form any string. You just have to place the string you want to check inside the parentheses. Here’s an example:

Variables and Strings– How to Use Them Together

Now that you know how strings and variables work, you’re ready to use them together.

As discussed earlier, variables can hold different types of information– even strings. Here’s an example:

The program above creates a variable named“question.” Then, it stores the string“What did you have for lunch?” inside that variable. Lastly, it instructs Python to give out the string.

It is important to note that you should not enclose the variable with quotation marks. By omitting quotation marks, you are telling Python that you are using“question” as a variable, not as a string. If you’ll enclose the variable using quotation marks, Python will consider it as an ordinary string. It will give out“question” rather than“What did you have for lunch?”

How to Combine Strings and Numbers

Analyze the screenshot below:

This code is designed to accept a number from the programmer, add ten to that number, and give out the sum. If you’ll run it, however, you’ll get the following error message:

What’s happening here? Instead of giving out a number, Python shows“TypeError.” This message means there is an issue with the information entered. To be specific, Python cannot determine how to combine the two kinds of data being used: strings and integers.

For instance, Python assumes that“number” (i.e. a variable) contains a string, rather than a number. If the programmer types in“15,” Python will think that the variable holds a 2-character string: 1 and 5. What can you do to inform Python that 15 is a number?

Additionally, when asking for the answer, you are instructing Python to combine a number (i.e. plusTen) and a string. The programming language doesn’t know how to accomplish that. Python can only combine two strings. How can you make Python treat numbers as strings, so you can use it with a different string?

Fortunately, you have two powerful functions at your disposal:

1. str()– This function can convert numbers into strings.

2. int()– This function can convert strings into numbers.

When using these functions, you just have to place the string/number you want to convert inside the parentheses. If you will apply this method to the code given earlier, you will get the following result:

The Fundamental Concepts

Python has 5 basic concepts, namely:

1. Scope– For large systems, you have to limit the relationship between codes. This is important if you want to prevent errors or unpredictable system behaviors. If you won’t restrict the effect of your codes on other codes, the entire system might get confused.

You can control the“scope” of your codes by assigning specific name groups to each programmer. For instance, one programmer will use the names of countries while another one uses names of animals. This technique can help in limiting the connections between your Python codes.

2. Objects– Similar to other object-oriented languages, Python uses code and data groups.

In Python, you’ll create (i.e. instantiate) objects using“Classes” (a set of templates used in this programming language). Objects possess“attributes,” which store the different pieces of data and code that form the object.

Accessing an object’s attribute is easy:

1. Enter the object’s name and place a dot after it.

2. Specify the name of the attribute/s you want to access.

3. Namespaces– Python has dir(), a preinstalled function that can help you understand namespaces. After starting Python’s interpreter, you can use dir() to show the objects in the default or current namespace. Check the screenshot below:

You can also use dir() to list the available names inside module namespaces. For this example, let’s use type() on _builtins_ (an object from the screenshot above). This function, i.e. type(), allows us to know the file type of an object. See the screenshot below:

The image shows that _builtins_ is a module. That means you can use dir() to list the names inside _builtins_. You’ll get this result:

This concept is easy to understand. Basically, namespaces are places in which names can reside. Every name inside a namespace is completely different from those outside a namespace. Computer programmers refer to this“namespace layering” as“scope.” In general, you should place names inside a namespace if those names have values. For instance:

The image above shows that you can add names to any namespace just by using a simple statement (i.e.“import”). That code used the import statement to add“math” to the active namespace. If you want to know what that object is, you can run this command:

It says that“math” is a module. Thus, it has its own namespace. You can show the names inside math’s namespace using the dir() function:

4. Case Sensitivity– Variables are always case-sensitive. That means“SMITH,” “Smith,” and“smith” are three different variables.

5. Tabs and Spaces Don’t Mix– Since whitespaces are important in Python, keep in mind that tabs and spaces cannot be mixed. Be consistent while indenting your python statements. If you’ll use spaces for indention, stick to that character. This is an important concept that many beginners forget about.

Although tabs and spaces have the same appearance, they give different meanings when read by the Python interpreter. That means you’ll experience errors or weird results if you’ll mix them in your statements.

Important Note: If you prefer to use spaces, make sure that you will hit the spacebar four times for each indention.