Introduction to Python Programming Basics
Introduction to Python Programming Basics
INTRODUTION TO PYTHON
Introduction: Features of Python, History of Python, installing Python; basic syntax, interactive
shell, editing, saving, and running a script. Statements and Expressions, Variables, Operators,
Precedence and Associativity, Data Types (Numbers, Booleans, Strings, None), Indentation and
comments, Type Conversions, type() Function, membership operator
Introduction:
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-
collected, and purely object-oriented programming language that supports procedural, object-
oriented, and functional programming.
It was created by Guido van Rossum, and released in 1991 at National Research Institute for
Mathematics and Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol-68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Python provides number of libraries and frameworks. Python has gained popularity because of its
simplicity, easy syntax and user-friendly environment. The usage of Python as follows.
o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing
Characteristics of Python:
Interpreted: Python source code is compiled to byte code as a .pyc file, and this byte code can
be interpreted by the interpreter.
Interactive
Object Oriented Programming Language
Easy & Simple
Portable
Scalable: Provides improved structure for supporting large programs.
Integrated
Expressive Language
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential features.
1) Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is straightforward
and much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java or
C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
So, we can say that Python is a portable language. It enables programmers to develop the software for
several competing platforms by writing a program only once.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official website [Link].
It has a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source means,
"Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used
further in our Python code. It converts the program into byte code, and any platform can use that byte
code.
8) Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web developer,
and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web
development.
9) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are
the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line
like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use Python
source code in another programming language as well. It can embed other language into our code.
12. Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned
integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
Python Install
To check if we have python installed on a Windows PC, search in the start bar for Python or run the
following on the Command Line ([Link]):
C:\Users\Your Name>python –version
To check if we have python installed on a Linux or Mac, then on linux open the command line or on
Mac open the Terminal and type:
python –version
If we find that we do not have Python installed on your computer, then we can download it for free
from the following website: [Link]
Python Interpreter:
Names of some Python interpreters are:
PyCharm
Python IDLE
The Python Bundle
pyGUI
Sublime Text etc.
i. Interactive Mode: Without passing python script file to the interpreter, directlyexecute code to
Python (Command line).
Example:
>>>6+3
Output: 9
ii. Script Mode: In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, we have to tell
the interpreter the name of the file.
Example: if we have a file name [Link] , to run the script we have to follow the following
steps:
Step-1: Open the text editor i.e. Notepad
Step-2: Write the python code and save the file with .py file extension. (Default directory is
C:\Python33/[Link])
Step-3: Open Integrated Development and Learning Environment (IDLE Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window.
TOKENS
Token: Smallest individual unit in a program is known as token. There are five types of token in
python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators
1. Keyword: Reserved words in the library of a language. There are 35 keywords inpython.
All the keywords are in lowercase except 03 keywords (True, False, None).
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print([Link])
Output:
The list of keywords are:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
2. Identifier: The name given by the user to the entities like variable name, class-name,function-
name etc.
Rules for identifiers:
It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) ordigits (0 to 9) or an
underscore.
It cannot start with a digit.
Keywords cannot be used as an identifier.
We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
_ (underscore) can be used in identifier.
Commas or blank spaces are not allowed within an identifier.
3. Literal: Literals are the constant value. Literals can be defined as a data that is given ina variable or
constant.
Literal
String Literal
Numeric Boolean Special
Collectio ns
B. Boolean literal: A Boolean literal can have any of the two values: True or False.
C. Special literals: Python contains one special literal i.e. None.
None is used to specify to that field that is not created. It is also used for end of lists inPython.
D. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
4. Operators: An operator performs the operation on operands. Basically there are two types of
operators in python according to number of operands:
A. Unary Operator: Performs the operation on one operand.
Example:
+ Unary plus
- Unary minus
~ Bitwise complementnot Logical negation
B. Binary Operator: Performs operation on two operands.
5. Separator or punctuator : , ; , ( ), { }, [ ]
B. Statements
C. Expressions:
D. Comments: Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the physical line are part
of the comment and the Python interpreter ignores them.
ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple quoted
„ ‟ ‟ or “ ” ”) multi-line comments may be used in python. It is also known as docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Definition: Named location that refers to a value and whose value can be used and processed during
program execution.
Variables in python do not have fixed locations. The location they refer to changes every time their
values change.
Creating a variable:
A variable is created the moment we first assign a value to [Link]:
x=5
y = “hello”
Variables do not need to be declared with any particular type and can even change type after they
have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print (x)
Note: Expressions separated with commas are evaluated from left to right and assigned in sameorder.
If we want to know the memory address or location of the object, we can use id( ) function.
Example:
>>>id(5) 1561184448
>>>b=5
>>>id(b) 1561184448
We can delete single or multiple variables by using del statement.
Example:del x
del y, z
Input from a user:
input( ) method is used to take input from the user.
Example:
print("Enter your name:")
x = input( )
print("Hello, " + x)
Type Casting:
To convert one data type into another data type.
Casting in python is therefore done using constructor functions:
int( ) - constructs an integer number from an integer literal, a float literal or a stringliteral.
Example:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
complex() - constructs a complex numbers are written with a "j" as the imaginary part:
x = 3+5j # x will be (3+5j)
y = 5j # y will be 5j
z = -5j #z will be (-0-5j)
a = 1 # int
b = complex(a) #b will be (1+0j)
str( ) - constructs a string from a wide variety of data types, including strings, integer literals and
float literals.
Example:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Syntax:
print(object, sep=<separator string >, end=<end-string>)
sep : sep argument specifies the separator character or string. It separate the objects/items. By default
sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it has
newline character( „\n‟ ).
Example:
x=10 y=20 z=30
print(x,y,z, sep=‟@‟, end= „ „)
Output:
10@20@30
Data Types in Python:
Python has Two data types:
Boolean: It has two values: True and False. True has the value 1 and False has thevalue 0.
Example:
>>>bool(0)
False
>>>bool(1)
True
>>>bool(„ „)
False
>>>bool(-34)
True
>>>bool(34)
True
float : float or "floating point number" is a number, positive or negative, containing one or more
decimals. Float can also be scientific numbers with an "e" to indicate the powerof 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3b = 12E4
c = -87.7e100
complex : Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z) 5+9j
>>>[Link] 5.0
>>>[Link] 9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example: print(10 + 5)
Operator Precedence
Operator precedence describes the order in which operations are performed.
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:
print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated
before additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest precedence at the top:
Operator Description
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary minus, and bitwise NOT
* / // % Multiplication, division, floor division, and
modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not in Comparisons, identity, and membership
operators
not Logical NOT
and AND
or OR
= Assignment
If two operators have the same precedence, the expression is evaluated from left to right.
Mutability in Python
As we have already told, an immutable Python object cannot be altered.
In Python, the integer data type is a prime case of an immutable object or data type. Let's conduct an
easy experiment to understand this.
Let's first make two integer variables, x and y. The variable y is a reference to the variable x:
Now, x and y both point towards the same location in memory. In other words, both integer variables
should have the same ID returned by the id() function. Let's confirm that this is true:
Code
1. # Python program to create two variables having the same memory reference
2.
3. # Initializing a variable
4. x=3
5.
6. # Storing it in another variable
7. y=x
8.
9. # Checking if two have the same id reference
10. print("x and y have same id: ", id(x) == id(y))
Output:
x and y have same id: True
As a result, the variables x and y points to a single integer object. In other words, even though there is
just one integer variable, two variables refer to it.
Let us change x's value now. Next, let's compare the reference ids of x and y once more:
Code
1. # Python program to check if x and y have the same ids after changing the value
2.
3. x=3
4. y=x
5.
6. # Changing the value of x
7. x = 13
8.
9. # Checking if x and y still point to the same memory location
10. print("x and y have the same ids: ", id(x) == id(y))
Output:
x and y have the same ids: False
This is because x now points to a distinct integer object. Therefore, the integer variable 3 itself
remained constant. However, the variable x that previously referred to it now directs users to the new
integer entity 13.
Therefore, even though it appears like we modified the original integer variable, we didn't. In Python,
the integer object is an immutable data type, meaning that an integer object cannot be changed once
created.
List
As a result of their mutable nature, lists can change their contents by incorporating the assignment
operators or the indexing operators.
Code
1. # Python program to show that a list is a mutable data type
2.
3. # Creating a list
4. list1 = ['Python', 'Java', 23, False, 5.3]
5. print("The original list: ", list1)
6.
7. # Changing the value at index 2 of the list
8. list1[2]='changed'
9. print("The modified list: ", list1)
Output:
The original list: ['Python', 'Java', 23, False, 5.3]
The modified list: ['Python', 'Java', 'changed', False, 5.3]
Dictionary
Due to the mutability of dictionaries, we can modify them by implementing a built-in function update
or using keys as an index.
Let's look at an illustration of that.
Code
1. # Python program to show that a dictionary is a mutable data type
2.
3. # Creating a dictionary
4. dict_ = {1: "a", 2: "b", 3: "c"}
5. print("The original dictionary: ", dict_)
6.
7. # Changing the value of one of the keys of the dictionary
8. dict_[2]= 'changed'
9. print("The modified dictionary: ", dict_)
Output:
The original dictionary: {1: 'a', 2: 'b', 3: 'c'}
The modified dictionary: {1: 'a', 2: 'changed', 3: 'c'}
Set
Due to the mutability of sets, we can modify them using a built-in function (update).
See an illustration of that:
Code
1. # Python program to show that a set is a mutable data type
2.
3. # Creating a set
4. set_ = {1, 2, 3, 4}
5. print("The original set: ", set_)
6.
7. # Updating the set using the update function
8. update_set = {'a', 'b', 'c'}
9. set_.update(update_set)
10. print("The modified set: ", set_)
Output:
The original set: {1, 2, 3, 4}
The modified set: {1, 2, 3, 4, 'b', 'a', 'c'}
int
Since int in Python is an immutable data type, we cannot change or update it.
As we previously learned, immutable objects shift their memory address whenever they are updated.
Code
1. # Python program to show that int is an immutable data type
2.
3. int_ = 25
4. print('The memory address of int before updating: ', id(int_))
5.
6. # Modifying an int object by giving a new value to it
7. int_ = 35
8. print('The memory address of int after updating: ', id(int_))
Output:
The memory address of int before updating: 11531680
The memory address of int after updating: 11532000
float
Since the float object in Python is an immutable data type, we cannot alter or update it. As we
previously learned, immutable objects shift their memory address whenever they are updated.
Here is an illustration of that:
Code
1. # Python program to show that float is an immutable data type
2.
3. float_ = float(34.5)
4. print('The memory address of float before updating: ', id(float_))
5.
6. # Modifying the float object by giving a new value to it
7. float_ = float(32.5)
8. print('The memory address of float after updating: ', id(float_))
Output:
The memory address of float before updating: 139992739659504
The memory address of float after updating: 139992740128048
String
Since strings in Python are immutable data structures, we cannot add or edit any data. We
encountered warnings stating that strings are not changeable when modifying any section of the
string.
Here is an illustration of that:
Code
1. # Python program to show that a string is an immutable data type
2.
3. # Creating a string object
4. string = 'hello peeps'
5.
6. # Trying to modify the string object
7. string[0] = 'X'
8. print(string)
Output:
TypeError Traceback (most recent call last)
<ipython-input-3-4e0fff91061f> in <module>
3 string = 'hello peeps'
4
----> 5 string[0] = 'X'
6
7 print(string)
Tuple
Because tuples in Python are immutable by nature, we are unable to add or modify any of their
contents. Here is an illustration of that:
Code
1. # Python program to show that a tuple is an immutable data type
2.
3. # Creating a tuple object
4. tuple_ = (2, 3, 4, 5)
5.
6. # Trying to modify the tuple object
7. tuple_[0] = 'X'
8. print(tulple_)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-e011ebc4971e> in <module>
5
6 # Trying to modify the tuple object
----> 7 tuple_[0] = 'X'
8 print(tulple_)
9
FrozenSet
Like sets, frozensets are immutable data structures. While the set's components can always be
changed, this cannot be done with a frozenset. Therefore, nothing can be added to or updated in the
frozenSet.
Here is an illustration of that:
Code
1. # Python program to show that a frozenset is an immutable data type
2.
3. # Creating a frozenset object
4. t = (2, 4, 5, 7, 8, 9, 5, 9, 6, 11, 12)
5. fset = frozenset(t)
6.
7. # Updating the value of the frozenset
8. fset[1] = 76
9. print(fset)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-2cafcda94faf> in <module>
6
7 # Updating the value of the frozenset
----> 8 fset[1] = 76
9 print(fset)
10
Integer Formatting
Example
>>>print(format(20,”10x”)) #Integer formatted to Hexadecimal Integer
14
>>> print(format(20,”<10x”))
14
>>> print(format(1234,”10d”)) #Right Justification
1234
Formatting String
A programmer can make use of conversion code s to format a string with a specifi ed width. However, by
default, string is left justifi ed. Following are some examples of string formatting.
Example
>>> print(format(“Hello World!”,”25s”) #Left Justification
Example
Hello World!
>>>print(format(“HELLO WORLD!”,”>20s”)) #String Right Justification
HELLO WORLD