Diving Into Python: A Comprehensive Guide to Programming Excellence
Table of Contents
ToggleWhat is Python?
Python is a popular high-level programming language developed by Guido van Rossum in the late 1980s. The language emphasizes code clarity and simplicity, allowing programmers to construct applications quickly.
Python code, like all high-level programming languages, is similar to the English language, which machines cannot grasp. To write, test, and execute Python programs, we must first install the Python interpreter.
Third-party tools, such Py2exe and Pyinstaller, can package Python code into executable programs for common operating systems like Windows and MacOS. This enables us to share Python programs without requiring users to install the interpreter.
Why Learn Python?
There are many high-level programming languages accessible, including C, C++, and Java. Fortunately, high-level programming languages are extremely comparable. The biggest differences are in syntax, accessible libraries, and how to access them. A library provides resources and pre-written code for programmers to use. After mastering one language, you may quickly learn a new one.
If you’re new to programming, Python is an excellent place to begin. Python’s simplicity makes it a great language for novices to learn. Most Python programs require many less lines of code to complete the same purpose than other languages such as C. This leads to fewer code errors and shorter development times. Python offers a wide range of third-party resources to enhance its functionality. Python is versatile and may be utilized for various tasks, including desktop, database, network, game, and mobile development. Python is a cross-platform language, therefore code built for one operating system (e.g. Windows) can be easily adapted to Mac OS or Linux without any changes.
Getting ready for Python Installing the Interpreter
To write our first Python program, we need to download the right interpreter for our PCs.
This book will utilize Python 3. According to the official Python website, Python 2.x is heritage, whereas Python 3.x is the language’s present and future. Furthermore, “Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers” .
However, Python 2 is still frequently used. Python 2 and 3 are around 90% similar. Learning Python 3 will let you grasp Python 2 code with ease.
To install the Python 3 interpreter, visit https://www.python.org/downloads. The right version should be displayed at the top of the page. To download Python 3, click on the version you want.
To install a different version, scroll down the page and find a list of available versions. Select your desired release version. We’ll be utilizing version 3.4.2 in this book. You will be routed to the download page for the specific version.
At the bottom of the page, you’ll find a table of installers for that version. Select the appropriate installer for your PC. The installer to use relies on two factors:
1. Operating system (Windows, Mac OS, or Linux)
2. Processor type (32-bit or 64-bit).
If you have a 64-bit Windows machine, you will likely use the “Windows x86-64 MSI installer”. Simply click the link to download it. Don’t worry if you download and execute the wrong installer. You will receive an error notice and the interpreter will not install. To get started, simply download the relevant installer.
After installing the interpreter, you may start coding in Python.
Using Python Shell and IDLE to write our first program.
We’ll use the IDLE program that comes with the Python interpreter to write our code.
To accomplish so, let us first launch the IDLE software. Launch IDLE like any other software. In Windows 8, search for it by typing “IDLE” in the search box.
When you’ve discovered it, click IDLE (the Python GUI) to launch it. You will see the Python Shell as shown below.
The Python Shell allows us to utilize Python in an interactive fashion. This allows us to enter one command at a time. The Shell accepts user commands, executes them, and returns their results. Following this, the Shell awaits the next command.
Try typing the following in the Shell. The commands should be typed on the lines beginning with >>>, while the results are displayed on the following lines.
>> 2+3
5
>>> 3>2
True
>>> print (‘Hello World’)
Hello World
Typing 2+3 sends a command to the Shell to evaluate its value. Thus, the Shell yields 5. By typing 3>2, you are asking the Shell if 3 is greater than 2. The Shell responds “True.” Finally, the print command instructs the Shell to display the line Hello World.
The Python Shell is a useful tool for testing Python commands, particularly for beginners. Exiting and re-entering the Python Shell will erase all previously entered commands. Additionally, the Python Shell cannot be used to generate an actual application. To create a program, type your code in a text file and save it with the.py extension. This file is called a Python script.
To build a Python script, select File > New File from the top menu of our Python Shell. This will launch the text editor where we will create our first program, “Hello World”. Writing the “Hello World” program is a common milestone for beginning programmers. This program will help us become comfortable with the IDLE software.
Enter the following code into the text editor (not the shell).
#Prints the Words “Hello World”
print (“Hello World”)
The line #Prints the Words “Hello World” is highlighted in red, with the word “print” in purple and “Hello World” in green. This is the software’s approach of making our code more readable. The words “print” and “Hello World” have different functions in our application, so they are shown in separate colors. Further details will be provided in following chapters.
The line #Prints the Words “Hello World” (red) is not part of the program. This comment aims to improve code readability for other programmers. The Python interpreter ignores this line. To add comments to our program, insert a # symbol before each line of remarks, as seen below:
#This is a comment
#This is also a comment
#This is yet another comment
For multiline comments, we can use three single or double quotes, as seen below:
’’’
This is a comment
This is also a comment
This is yet another comment
’’’
Click File > Save As to save your code. Save it using the.py extension.
Done? Voilà! You have successfully written your first Python application.
Finally, click Run > Run Module to start the program (or press F5).
Your Python Shell should display the words “Hello World”.
Please keep in mind that the video was created using Python 2, so some commands may not work properly. To try his scripts, add () to the print statements. Instead of writing ‘Hello World’, use ‘print (‘Hello World’)’. Additionally, modify raw_input() to input(). In Chapter 5, we will explore print() and input() functions.
The World of Variables and Operators
After the introduction, let’s go on to the main topic. In this chapter, you will learn about variables and operators.
You’ll learn about variables, including how to name and declare them. We will learn about common procedures on them. Ready? Let’s go!
What are variables?
Variables are names for data stored and manipulated in programs. For example, assume your program needs to keep a user’s age. To name the data and define the variable, use the following statement.
userAge = 0
After defining the variable userAge, your software will allocate storage space for this data. You can access and alter this data by using the term “userAge”.
Every time you declare a new variable, you must assign it an initial value.
In this example, we assigned it the value zero. We can adjust this value in our software later.
We can also define many variables at one time. To accomplish that, simply write
userAge, userName = 30,
‘Peter’
This is equivalent to
userAge = 30
userName = ‘Peter’
Naming a Variable
Python variable names can only include letters (a-z, A-B), integers, or underscores. However, the first character can’t be a number.
You can name variables userName, user_name, or userName2, but not 2userName.
Some reserved terms cannot be used as variable names in Python due to their predefined meanings. Reserved terms include print, input, if, while, etc. We’ll learn more about each of them in future chapters.
Finally, variable names are case-sensitive. Username is not the same as userName.
There are two conventions for naming variables in Python. We can use camel case notation or underscores. Camel case is the technique of writing complex words with mixed casing, such as “thisIsAVariableName”. This will be the convention used throughout the book. Another popular technique is to use underscores (_) to separate words. Alternatively, you can name your variables like this: this_is_a_variable_name
The Assignment Sign
The = symbol in the phrase userAge = 0 differs from what we taught in Math. In programming, the = sign is referred to as the assignment sign. Using the = sign assigns the value on the right to the variable on the left. To better comprehend the phrase userAge = 0, consider it as userAge < – 0.
In programming, the expressions “x = y” and “y = x” have distinct interpretations.
Confused? An example will most likely clear things up.
Enter the following code into the IDLE editor and save it.
x = 5
y = 10
x = y
print ("x = ", x)
print ("y = ", y)
Now, execute the application. You should get the following output:
x = 10
y = 10
The third line, x = y, assigns the value of y to x (x <- y), resulting in a value of 10 for x while keeping y intact.
Next, alter the program by modifying only one statement: Change the third line from “x = y” to “y = x”. The mathematical expressions x = y and y = x are equivalent. However, this is not true in programming.
Run the second program. You’ll immediately receive
x = 5
y = 5
In this example, the x value remains 5, while the y value is altered to 5. The phrase y = x assigns x’s value to y (y <- x). Y becomes 5, whereas x remains unchanged at 5.
Basic Operators
Variables can be assigned initial values and used for standard mathematical procedures. Python’s basic operators are +, -,, /,%, and *, which represent addition, subtraction, multiplication, division, floor division, modulus, and exponent, respectively.
Example:
Suppose x = 5, y = 2
Addition: x + y = 7
Subtraction: x - y = 3
Multiplication: x*y = 10
Division: x/y = 2.5
Floor Division: x//y = 2 (rounds down the answer to the nearest whole number)
Modulus: x%y = 1 (gives the remainder when 5 is divided by 2)
Exponent: x**y = 25 (5 to the power of 2)
More Assignment Operators
In addition to the = sign, Python (and most programming languages) has several other assignment operators. These include operators such as +=, -=, and *=.
Assume we have the variable x with a starting value of ten. To increase x by 2, use the formula x = x + 2.
The software evaluates the expression on the right (x + 2) and assigns the result to the left. Eventually, the above statement becomes x < -12.
To express the same idea as x = x + 2, we can use x += 2. The += sign is a shorthand for combining the assignment and addition operators. Thus, x += 2 implies x = x + 2.
For subtraction, we can write x = x – 2 or x -= 2. This applies to all seven operators indicated in the section above.
Data Types in Python
This chapter introduces basic data types in Python, including integers, floats, and strings. Next, we’ll study type casting. Next, we’ll cover three advanced data types in Python: list, tuple, and dictionary.
Integers
Integers are numbers that do not contain any decimal parts, such as -5, -4, -3, 0, 5, 7, and so on.
To define an integer in Python, type variableName = initial value.
Example:
UserAge = 20; Mobile Number = 12398724.
Float
Floats are numbers with decimal parts, such 1.234, -0.023, and 12.01.
To declare a float in Python, type variableName = initial value.
Example:
UserHeight = 1.82; UserWeight = 67.2
String
The term “string” refers to text.
To define a string, use either ‘initial value’ (single quotes) or “initial value” (double quotes).
In this example, the userName is ‘Peter’, the userSpouseName is “Janet”, and the userAge is ’30’.
In the last example, we defined userAge as ’30’, which is a string. If you write “userAge = 30” without quotes, it is an integer.
The concatenate sign (+) allows us to merge numerous substrings.
For example, “Peter” + “Lee” equals “PeterLee”.
Built-In String Functions
Python contains several built-in routines for manipulating strings. A function is a block of reusable code that performs a certain task.
We’ll go over functions in further detail in Chapter 7.
Python has functions such as the higher() method for strings. You use it to capitalize every letter in a string. For example, ‘Peter’.upper() will return the string “PETER”. Appendix A provides additional examples and code for using Python’s built-in string functions.
Formatting Strings using the % Operator
Strings can also be formatted with the % operator. This provides greater control over how your string is displayed and kept.
The syntax for applying the % operator is
“string to be formatted” %(values or variables to be
inserted into string, separated by commas)
There are three pieces to this syntax. To format a string, first write it in quotation marks. We then write the % sign. Finally, we use round brackets () to introduce values or variables into the string. The round brackets with values inside are referred to as a tuple, which will be covered later in the chapter.
Type the following code in IDLE and run it.
brand = ‘Apple’
exchangeRate = 1.235235245
message = ‘The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR’ %(brand,
1299, exchangeRate)
print (message)
In this example, we wish to format the string ‘The price of this%s laptop is%d USD and the exchange rate is%4.2f USD to 1 EUR’. We use the %s, %d, and %4.2f formats as placeholders in the string.
The placeholders will be changed with the variable brand, value 1299, and exchangeRate, as stated by the round brackets. If we run the code, we will obtain the output shown below.
This Apple laptop costs 1299 USD, at an exchange rate of 1.24 USD to 1 EUR.
The %s formatter represents a text (“Apple”), but the %d formatter represents a number (1299). To add spaces before an integer, specify the required length of the string using a number between % and d. For example, “%5d”%(123) returns “123” (with 2 spaces in front and a total length of 5).
The%f formatter is used to format floats (decimals). Here, we format it as %4.2f, where 4 represents the total length and 2 represents two decimal places. To add spaces before a number, format it as %7.2f, resulting in “1.24” with 2 decimal places, 3 spaces, and a total length of 7.
Formatting Strings using the format() method
Python offers both the % operator and the format() function for string formatting.
The syntax is: “string to be formatted”.Format (insert values or variables into a string separated by commas).
When using the format method, we avoid using placeholders such as %s, %f, or %d. Instead, we use curly brackets, as follows:
message = ‘The price of this {0:s} laptop is {1:d} USD
and the exchange rate is {2:4.2f} USD to 1
EUR’.format(‘Apple’
, 1299, 1.235235245)
Inside the curly bracket, we first write the position of the parameter.
Use, followed by a colon. After the colon, we write the format. The curly brackets should not contain any spaces.
Format(‘Apple’, 1299, 1.235235245) specifies three parameters for the format() function. Parameters are the necessary data for a method to function properly. The parameters include ‘Apple’, 1299, and 1.235235245.
The parameter ‘Apple’ has a position of 0, while 1299 has positions 1 and 1.235235245 has a position of 2.
Positions always begin with ZERO.
When we write {0:s}, we ask the interpreter to replace {0:s} with the parameter at position 0 and that it is a string (because the formatter is’s’).
{1:d} refers to the parameter at position 1, which is an integer (formatter is d).
{2:4.2f} refers to a float parameter in position 2 that should be formatted with 2 decimal places and a total length of 4 (formatter: 4.2f).
If we print the message, we will receive
This Apple laptop costs 1299 USD, at an exchange rate of 1.24 USD to 1 EUR.
To avoid formatting the string, simply type message = ‘The price of this {} laptop is {} USD and the exchange rate is {} USD to 1 EUR’.Format(‘Apple’,1299, 1.235235245)
The parameters’ positions do not need to be specified here. The translator will replace curly brackets according to the order of the parameters provided. We’ll get.
This Apple laptop costs 1299 USD, at an exchange rate of 1.235235245 USD to 1 EUR.
Beginners may find the format() technique difficult to understand. String formatting can be more complex than what we’ve described here, but it’s sufficient for most needs. To further understand the format() method, try the following code.
message1 = ‘{0} is easier than {1}’.format(‘Python’,‘Java’)
message2 = ‘{1} is easier than {0}’.format(‘Python’,‘Java’)
message3 = ‘{:10.2f} and {:d}’.format(1.234234234, 12)
message4 = ‘{}’.format(1.234234234)
print (message1)
#You’ll get ‘Python is easier than Java’
print (message2)
#You’ll get ‘Java is easier than Python’
print (message3)
#You’ll get ‘ 1.23 and 12’
#You do not need to indicate the positions of the
parameters.
print (message4)
#You’ll get 1.234234234. No formatting is done.
You can use the Python Shell to play with the format() method.
Try typing in different strings to see what you get.
Type Casting In Python
In our software, we may need to convert between data types, such as integers and strings. This is referred to as typecasting.
Python provides three built-in methods for type casting. These include the int(), float(), and str() functions.
Python’s int() method transforms floats and strings to integers. To convert a float to an integer, type: int(5.712987). We will receive 5 (after removing the decimal point). To convert a text to an integer, type int(“4”) and it will return 4. However, we can’t type int (“Hello”) or “4.22321”. We will receive an error in both circumstances.
The float() method converts an integer or equivalent text to a float. For example, typing float(2) or float(“2”) returns 2.0. Typing float(“2.09109”) yields 2.09109, which is a float rather than a string due to the removal of quotation marks.
The str() method converts integers and floats to strings. For example, if we type str(2.1), we will receive “2.1”.
After learning about the three basic data types in Python and how to cast them, we’ll explore more sophisticated data types.
List
A list is a collection of connected data. We can store these data as a list rather than individual variables. For example, imagine our software has to save the age of five users. It’s more efficient to store user ages as a list rather than individual values (e.g., user1, user2, user3, user4, and user5).
To declare a list, use listName = [starting values]. Use square brackets [] to declare a list. Multiple values are separated by commas.