2python 11-26
2python 11-26
2
WELCOME TO PYTHON
PROGRAMMING WORLD!
2.1 History
Python is a widely used general-purpose high-level programming language.
Reading and writing instructions using Python language is much like reading and writing regular
English statements. Hence, it is high-level programming language. It was initially conceived by Guido
van Rossum1 in 1980. Python’s implementation began in December 1989, while, first version 0.9.0 was
released in Feb 1991. Python was primarily developed with a strong emphasis on code (instructions)
readability and provides easier way to write instructions for developing programs.
Python language is nowhere related to Python snake 😊 Guido Van Rossum named it Python as he
wanted to keep the name short, sweet & slightly mysterious. Also, at the time of implementation of
Python, he was reading a comedy series “Monty Python's Flying Circus”. Hence, he named it Python.
Python is a powerful language that you can use to create games, develop graphical user interfaces,
(GUI)/ web applications etc. Popular companies Google, Amazon, Facebook, Uber etc. use Python.
Python is currently managed by Python Software Foundation. Most recent major version is 3.9.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
Python has a simple syntax similar to English language.
Python allows developers to write programs in fewer lines compared to other languages.
Python runs on an interpreter system meaning that code can be executed as soon as it is written.
Python can be treated in a procedural way, an object-orientated way or a functional way.
It is possible to write Python programs in an Integrated Development Environment, such as
Thonny, Pycharm, Netbeans or Eclipse especially managing large number of Python files.
Python programming language has a global community with millions of software developers
who interact online and offline in thousands of virtual and physical locations
1 Guido van Rossum (31st Jan, 1956) is a Dutch programmer and currently living at Belmont, California.
12 Core Python for Everyone
Now, let's use a computer to do this task. As we want to use a computer to do this task, we need to
give instructions in the computer's language. Since we are learning Python, let's write instructions in
Python so that computer can execute those instructions & display addition of these 2 numbers. Like we
stored 13 & 24 in our brain’s memory to produce sum, we need to store it in computer’s memory. Let
computer to do this sum & display the result on output device like desktop monitor, laptop screen etc.
2
This number is presented in the hexadecimal system format.
3
This number is presented in the hexadecimal system format.
Welcome to Python Programming World! 13
Step 3: Add these 2 numbers and store the sum in a new variable sum.
Following instruction adds Number1 & Number2 and stores it in a variable sum
sum = Number1 + Number2
For easier understanding, you can see below representation.
Number1
13
0x0042103c sum
sum = Number1+ Number2 37
Number2 0x0054C23B
24
0x00422031
Step 4: Display addition of these 2 numbers (sum).
print(variablename) is a standard command /instruction (function) that displays the value stored at the
memory location variablename on the output device like a desktop monitor/laptop screen etc.
As we want to display the contents of a variable sum, the instruction is
print (sum)
The complete program of addition of 13, 24 and displaying the result can be written as below.
Program 2.1:
Number1=13 # step 1
Number2=24 # step 2
sum = Number1 + Number2 # step 3
print(sum) # step 4
Output:
37
FAQ:
Q. Name variables used in the program 2.1?
Number1,Number2 & sum are the variables used in the program 2.1
Q. Is print a variable?
No. It is in-built function (command) in Python that is used to display the output.
Q. What is a variable?
Variable stores values.
Q. Computer stores values in its memory. Then, why we refer to them by variable name instead of
memory address like 0x0042103c ?
If we start referring every person by his/her mobile number, will it be practicable? Similarly, referring
memory locations by hexadecimal addresses like '0x0042103c' can be cumbersome and error-prone.
Variable names are used to provide a more human-friendly way to reference memory locations where
data is stored. This becomes especially crucial as the program size increases. Using names makes it
easier to read, write, and maintain a program.
Q. What literals are used in above program 2.1? What are literals?
13 and 24 are literals used in program 2.1.
A constant value in Python is created by using a literal representation of it. e.g. 100, 98.2, ‘x’.
Literals in Python are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables.
Q. Can I use variable names a, b instead of Number1, Number2?
Yes, you can use it. However, as the program size increases, it becomes difficult to understand the
meaning of the data the variable is containing. It’s better programming practice to use relevant variable
names to improve the readability of a program.
Q. What is a function?
Function4 is a set of instructions arranged in a sequence to perform certain task.
Function is component of a program that provides particular functionality. e.g. print function is used
to display the value of the variable sum on the output device like desktop monitor, laptop screen etc.
Q. What is the meaning of the “# step 1”?
It is a comment. Text written after # is ignored by the compiler while compiling instructions in a
program. Comments are helpful when anyone reads a program.
Q. What is a comment? What are the different types of comments?
It is information written in a program that is ignored by a compiler while compiling instructions in a
program. It is like notes written for understanding the program.
Advantages of using comments:
Comments improve the readability of the program.
It is easy to read and understand a program with comments.
Useful when a new programmer has to work on the program (source code).
Comments help at the time of maintenance 5/enhancement of the application.
Python only supports a single line comment. A Single line comment is any text written after # .
However, one can comment multiple lines by writing that multiline text between ‘‘‘ ’’’ (triple double
quotes). This is actually known as documentation strings (docstrings).
4
Function will be discussed in chapter 5.
5
Maintenance is a process in which defects in the program are found and fixed. Concept of
maintenance of a vehicle is similar to a maintenance of a program.
Welcome to Python Programming World! 15
Algorithm
2.3.1 Editor
Editor is a standard program that allows you to edit your source program code. Program is written in
a file in an editor. There are many editors available, however, we will use notepad as it is good for beginners.
Every Python source program file name ends with .py extension. e.g. [Link]
2.3.2 Compiler
Every language has a grammar. Once the program is written, we need to check whether it follows
grammar rules. In case of English, if someone says to you
“program to required is a compiler compile”.
You won’t understand it. This is actually “Compiler is required to compile a program.” in a correct
English format as per the grammar rules. Hence, we must give instructions to a computer which follow
language grammar rules. e.g. print function (command) should have parentheses.
If you forget to write = sign in the program 2.1, compiler produces syntax error. Let’s remove =, compile
the program, you will get syntax error. If program doesn’t obey any grammar rule, it gives syntax error.
Compiler is a standard program that checks whether every instruction in the program is written as
per the Python language standard grammar rules or not & then translates it into bytecode.
16 Core Python for Everyone
i. Dividing a number by zero. i.e. a=0, #Test program. Attempting to divide by zero
k=90/a; a=0
ii. Trying to open a file that doesn't exist. k=90/a
You will study this in File chapter. Traceback (most recent call last):
File "[Link]", line 3, in <module>
k=90/a
ZeroDivisionError: division by zero
III. Logical Error
The aim of the above program 2.1 is to display the sum of the 2 numbers. i.e. 13 and 24. If we write
the instruction print(Number1) instead of print(sum); we will get incorrect result. If you use – (minus)
symbol instead of +(plus) symbol by mistake, it will give you wrong results which is also a logical error.
i. Multiplying when you should be #Displaying Number1 instead of sum ( program 2.1)
dividing Number1=13 # step 1
ii. Adding when you should be Number2=24 # step 2
subtracting sum = Number1 + Number2 # step 3
iii. Opening and using data from the print(Number1) # step 4
wrong file Output:
iv. Displaying the wrong message 13
Do not get discouraged while executing your first program. You will learn more if you come across
many errors initially. You must be familiar with the name Thomas Edison who invented the bulb. He
failed 10,000 times to produce an electric bulb and then successfully invented first electric bulb. When
someone asked him about his failure, he said” Now, I know 10,000 different ways by which bulb cannot
be produced.” Take motivation from him and do not get nervous even if you initially fail many
times to compile & execute a Python program. You will understand different types of errors that
become hurdle to compile & execute a Python program. This experience will help you to develop big
sized programs with ease.
18 Core Python for Everyone
Program 2.1 (Without data type declaration) Program 2.1 (With data type declaration)/
/(Without Annotations) (With Annotations)
Number1=13 # step 1 Number1:int=13 # step 1
Number2=2.4 # step 2 Number2:int=2.4 # step 2
sum = Number1 + Number2 # step 3 sum:int = Number1 + Number2 # step 3
print(sum) print(sum)
Data types of variables are determined at Data types are known before execution of a
runtime by Python while executing program. program. It makes program more readable.
In practical life, we store books in the shelf. Do we store liquid in the shelf? No, it’s not possible. We
require container to store liquid. Similarly, Python supports various data types so that programmer
can store various type of values depending upon the need by creating variables of those data types.
Following section shows various data types that Python supports. It specifies range which indicates
the maximum and minimum value that variables of that data type can store.
2.4.1 Numeric
This data type includes integers (e.g. 11,121 etc.), float (e.g. 23.222,343.2234 etc.) & complex (e.g. 2+2i,
5+2323j etc.). You may learn integer and float data type and skip learning complex number data type
if you are not familiar with complex numbers.
(i) Integer
What if someone wants to store integer values like 11,45675641, -1234, etc.? Is there any data type in
Python whose variables can store numerical values? Yes, Python supports integer data types whose
variables are used to store numerical values. These are referred as int. They are positive or negative
whole numbers with no decimal point. Integers in Python 3 are of unlimited size.
Program 2.2
(ii) Float
What if someone wants to store decimal values like 11.23? Is there any data type in Python whose
variables can store decimal values? Yes, Python supports float data types whose variables are used to
store decimal values.
Let us understand below program 2.3 which stores decimal value 11.23 in float variable var2.
Program 2.3
Program 2.3:
var1:float=22.36 #var1 is the variable, whereas, 22.36 is the value stored.
var2:float=11.23 #var2 is the variable, whereas, 11.23 is the value stored.
sum:float=var1+var2
print(“The sum is: ”,sum)
Output:
The sum is: 33.59
Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 10 2 = 250).
Size of the float data type is 4 bytes.
(iii) Complex
If you are familiar with complex number, you can read this, otherwise, you can skip this subsection.
What if someone wants to store the complex numbers like 1+2j,etc in Python? Is there any data type
in Python whose variables can store complex values? Yes, Python supports complex data types
whose variables are used to store complex values and its associated functions using the file “cmath”.
Complex numbers have their uses in many applications related to mathematics and Python provides
useful tools to handle and manipulate them.
A complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex
using the function complex(x,y). The real part can be accessed using the function real() and imaginary
part can be represented by imag().
2.4.2 String
What if the user wants to store the string literals (e.g. “Hello” or ‘Hi’ etc.)? Python provides String data
type for that. String literals in Python are surrounded by either single/double/Triple quotation marks.
e.g. 'hello' is the same as "hello". In case of multiline string, triple single quotes or triple double quotes
are used. You can store single line string using triple single/double quotes as well.
Program 2.3
var3:str=”Hello” #var3 is the variable, whereas, Hello is the value stored.
print(var3)
Output:
Hello
20 Core Python for Everyone
In program 2.1, we have directly stored 13 & 24 in variables Number 1 & Number2 respectively
without specifying data type. Then, how compiler can understand the data type of the values stored
inside variable? Yes, Python provides in-built command (function) that displays type of the data that
specified variable holds.
Program 2.4
var1=1231564
var2=11.23
var3=”Hello”
print(type(var1))
print(type(var2))
print(type(var3))
Output:
<class ‘int’>
<class 'float'>
<class 'str'>
e.g. If number a is greater than b or not i.e. a>b, it evaluates it to either True or False.
Program 2.12:
var4=1544>98232
print (“Result is “, var4)
print(type(var4))
Output:
Result is False
<class 'bool'>
You can execute above program by manually changing values of var4 and see the result. You will get
output as either True or False.
While Annotations don't enforce strict type checking at runtime, they serve as documentation and can
be used by static analysis tools. Strict type checking means if the data type is specified as int, it should
store only integer values in that variable and does not allow float, string etc.
II. Number1=13579
Number2=2468
Number1=4517
sum= Number1+ Number2
print(sum)
Output:
6985
The output is a 6985 because the variable Number1 is declared twice and hence, the latest
initialized value is overwritten. i.e. 13579 is overwritten by 4517. Hence, Number1 is 4517
which is added to 2468 & the sum is 6985.
III.
Number1=13579
Number2=2468
sum= Number1+ Number2
sum=156
print(sum)
Output:
156
The addition of 13579 and 2468 is first stored in a variable sum.
22 Core Python for Everyone
However, the next instruction sum=156 changes the contents of the variable sum to 156. Hence,
the value stored in the variable sum i.e. 156 is displayed as output.
The primitive or the basic data structures are the building blocks for data manipulation. They contain
pure and simple values of a data. In Python there are four types of primitive variable:
Integer, float, String and Boolean. Non-primitive stores not just a value, but rather a collection of values
in various formats. The non-primitive data structures are further divided as Arrays, Lists, Files.
Fig.: 2.1
2. Open the command prompt. Change the directory on the command prompt where [Link] is
saved. This can be done by writing the command “cd \d” and then your path name where the
Python module exists e.g. >cd /d D:\Project\MyPython
3. Execute the program by running the command “py [Link]” on the command prompt as shown.
FAQ:
Q. Why should we use Python language for writing this program, let us say, addition of 2
numbers as compared to machine and assembly language?
If you use machine language to write this program, you have to write instructions in machine language
which is difficult and error prone.
If you use assembly language to write this code, you would have to write instructions in assembly
language using mnemonics. Number of the instructions in assembly language are less than machine
language. However, still, it is tedious job.
If you see Python language program, it is hardly few lines of code as compared to programs written in
machine and assembly language instructions. This reduces the chances of doing mistakes while writing
a program because the size of the program is small. The biggest advantage of Python language is
platform independent. It means it can be compiled on different processors and executed. Machine
and assembly languages are specific to the machine.
Structural & Object Oriented: Python supports sequential, selection & iterative control flow. It is
possible to create objects in Python. Hence, it is object oriented as well.
Platform independent: Unlike many other programming languages including C and C++ when Python
code is compiled, it is not compiled into platform specific machine code, but it is converted into
platform independent bytecode. This bytecode is interpreted by the Python Virtual Machine (PVM) on
whichever platform it is being run.
Simple: Python is a simple and easy to learn language because of its clear syntax and readability.
That's why it reduces the cost of program maintenance. It is good for starting out because of
its simple syntax. Python's syntax are shorter than most other programming languages (Java, C, C++
etc.) If you understand the basic concept of Object oriented programming (OOP), Python would be
easy to master.
24 Core Python for Everyone
Secure: Python is secure because the reverse engineering of the .pyc files (bytecode) is a lot harder.
Architectural- neutral: Python compiler generates an architecture-neutral bytecode file which makes
the compiled code to be executable on many processors with the present Python runtime system.
Robust: Programmer has to write few lines of code as compared to other languages like C, C++ for the
same program. So, it is easy to maintain and is prone to fewer issues. Python also has the capability to
scale easily to solve complex problems. Also, the memory management techniques are in built in
Python.
Multi-threaded: With Python's multi-threaded feature it is possible to write programs that can do
many tasks simultaneously. This design feature allows developers to construct smoothly running
interactive applications.
Interpreted: Python is an Interpreted Language because Python code is executed line by line at a time.
Like other language C, C++, java etc there is no need to compile Python code, this makes it easier to
debug our code. The source code of Python is converted into bytecode.
High Performance: With the use of Just-In-Time compilers Python enables high performance.
Dynamic: Python is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Python programs can carry extensive amount of run-time information that can
be used to verify and resolve accesses to objects on run-time.
Q. What is meaning of print function (command)?
The print function prints the specified message on the output device like desktop monitor/laptop
screen. The message can be a string, or any other object, the object gets converted into a string before
displaying on the screen. You will learn more about print function in the later part of this book.
Q. Why Python is compiled & interpreted language?
Python Interpreter has compiler & Python Virtual Machine (PVM). Compiler converts Python
instruction into bytecode and Python Virtual Machine (PVM) executes it. Hence, it is compiled as well
as interpreted language.
Num1
Num1=10 10
0x00532031
Num1
Num1=20 20
2
0x00643098
When Num1=20 instruction is executed, num1 refers to the new value 20 is stored.
5. A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
6. Python does not allow special characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
Python.
7. bool(-1) is True in Python.
8. The source code program (e.g. [Link]) is stored in a secondary memory. i.e. inside C:\ or any
other drive. Hard disk is an example of secondary memory.
9. When compiled file like [Link] is executed (just click on it), it gets copied into the RAM.
10. The program that copies the executable file from secondary memory to a primary memory (RAM)
is called as a loader.
11 Python compiler stores .pyc file in __pycache__ directory. e.g. Python Compiler compiles [Link]
into [Link] and stores it into __pycache__ directory.
Questions
Q.1 State true or false.
i. Python was developed at AT&T Bell Laboratories in 1991.
ii. Algorithm is a set of logical steps to perform a certain task.
iii. It is possible to write a Python program without a main function.
iv. print is a standard command that displays the value stored at that memory
location.
v. Function is a group of set of instructions arranged in a sequence to perform certain
tasks.
vi. Comment is information written inside the source code that is ignored by a
compiler when the source file is preprocessed.
vii. Directory is the location on a computer where files and other directories can be
stored.
viii. Python language is not a case sensitive language.
ix. Every Python program source file ends with an extension .Python
x. In Python language, it is mandatory to declare variables at the beginning of a block,
otherwise, compile time error is generated.
26 Core Python for Everyone
Answers:
Q.1 i. False ii. True iii. True iv. True v. True vi. False
vii. True viii. False ix. False x. False