Programming Essentials in Python
Programming Essentials in Python
1
Table of Content
Contents
Notes about Programming Essentials in Python ................................................ 1
Chapter 1: Introduction to Computers, Programs, and Python ............................. 4
1. What is a computer? ...................................................................................... 5
2. Programming Languages............................................................................... 6
2.1 Machine Language ............................................................................................. 6
2.2 High-Level Language ......................................................................................... 7
2.3 Getting Started with Python ................................................................................. 9
The Problem Analysis–Coding–Execution Cycle ........................................... 9
Python Tools for development. ..................................................................... 13
Creating Python Source Code Filest ...................................................................... 14
Using Python to Perform Mathematical Computations ................................ 16
Programming Errors ........................................................................................... 16
2.4 End of chapter Questions............................................................................... 18
Chapter 2: Write your first Python program ....................................................... 23
1. First Python Program .................................................................................. 23
2. Python Comments ....................................................................................... 23
3. Variables ...................................................................................................... 24
4. Rules for Valid Variable Names ................................................................. 26
4. Descriptive names are better than short names ........................................... 27
2.4 End of chapter Questions............................................................................... 28
Chapter 3: Basic data types and operators........................................................... 32
3.1 Operators................................................................................................... 32
3.2 Standard Data Types................................................................................. 32
Numbers ......................................................................................................... 33
2
String .............................................................................................................. 35
List ................................................................................................................. 40
Tuple .............................................................................................................. 41
Dictionary ...................................................................................................... 44
3.3 End of Chapter Questions ......................................................................... 45
Chapter 4: Mathematical functions, strings ......................................................... 46
4.1 Common Python Functions ........................................................................... 46
4.2 Reading Strings from the Console .......................................................... 49
4.3 End of Chapter Questions ........................................................................ 50
Chapter 5: Selections ........................................................................................... 52
if Statements ..................................................................................................... 52
Two-Way if-elseStatements ............................................................................... 54
Nested if and Multi-Way if-elif-else Statements .................................. 58
Common Errors in Selection Statements ................................................................ 60
End of Chapter Questions ................................................................................. 62
Chapter 6: Loops.................................................................................................. 65
6.1 The while Loop .............................................................................................. 66
6.2 The for Loop ................................................................................................. 69
6.3 Nested Loops ................................................................................................. 70
6.4 Keywords break and continue ......................................................................... 71
6.5 End of Chapter Questions ........................................................................... 76
References ............................................................................................................ 80
3
Chapter 1: Introduction to Computers,
Programs, and Python
a popular open source programming language used for both standalone programs
powerful, and remarkably easy and fun to use. Programmers from every corner of
the software industry have found Python’s focus on developer productivity and
Whether you are new to programming or are a professional developer, this book’s
goal is to bring you quickly up to speed on the fundamentals of the core Python
language.
The benefits of using Python Some common terms you should know to get started
How to download Python and the other programs you will need to get started Some
of the basic functions and commands with Python Learning what comments are as
well as strings and more functions Learning what variables are and how they can
help you do in Python Getting started in programming can be scary, but Python
makes it easy. After reading this book, you will know enough about Python to
visible, physical elements of the computer, and software provides the invisible instructions
that control the hardware and make it perform specific tasks. Knowing computer
hardware isn’t essential to learning a programming language, but it can help you better
understand the effects that a program’s instructions have on the computer and its
components. This section introduces com- puter hardware components and their functions.
5
2. Programming Languages
Computers do not understand human languages, so programs must be written in a
language a computer can use. There are hundreds of programming languages, and they were
developed to make the programming process easier for people. However, all programs
machine language—a set of built-in primitive instructions. These instructions are in the
6
form of binary code, so if you want to give a computer an instruction in its native language,
you have to enter the instruction as binary code. For example, to add two numbers, you
1101101010011010
7
translated into machine code for execution. The translation can be done using another
• An interpreter reads one statement from the source code, translates it to the
machine code or virtual machine code, and then executes it right away.
• A compiler translates the entire source code into a machine-code file, and the
Figure An interpreter translates and executes a program one statement at a time. (b) A compiler
translates the entire source program into a machine-language file for execution.
8
2.3 Getting Started with Python
applications.
9
How to Download and Install Python?
[Link]
Step 2: Underneath the Python Releases for Windows find the Latest Python 3 Release
Python installation
10
Step 3: On this page move to Files and click on Windows x86-64 executable
Windows
Windows.
11
• After installation is complete click on Close. Now go to Windows and type
IDLE.
Python Shell
12
• This is Python Interpreter also called Python Shell. I printed Hello geeks, python
is working smoothly.
• The three greater than >>> sign is called the Python command prompt, where we
write our program and with a single enter key, it will give results so instantly.
✓ Python 3
➢ Text Editor
13
Creating Python Source Code Filest
Entering Python statements at the statement prompt >>> is convenient, but the statements
are not saved. To save statements for later use, you can create a text file to store the
statements and use the following command to execute the statements in the file:
python [Link]
The text file can be created using a text editor such as Notepad. The text file, filename, is
called a Python source file or script file, or module. By convention, Python files are named
Running a Python program from a script file is known as running Python in script mode.
Typing a statement at the statement prompt >>> and executing it is called running Python
in interactive mode.
2 print("Welcome to Python")
3 print("Python is fun")
When the Python interpreter sees #, it ignores all text after # on the same line.
When it sees ''', it scans for the next ''' and ignores any text between the
Python programs are case sensitive. It would be wrong, for example, to replace print in
the program with Print. You have seen several special characters (#, ", ()) in the
program. They are used in almost every program. Table 2 summarizes their uses.
15
Using Python to Perform Mathematical Computations
Python programs can perform all sorts of mathematical computations and display the
result. To display the addition, subtraction, multiplication, and division of two numbers, x
and y, use the following code:
print(x + y)
print(x – y)
print(x * y)
print(x / y)
Programming Errors
Programming errors can be categorized into three types: syntax errors, runtime errors,
and logic errors.
1- Syntax Errors
The most common error you will encounter are syntax errors. Like any programming
language, Python has its own syntax, and you need to write code that obeys the syntax
rules. If your program violates the rules—for example, if a quotation mark is missing or a
word is misspelled—Python will report syntax errors.
Syntax errors result from errors in code construction, such as mistyping a statement, incor-
rect indentation, omitting some necessary punctuation, or using an opening parenthesis
with- out a corresponding closing parenthesis. These errors are usually easy to detect,
16
because Python tells you where they are and what caused them. For example, the following
print statement has a syntax error.
2- Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. They occur while
carry out. Input mistakes typically cause runtime errors. An input error occurs when the
user enters a value that the program cannot handle. For instance, if the program expects to
read in a number, but instead the user enters a string of text, this causes data-type errors to
Another common source of runtime errors is division by zero. This happens when the
divisor is zero for integer divisions. For example, the expression 1 / 0 in the following
statement would cause a runtime error.
17
3- Logic Errors
Logic errors occur when a program does not perform the way it was intended to. Errors of
this kind occur for many different reasons. For example, suppose you wrote the program
18
19
20
21
22
Chapter 2: Write your first Python program
1. First Python Program
"Hello, World!" is a simple program that outputs Hello, World! on the screen.
1. Create a file and save it with .py extension and then write the following
code.
2. type the word print followed by a set of parentheses with the text "Hello,
World" inside:
>> print("Hello, World")
2. Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully. Types of comments in Python:
1. Single line Comments:
Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next
line and continue the Python Comments. Python’s single-line comments are proved useful
for supplying short explanations for variables, function declarations, and expressions. For
example
23
# Print “GeeksforGeeks !” to console
print("GeeksforGeeks")
Output
GeeksforGeeks
2. Multiline Comments:
Python does not provide the option for multiline comments. However, there are different
ways through which we can write multiline comments. Multiline comments using multiple
hashtags (#). We can multiple hashtags (#) to write multiline comments in Python. Each
and every line will be considered as a single-line comment. For example
# Python program to demonstrate
# multiline comments
print("Multiline comments")
Output
Multiline comments
Comments can be used to explain Python code. It can be used to make the code
more readable. Comments can be used to prevent execution when testing code.
3. Variables
In Python, variables are names that can be assigned a value and then used to refer
to that value throughout your code. Variables are fundamental to programming for
two reasons:
1. Variables keep values accessible: For example, you can assign the result of
some time-consuming operation to a variable so that your program doesn’t
have to perform the operation each time you need to use the result.
24
2. Variables give values context: The number 28 could mean lots of different
things, such as the number of students in a class, the number of times a user has
accessed a website, and so on. Giving the value 28 a name like num_students
makes the meaning of the value clear.
In this section, you’ll learn how to use variables in your code, as well as some of
the conventions Python programmers follow when choosing names for variables.
Values are assigned to variable names using a special symbol called the
assignment operator (=) . The = operator takes the value to the right of the operator
and assigns it to the name on the left.
Let’s modify the hello_world.py file from the previous section to assign some text
in a variable before printing it to the screen:
On the first line, you create a variable named greeting and assign it the value "Hello,
World" using the = operator.
print(greeting) displays the output Hello, World because Python looks for the name
greeting, finds that it’s been assigned the value "Hello, World", and replaces the
variable name with its value before calling the function. If you hadn’t executed
greeting = "Hello, World" before executing (greeting), then you would have seen a
NameError like you did when you tried to execute print(Hello, World) in the
previous section.
25
Variable names are case sensitive, so a variable named greeting is not the same as a
variable named Greeting. For instance, the following code produces a NameError:
26
For example, each of the following is a valid Python variable name:
➢ string1
➢ _a1p4a
➢ list_of_names
The following aren’t valid variable names because they start with a digit:
➢ 9lives
➢ 99_balloons
➢ 2beOrNot2Be
Descriptive variable names are essential, especially for complex programs. Writing
descriptive names often requires using multiple words. Don’t be afraid to use long
variable names.
In the following example, the value 3600 is assigned to the variable s:
s = 3600
27
The name s is totally ambiguous. Using a full word makes it a lot easier to
understand what the code means:
seconds = 3600
seconds is a better name than s because it provides more context. But it still doesn’t
convey the full meaning of the code. Is 3600 the number of seconds it takes for a
process to finish, or is it the length of a movie?
There’s no way to tell. The following name leaves no doubt about what the code
means:
seconds_per_hour = 3600
When you read the above code, there’s no question that 3600 is the number of
seconds in an hour. seconds_per_hour takes longer to type than both the single
letter s and the word seconds, but the payoff in clarity is massive.
Although naming variables descriptively means using longer variable names, you
should avoid using excessively long names. A good rule of thumb is to limit
variable names to three or four words maximum.
28
29
30
31
Chapter 3: Basic data types and operators
Python, a widely used high-level programming language, offers various built-in
data types and operators. Here's a brief overview of both.
3.1 Operators
These are special symbols which help the user to carry out operations like addition,
subtraction, etc. Python provides following type of operators:
Relational operators: <, <=, >, >=, != or < > and ==.
➢ Numbers
➢ String
➢ List
32
➢ Tuple
➢ Dictionary
Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them.
Python supports different numerical types:
➢ int for integer numbers : Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.
➢ float for decimal numbers: Float, or "floating point number" is a number, positive or
negative, containing one or more decimals.
➢ complex for complex numbers: Complex numbers are written with a "j" as the
imaginary part:
Variables of numeric types are created when you assign a value to them. For example
x = 1 # int
y = 2.8 # float
z = 1j # complex
for example:
33
34
String
A string is a collection of one or more characters put in a single quote, double-
quote, or triple-quote. In python there is no character data type, a character is a
string of length one. It is represented by str class.
Creating String: Strings in Python can be created using single quotes or double
quotes or even triple quotes.
As you’ve already seen, you can create a string by surrounding some text with
quotation marks:
➢ string2 = "1234"
You can use either single quotes (string1) or double quotes (string2) to create a
string as long as you use the same type at the beginning and end of the string.
35
Whenever you create a string by surrounding text with quotation marks, the string
is called a string literal. The name indicates that the string is literally written out in
your code. All the strings you’ve seen thus far are string literals. A string is
organized as an array of characters. For example:
Example 1:
Example 2:
36
Example 3:
37
For example:
38
Strings (Functions)
Example 1:
Example 2:
39
List
Python Lists are just like dynamically sized arrays. A list is a collection of things,
enclosed in [ ] and separated by commas. The list is a sequence data type which is used to
store the collection of data. Tuples and String are other types of sequence data types.
For example:
Here we are creating Python List using [].
Var = ["Geeks", "for", "Geeks"]
print(Var)
Output:
["Geeks", "for", "Geeks"]
40
Tuple
A Tuple is a sequence, just like a list. The differences between tuples and lists are:
➢ tuples use parentheses (), whereas lists use square brackets [].
41
How to remove the entire tuple?
42
Lists (Functions)
43
Dictionary
Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.
For example:
print(Dict)
44
3.3 End of Chapter Questions
45
Chapter 4: Mathematical functions, strings
The focus of this chapter is to introduce functions, strings, and objects, and to use
them to develop programs.
46
Many programs are created to solve mathematical problems. The Python math module
provides the mathematical functions listed in Table.
47
48
4.2 Reading Strings from the Console
To read a string from the console, use the input function. For example, the
following code reads three strings from the keyboard:
49
4.3 End of Chapter Questions
50
51
Chapter 5: Selections
In Python, the selection statements are also known as Decision control statements or
branching statements. The selection statement allows a program to test several conditions
if Statements
A one-way if statement executes the statements if the condition is true. Python has several
types of selection statements: one-way if statements, two-way if- else statements, nested if
A one-way if statement executes an action if and only if the condition is true. The syntax
if boolean-expression:
The statement(s) must be indented at least one space to the right of the if keyword and each
52
53
Two-Way if-elseStatements
A two-way if-else statement decides which statements to execute based on whether the
condition is true or false. A one-way if statement takes an action if the specified condition
is True. If the condition is False, nothing is done. But what if you want to take one or
more alternative actions when the condition is False? You can use a two-way if-else
statement. The actions that a two-way if-else statement specifies differ based on whether
the condition is True or False.
if boolean-expression: statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case
54
Figure An if-else statement executes statements for the true case if the Boolean expression
evaluates to True; otherwise, statements for the false case are executed.
If the boolean-expression evaluates to True, the statement(s) for the true case are exe-
cuted; otherwise, the statement(s) for the false case are executed. For example, consider
if radius >= 0:
else:
print("Negative input")
If radius >= 0 is true, area is computed and displayed; if it is false, the message
Here is another example of the if-else statement. This one determines whether a num-
else:
55
print(number, "is odd.")
Suppose you want to develop a program for a first grader to practice subtraction. The pro-
gram randomly generates two single-digit integers, number1 and number2, with
number1 >= number2 and asks the student a question such as "What is 9 – 2? " After the
student enters the answer, the program displays a message indicating whether it is correct.
Step 4: Check the student’s answer and display whether the answer is correct. The
56
57
Nested if and Multi-Way if-elif-else Statements
statement.
The statement in an if or if-else statement can be any legal Python statement, including
another if or if-else statement. The inner if statement is said to be nested inside the outer if
statement. The inner if statement can contain another if statement; in fact, there is no limit
to the depth of the nesting. For example, the following is a nested if statement:
if i > k:
if j > k:
The nested if statement can be used to implement multiple alternatives. The statement given
in Figure below, for instance, assigns a letter value to the variable grade according to the
58
59
This style, called multi- way if statements, avoids deep indentation and makes the program
easier to read. The multi-way if statements uses the syntax if-elif-else; elif (short for else if )
is a Python keyword.
60
61
End of Chapter Questions
62
63
64
Chapter 6: Loops
A loop can be used to tell a program to execute statements repeatedly. Suppose that you
need to display a string (e.g., Programming is fun!) 100 times. It would be tedious to type
Python provides a powerful construct called a loop, which controls how many times in
statement, you don’t have to code the print statement a hundred times; you simply tell the
computer to display a string that number of times. The loop statement can be written as
follows:
count = 0
while count < 100: print("Programming is fun!")
count = count + 1
The variable count is initially 0. The loop checks whether count < 100 is true. If so, it
executes the loop body—the part of the loop that contains the statements to be repeated—
to display the message Programming is fun! and increments count by 1. It repeatedly exe-
65
cutes the loop body until count < 100 becomes false (i.e., when count reaches 100). At this
point the loop terminates and the next statement after the loop statement is executed.
A loop is a construct that controls the repeated execution of a block of statements. The con-
cept of looping is fundamental to programming. Python provides two types of loop state-
ments: while loops and for loops. The while loop is a condition-controlled loop; it is
controlled by a true/false condition. The for loop is a count-controlled loop that repeats a
A while loop executes statements repeatedly as long as a condition remains true. The
Statement(s)
Figure below shows the while-loop flowchart. A single execution of a loop body is called
Boolean expression that controls the body’s execution. It is evaluated each time to determine if
the loop body should be executed. If its evaluation is True, the loop body is executed;
otherwise, the entire loop terminates and the program control turns to the statement that
follows the whileloop. The loop that displays Programming is fun!100 times is an
66
example of a whileloop. Its flowchart is shown in Figure b. The loop-continuation-
condition is count <100 and the loop body contains two statements:
FIGURE The while loop repeatedly executes the statements in the loop body as long as
67
Here is another example illustrating how a loop works:
68
6.2 The for Loop
A Python for loop iterates through each value in a sequence. Often you know exactly how
many times the loop body needs to be executed, so a control variable can be used to count
the executions. A loop of this type is called a counter-controlled loop. In general, the loop
can be written as follows:
i = initialValue # Initialize loop-control variable
while i < endValue:# Loop body
...
i += 1 # Adjust loop-control variable
A sequence holds multiple items of data, stored one after the other. Later in the book,
we will introduce strings, lists, and tuples. They are sequence-type objects in Python. The
vari- able vartakes on each successive value in the sequence, and the statements in the body
For example,
69
6.3 Nested Loops
A loop can be nested inside another loop. Nested loops consist of an outer loop and one or
more inner loops. Each time the outer loop is repeated, the inner loops are reentered and
started anew. This example presents a program that uses nested for loops to display a
multiplication table.
70
The program displays a title (line 1) on the first line in the output. The first for loop
(lines 4–5) displays the numbers 1 through 9 on the second line. A line of dashes (-) is dis-
The next loop (lines 10–15) is a nested for loop with the control variable i in the outer
loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner
To align the numbers properly, the program formats i * j using format(i * j, "4d")
(line 14). Recall that "4d" specifies a decimal integer format with width 4.
Normally, the print function automatically jumps to the next line. Invoking print(item,
end = '') (lines 3, 5, 11, and 14) prints the item without advancing to the next line.
71
The break and continue keywords provide additional controls to a loop. You can use the
The program adds integers from 1 to 20 in this order to sum until sum is
greater than or equal to 100. Without lines 7–8, this program would
calculate the sum of the numbers from 1 to 20. But with lines 7–8, the loop
You can also use the continue keyword in a loop. When it is encountered, it ends
the cur- rent iteration and program control goes to the end of the loop body. In other
72
words, continuebreaks out of an iteration, while the break keyword breaks out of a
The program adds all the integers from 1 to 20 except 10 and 11 to sum. The continue
statement is executed when number becomes 10 or 11. The continue statement ends the
current iteration so that the rest of the statement in the loop body is not executed;
therefore, number is not added to sum when it is 10 or 11. Without lines 6 and 7, the
In this case, all the numbers are added to sum, even when number is 10 or 11. Therefore,
73
You can always write a program without using break or continue in a loop. In general, it
is appropriate to use break and continue if their use simplifies coding and makes
Suppose you need to write a program to find the smallest factor other than 1 for an
integer n (assume n >= 2). You can write a simple and intuitive code using the
Obviously, the break statement makes the program simpler and easier to read in this
example. However, you should use break and continue with caution. Too many break
74
and continue statements will produce a loop with many exit points and make the pro-
75
6.5 End of Chapter Questions
76
77
78
79
References
[Link]
[Link]
language/?ref=l
[Link]
sources/Python%[Link]
[Link]
science/[Link]
[Link]
[Link]
80