Programming and Problem Solving through Python
Introduction To Python
Python is a popular programming language. It was created by Guido van Rossum,
and released in 1991.
It is used for:
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used to solve Data Science and Machine Learning related
complex mathematical and statistical problems.
Python can be used for rapid prototyping, or for production-ready software
development.
Technical Strength of Python
Some of Python’s technical strength are:
Object-Oriented: Python is an object-oriented language. Its class model
supports advanced features such as polymorphism, operator overloading, and
multiple inheritance; yet in the context of Python’s simple syntax and
typing, OOP is remarkably easy to apply.
Open Soyrce & Free: Python is free. Just like other open source software,
such as Perl, Linux, and Apache, you can get the entire Python system for free.
Portable: The standard implementation of Python runs on virtually every major
platform in use today. For example, Python programs run today on everything
from small computing devices to supercomputers. Further, Python programs
are translated to machine understandable code through an interpreter, which
runs the same on any platform with a compatible version of Python installed.
Powerful: From a features perspective, Python is something of a hybrid. Its
features places it between traditional scripting languages (such as Perl), and
systems development languages (such as C, C++, and Java). Python provides
all the simplicity and ease of use of a scripting language, along with more
advanced features typically found in compiled languages. Unlike some scripting
languages, this combination makes Python useful for large-scale development
projects. Some of the main characteristics of Python are:
Dynamic typing- Python keeps track of the kinds of objects your program
uses when it runs; it doesn’t require complicated type and size declarations
in your code. In fact, there is no type or variable declaration in Python.
Automatic memory management- Python automatically allocates and
reclaims (” garbage collects”) objects when no longer used, and most grow
and shrink on demand. Python keeps track of low-level memory details.
Programming-in-the-large support - For building larger systems, Python
includes tools such as modules, classes, and exceptions. These tools allow
you to organize systems into components, use OOP to reuse and customize
code, and handle events and errors gracefully.
Built-in object types - Python provides commonly used data structures
such as lists, dictionaries, and strings, as an intrinsic part of the language; as
we’ll see, they’re both flexible and easy to use. For instance, built-in objects
Page - 1
Programming and Problem Solving through Python
can grow and shrink on demand, can be arbitrarily nested to represent
complex information, and more.
Library utilities - For more specific tasks, Python also comes with a large
collection of pre-coded library tools that support everything from regular-
expression matching to networking. Python’s library tools are where much of
the application-level action occurs.
Third-party utilities - Because Python is freeware, it encourages
developers to contribute tools that support tasks beyond Python’s built-ins. .
Mixable: Python programs can be easily “glued” to components written in other
languages, in a variety of ways. For example, Python’s C API lets C programs
call and be called by Python programs flexibly.
Easy to Use: To run a Python program, you simply type it and run it. There are
no intermediate compile and link steps like there are for languages such as C or
C++.
Easy to Learn: Python language is remarkably easy to learn due to its simple
syntax pattern.
Python Interpreter and Program Execution
What is an interpreter?
An interpreter is a kind of program that executes a program written in high-
level language .
Working Procedure of Python Interpreter
When you write Python programs , it converts source code written by the
developer into intermediate language which is again translated into the native
language / machine language that is executed.
The python code you write is compiled into python byte code, which
creates file with extension .pyc . The byte code compilation happened
internally, and almost completely hidden from developer. Compilation is
simply a translation step, and byte code is a lower-level, and platform-
independent , representation of your source code. Roughly, each of your
source statements is translated into a group of byte code instructions.
This byte code translation is performed to speed execution byte code can
be run much quicker than the original source code statements.
The .pyc file , created in compilation step, is then executed by
appropriate virtual machines. The Virtual Machine just a big loop that
iterates through your byte code instructions, one by one, to carry out
their operations. The Virtual Machine is the runtime engine of Python and
it is always present as part of the Python system, and is the component
that truly runs the Python scripts . Technically, it’s just the last step of
what is called the Python interpreter.
Invoking the Interpreter -
o The Python interpreter is usually installed as /usr/local/bin/python3.x on
Linux platform. For those machines where it is available;
putting /usr/local/bin in your Linux shell’s search path makes it possible to
start it by typing the command to the shell.:
Page - 2
Programming and Problem Solving through Python
python3.x
o On Windows machines the installation folder where Python has been installed
should be included in the PATH system variable. The following command will
be used to run Python’s interpreter..
python
o The Python interpreter can work either in interactive mode or in scripting
mode:
Interactive Mode - When commands are read from a tty, the
interpreter is said to be in interactive mode. In this mode it prompts
for the next command with the primary prompt, usually three
greater-than signs (>>>); for continuation lines it prompts with
the secondary prompt, by default three dots (...). The interpreter
prints a welcome message stating its version number and a
copyright notice before printing the first prompt:
python
Python 3.8 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this if statement:
>>> the_world_is_flat = True
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
... Be careful not to fall off!
Typing Control-D (on Linux) or Control-Z (on Windows) at the primary
prompt causes the interpreter to exit. Alternatively exit() or quit() can be
used to exit from the interpreter.
Scripting mode - When called with a file name as argument it reads and
executes a script from that file. For example::
Python [Link]
o A second way of starting the interpreter is python -c command [arg] ...,
which executes the statement(s) in command. Since Python statements often
contain spaces or other characters that are special to the shell, it is usually
advised to quote command in its entirety with single quotes.
o Some Python modules are also useful as scripts. These can be invoked
using python -m module [arg] ..., which executes the source file
for module as if you had spelled out its full name on the command line.
Page - 3
Programming and Problem Solving through Python
Argument Passing
When known to the interpreter, the script name and additional arguments
thereafter are turned into a list of strings and assigned to the argv variable in
the sys module. You can access this list by executing import sys. The length of
the list is at least one; when no script and no arguments are
given, [Link][0] is an empty string. When the script name is given as '-
' (meaning standard input), [Link][0] is set to '-'. When -c command is
used, [Link][0] is set to '-c'. When -m module is used, [Link][0] is set to
the full name of the located module. Options found after -c command or -
m module are not consumed by the Python interpreter’s option processing but
left in [Link] for the command or module to handle.
Python Lexical structure
Programming languages, like human’s languages, have a lexical structure. A
source code of a Python program consists of tokens. Tokens are atomic code
elements. In Python language, we have comments, variables, literals, operators,
and keywords.
Python 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.
Single Line Comment: Single line comment starts with a #, and Python will
ignore the line from that position to end of line. For example:
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the
line. For example:
print("Hello, World!") #This is a comment
Multi Line Comments: Python does not really have a syntax for multi line
comments. To add a multiline comment you could insert a # for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, a multiline string can be used for multiline comment. Since Python will ignore
string literals that are not assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment inside it:
"""
This is a comment
written in more than just one line
"""
print("Hello, World!")
Page - 4
Programming and Problem Solving through Python
As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.
Python variables
A variable is an identifier which holds a value. In programming we say that we
assign a value to a variable. Technically speaking, a variable is a reference to a
computer memory, where the value is stored. In Python language, a variable can
hold a string, a number, or object of a class. Variables can be assigned different
values over time.
Rules for Variable Name in Python:
a) A variable name can be formed using alphabets, digits and the
underscore(_) character.
b) A variable name cannot begin with a digit.
c) Python keywords cannot be used as variable name.
d) The variable names are case sensitive. This means that Price, price,
and PRICE are three different identifiers.
Following are some examples of valid identifiers.
Value
value2
company_name
Following aresome examples of invalid identifiers.
12Val
exx$
first-name
total amount
Python literal
A literal is any notation for representing a value in a Python source code.
age = 29
nationality = "Indian"
Here we assign two literals to variables; number 29 and string "Indian" are literals.
Python operators
An operator is a symbol used to perform an action on some value. This is a list of
some operators available in Python language. .
+ - ~ * ** / //
% << >> & | ^
and or not in not in
is is not < > !=
== <= >=
Python keywords
A keyword is a reserved word in the Python programming language. Keywords are
used to perform a specific task in a computer program. For example, import other
code, do repetitive tasks or perform logical operations. A programmer cannot use a
keyword as an ordinary variable. This is a list of Python keywords.
and del global not with
as elif if or yield
assert else import pass False
Page - 5
Programming and Problem Solving through Python
break except in raise None
class finally is return True
continue for lambda try
def from nonlocal while
Python Datatype
Built-in Data Types
In programming, data type is an important concept. Variables can store data of
different types, and different types can do different things. Python has the following
built-in data types:
Category Python Type(s)
String Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
N.B. :- In Python, all built-in data types are objects in nature.
Getting the Data Type
You can get the data type of any object by using the type() function as shown
below:
x=5
print(type(x))
Above code will print the data type of the variable x:
Setting the Data Type
Python is loosely typed programming language. In Python, the data type is set
when you assign a value to a variable and there is no need to declare the variable.
Following examples show how to set built-in data type of a variable implicitly by
assigning value to it:
Example Data Type
x = "Hello World" str
x = 20 int
Page - 6
Programming and Problem Solving through Python
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
Setting the Specific Data Type
If you want to specify the data type explicitly, then you can use the following
constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = bool(5) bool
Python Numbers
There are three numeric types in Python:
o int
Page - 7
Programming and Problem Solving through Python
o float
o complex
Variables of numeric types are created when a value assign to them. For example:
x = 1 # int type
y = 2.8 # float type
z = 1j # complex type
Int Type:
Int, or integer, is a whole number, positive or negative, of unlimited length. For
example:
x=1
y = 35656222554887711
z = -3255522
Float Type:
Float, or "floating point number" is a number, positive or negative, containing
fractional part. For example:
x = 1.10
y = 1.0
z = -35.59
Float values can be also represented by:
x = 35e3
y = 12E4
z = -87.7e100
Complex Type:
Complex numbers are those numbers which have real part and imaginary part.
They are written with a "j" as the imaginary part. For example:
x = 3+5j
y = 5j
z = -5j
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods. For exampleL
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
Page - 8
Programming and Problem Solving through Python
print(type(a))
print(type(b))
print(type(c))
N.B.: You cannot convert complex numbers into another number type.
Console Input / Output Operations in Python
The print Function:
In Python print() function is used to provide output on console. Use of parenthesis
() with print function is mandatory in Python 3.x, although in Python 2.x
parenthesis () was optional. For example, to display a message in Python following
print() function can be use:
print ("Hello World")
The print() function inserts a new line at the end, by default. In Python, ' end=" " '
appends space instead of newline. For example:
x=10
y=20
print(x, end=" ")
print(y)
in print function multiple values can be displayed by putting ',' as value separator
between them. For example:
x=10
y=20
print(x,y) # Displays 10 20
print(Sum=",x+y) # Displays Sum= 30
Python also supports formatted output. The print() can be used to provide
formatted output. For example:
x=10
y=20
z=x+y
print(f"Sum of {x} and {y} is {z}") # Displays Sum of 10 and 20 is 30
print("Sum of {0} and {1} is {2}".format(x,y,z)) Displays Sum of 10 and 20 is 30
Reading Input From Keyboard
Python has input() function to read data from keyboard. The data read by the
input() function is always treated as string. For example, to read a string value
from keyboard following statement can be use:
>>> name=input("What is your name? ")
What is your name? Joy
>>> print(name)
Page - 9
Programming and Problem Solving through Python
Joy
In Python, a numeric value read by input() function is also treated as string. For
example:
>>> x=input("Enter an integer:")
Enter an integer:15
>>> print(type(x))
<class 'str'>
But, using following way data of other types can be read through input() function:
>>> x=int(input("Enter an integer:"))
Enter an integer:19
>>> print(type(x))
<class 'int'>
>>> y=float(input("Enter an number:"))
Enter an integer:3.14
>>> print(type(y))
<class 'float'>
Page - 10