INTRODUCTION TO PYTHON
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL).
Python is a language with a simple syntax, and a powerful set of libraries. It is an interpreted
language, with a rich programming environment, including a robust debugger and profiler. While
it is easy for beginners to learn, it is widely used in many scientific areas for data exploration.
The key advantages of learning Python:
Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive −We can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
1.1 Characteristics of Python
Following are important characteristics of Python Programming −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
1.2 Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Apart from the above-mentioned features, Python has good features, few are listed below −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Different Ways of Invoking Python:
Python GUI
Python command line
Command prompt from windows
Use Python Shell (using command line) and IDLE – Interactive development environment.
To evaluate expression
To create a script.
1.3 Using IDLE
IDLE is the standard Python development environment. Its name is an acronym of "Integrated
DeveLopment Environment". It works well on both Unix and Windows platforms. It has a
Python shell window, which gives you access to the Python interactive mode. It also has a file
editor that lets you create and edit existing Python source files.
1.3.1 Interactive Python shell
When you start up IDLE, a window with an interactive Python shell will pop up:
You can type Python code directly into this shell, at the '>>>' prompt. Whenever you enter a
complete code fragment, it will be executed. For instance, typing: >>> print "hello world" and
pressing ENTER, will cause the following to be displayed: hello world
IDLE can also be used as a calculator:
>>> 4+4 8
>>> 8**3 512
Addition (+), subtraction (-), multiplication (*), division (/), modulo (%) and power (**)
operators are built into the Python language. This means you can use them right away. If you
want to use a square root in your calculation, you can either raise something to the power of 0.5
or you can import the math module Below are two examples of square root calculation:
>>> 16**0.5 #4.0
>>> import math
>>> [Link](16) #4.0
The math module allows you to do a number of useful operations:
>>> [Link](16, 2) #4.0
>>> [Link]( 0 ) #1.0
Note that you only need to execute the import command once after you start IDLE; however you
will need to execute it again if you restart the shell, as restarting resets everything back to how it
was when you opened IDLE.
1.3.2 Creating scripts
1. save your [Link] program in the ~/pythonpractice folder.
2. Open up the terminal program.
3. Type cd ~/pythonpractice to change directory to your pythonpractice folder, and hit Enter.
4. Type chmod a+x [Link] to tell Linux that it is an executable program.
5. Type ./[Link] to run your program!
Program to add two integers. Take input from user.
number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")
# Using arithmetic + Operator to add two numbers
sum = float(number1) + float(number2)
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
1.4 Python Comments
Comments starts with a #,""" and Python will ignore them:
# this is a comment
print("Python Program")
1.5 Variables
Containers for storing data values. Unlike other programming languages, Python has no command for
declaring a variable.
A variable is created the moment you first assign a value to it. Variables do not need to be declared with
any particular type and can even change type after they have been set.
x=4 # x is of type int
x = "python" # x is now of type str
print(x)
1.6 Built-in Data Types
Variables can store data of different types, and different types can do different things. Python has the
following data types built-in by default, in these categories:
Text 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
We can get the data type of any object by using the type() function:
x=1 # int
y = 2.8 # float
z = 1j # complex
print(type(x)) #output 'int'
Example
integer number from an integer literal, a float literal (by rounding down to the previous whole
number), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
1.7 Python Operators
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Type Casting
From a programming point of view, a type casting refers to converting an object of one type into
another. Here, we shall learn about type casting in Python Programming.
In Python there are different data types, such as numbers, sequences, mappings etc. There may be a
situation where, you have the available data of one type but you want to use it in another form. For
example, the user has input a string but you want to use it as a number. Python's type casting
mechanism let you do that.
Example:-
print( int(1) )
print( int(12.6) )
print( int('1') )
print( int("90") )
print( int(True) )
print( int(False)
Output:
1
12
1
90
1
0
Python Comments
Python comments are programmer-readable explanation or annotations in the
Python source code. They are added with the purpose of making the source
code easier for humans to understand, and are ignored by Python interpreter.
Comments enhance the readability of the code and help the programmers to
understand the code very carefully.
Python supports three types of comments as shown below −
1. Single-line comments
2. Multi-line comments
1. Single-Line Comment:
A standalone single-line comment is a comment that occupies an entire line by itself, starting with a
hash symbol (#). It is placed above the code it describes or annotates.
# Standalone single line comment is placed here
def greet():
print("Hello, World!")
greet()
2. Multi Line Comments in Python
In Python, multi-line comments are used to provide longer explanations or notes that span
multiple lines. While Python does not have a specific syntax for multi-line comments, there are
two common ways to achieve this: consecutive single-line comments and triple-quoted strings –
We can use triple-quoted strings (''' or """) to create multi-line comments. These strings are
technically string literals but can be used as comments if they are not assigned to any variable or
used in expressions.
"""
This function calculates the greatest common divisor (GCD)
of two numbers using the Euclidean algorithm. The GCD of
two numbers is the largest number that divides both of them
without leaving a remainder.
"""
def gcd(a, b):
while b:
a, b = b, a % b
return a
result = gcd(48, 18)
print("The GCD of 48 and 18 is:", result)