© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_2

2. The Basics

Kevin Wilson1  
(1)
London, UK
 

Python programs are written in a text editor, such as Notepad, PyCharm, or the code editor in Python’s integrated development environment (IDLE), and saved with a .py file extension.

You then use the Python interpreter to execute the code saved in the file.

Let’s start at the beginning.

Language Classification

There are different levels of programming language: low-level languages and high-level languages.

Low-Level Language

A low-level language is a programming language whose functions often refer directly to the processor’s instructions and is commonly written in machine code or assembly language. Assembly language is known as a second-generation programming language , machine code being the first generation.

Let’s take a look at a simple program. Here, we have a little adder program written in assembly language for our processor, and might look something like this:
LDA 12H
ADD 07H
STA 09H
STP
Code is written in assembly language and then assembled into machine code using an assembler before it is executed.

A diagram exhibits the role of an assembler in turning a 4-line code into a sequence of binary numbers.

Figure 2-1

Code assembled into machine code by assembler

Each assembly language instruction corresponds to a sequence of binary numbers in machine code. The numbers, characters, addresses, and other data are converted into their machine code equivalents.

So, LDA could be represented by the binary code 11000011; the number 1210 is 00001100 in binary.

The assembled machine code is then executed by the processor.

High-Level Language

Python is an example of a high-level language . Rather than dealing directly with processor registers and memory addresses, high-level languages deal with variables, human-readable statements, loops, and functions.

High-level language code is either compiled into a machine code executable program or interpreted. Languages such as C or C++ are often compiled, meaning the code is written and then converted into an executable file. This makes them ideal for software development to write applications such as Microsoft Word that run on a computer.

A diagram exhibits the role of a compiler in turning a 16-line code into an E X E file.

Figure 2-2

Code compiled into machine code by compiler

Python is an interpreted language, meaning the code you write is translated into machine code directly, making it well suited to web development.

Here, you can see the interpreter executes the code line by line while accessing any data required by the program and then displays the output directly onto the screen.

A diagram exhibits the role of an interpreter in turning a 15-line code into a program output. The interpreter has an interrelationship with data.

Figure 2-3

Code interpreted by interpreter for execution

When you attempt to run your program, the interpreter will convert and execute your code, but will only do this if it doesn’t contain any errors.

If there are syntax errors, an error in the Python grammar, the interpreter will stop and highlight the error.

The first window page highlights a python grammar error. It stops interpreting and displays the message 'invalid syntax'. The date and other information are displayed on the second window page.

If your program runs, there could still be errors. These could be logical errors and can produce unexpected results and are sometimes called bugs in the program. This could be a divide by 0 error which can cause the program to crash.

The process of eliminating these errors is called debugging.

Python Language Syntax

The syntax defines how a program is written and interpreted and forms the basis of writing code.

Reserved Words

These are words reserved by the programming language that define the syntax and structure. Here are some of the most common ones:

A table of reserved programming words in two columns and 33 rows. The words are arranged alphabetically on the left with their definitions on the right.

For example , the word “while” indicates a while loop. The word “if” defines an “if statement.” You can’t use a reserved word as a variable name or function name.

Identifiers

An identifier is a name given to a class, function, or a variable. Identifiers can be a combination of uppercase or lowercase letters, numbers, or an underscore (_). Try to keep the identifiers meaningful, so that they describe what they’re used for.
printData, firstVariable, _count, userCount

Indentation

Most other programming languages such as C and C++ use braces { } to define a block of code. Python uses indentation . Use the tab key.

A table compares the programming languages C plus plus and Python. Python uses indentation to interpret a block of code, whereas C plus plus uses braces.

Comments

A comment is an explanation or annotation in the source code of a computer program for the purpose of making the source code easier for other programmers to understand. Comments are intended to be human readable for the programmer’s benefit and are ignored by the Python interpreter during execution.

Comments are very important while writing a program. You should clearly document all your code using comments, so other developers working on a project can better understand what your code is doing.

Use the hash character (#) to write single-line comments:
# Prompt user for two numbers
a = input ('Enter first number: ')
b = input ('Enter second number: ')

If you need to write a block describing the functionality, then use a triple quote before and after the comment block.

For example:
""" Prompt user for two numbers
one after the other using a text input """
a = input ('Enter first number: ')
b = input ('Enter second number: ')

Input

You can obtain input from the user using the input( ) function. This function prompts the user to type in some data.
number = input ('Enter a number: ')

Output

You can display information on the screen with the print( ) function. You can print the contents of a variable or enclose a string within the parameters of the print( ) function. For example:
print (number)

Escape Characters

An escape character tells the interpreter to perform a specific operation such as a line break or tab or a reserved character such as a quote mark or apostrophe.

Escape characters start with the a backslash () and are used to format a string. Table 2-1 lists escape characters and their function.
Table 2-1

Escape characters

Escape Character

Function

Line break

Tab (horizontal indentation)

New line in a multiline string

\

Backslash

Apostrophe or single quote

Double quote

For example, you could use the tab escape and break line character to format some text:
print("John 45 Joanne 15")
The output to this line would look something like this:
John        45
Joanne      15

Writing a Program

To write a program , open IDLE Python from the start menu. Select the File menu and then click “New File.”

A window labeled Python Shell exhibits the four-part context menu for the File option in the menu bar. New File is highlighted.

A new blank window will appear. This is the code editor. Here, you can write all your Python code.

A blank untitled window for editing lines of code is on the right side of a Python Shell window with several lines of code.

Arrange your windows as shown here, with the Python Shell on the left-hand side (or right if you prefer) – this is where you’ll see the results of your programs. Put the code editor window next to the Python Shell window.

For our first program, we’re going to write something that adds two numbers together and then displays the result.

First, we need two variables to store the numbers. We’ll use “a” and “b.” We’ll assign the number 5 to each variable.
a = 5
b = 5
Next, we need a piece of code that will add the two numbers together and store the result. In this case, the values assigned to the variables “a” and “b” will be added together and stored in the variable “result.”
result = a + b
Next, we’ll need a function to print the result on the screen:
print (result)

Let’s put it all together in a program.

A starter dot p y window exhibits three lines of variables with a print function at the bottom.

To run the program , press F5, or go to the “Run” menu in your code editor and click “Run Module.”

An untitled code editor window exhibits the context menu for the Run option in the menu bar with four functions under it. Run Module is highlighted.

You can see in the following image the output of the program, in this case “10.”

Two windows show the python code with output.

This particular program isn’t very useful. It would be much better if we could allow the user to enter the numbers they want to add together. To do this, we’ll need to add a function that will prompt the user for a value.

We’ll use the input function. We can replace the variables “a” and “b” from the previous program with the input function.
a = input ('Enter first number: ')
b = input ('Enter second number: ')
Now, because the input function reads the values entered as text (called a string), we need to convert these to numbers. So we need to modify the code that adds the two numbers together. We can use the int function – this converts the text to an integer which is a fancy name for a whole number.
result = int(a) + int(b)
Let’s put it all together in a program.

Two windows show the python code with output. The print function for the result is observed.

You can see in the following image the output of the program . The program prompted the user for two numbers, added them together, and then displayed the result underneath.

Two windows show the python code with output.

Lab Exercises

What is the output produced by the following code fragment ?
num1 = 2
num2 = 3
print (num1 + num2)
What is the output produced by the following code fragment?
num1 = 2
num2 = 3
print ("num 1 + num 2 = ", num1 + num2)
Find the errors in the following program:
Num1 = 2
num2 := 3
Sum = num1 + num2;
printf(sum)
Which of the following identifiers are valid and which are invalid? Why?
Num1
time-of-day
tax_rate
x5
int
7th_Rec
yield

How do you write comments in your code? Explain with an example.

Why should you include comments?

Summary

  • Python programs are written in a text editor, such as Notepad, PyCharm, or the code editor in Python’s development environment (IDLE), and saved with a .py file extension.

  • Python is an example of a high-level language.

  • Python is an interpreted language, meaning the code you write is translated into machine code directly, making it well suited to web development.

  • An identifier is a name given to a class, function, or a variable.

  • Python uses indentation to mark a block of code. Use the tab key to indent.

  • A comment is an explanation or annotation in the source code of a computer program for the purpose of making the source code easier for other programmers to understand.

  • You can obtain input from the user using the input( ) function.

  • You can display information on the screen with the print( ) function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.193.244