0% found this document useful (0 votes)
1 views45 pages

Python Unit I Notes-1

The document provides an overview of Python programming, including its history, features, and usage in various applications. It details the language's syntax, data types, operators, and key concepts such as identifiers, keywords, and literals. Additionally, it highlights Python's popularity among tech companies and its evolution over the years, including version updates and the inspiration behind its name.

Uploaded by

shiva.yuva2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views45 pages

Python Unit I Notes-1

The document provides an overview of Python programming, including its history, features, and usage in various applications. It details the language's syntax, data types, operators, and key concepts such as identifiers, keywords, and literals. Additionally, it highlights Python's popularity among tech companies and its evolution over the years, including version updates and the inspiration behind its name.

Uploaded by

shiva.yuva2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMING

Unit I

Basics of Python Programming:History of Python-Features of Python-Literal-Constants-


Variables - Identifiers–Keywords-Built-in Data Types-Output Statements – Input
Statements-Comments – Indentation- Operators-Expressions-Type
conversions.PythonArrays: Defining and Processing Arrays – Array methods.

What is Python?

Python is a high-level, general-purpose, and very popular programming language. Python programming
language is being used in web development, Machine Learning applications, along with all cutting-edge
technology in Software Industry.

Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook,
Instagram, Dropbox, Uber… etc.

The biggest strength of Python is huge collection of standard library which can be used for the following:

 Machine Learning
 GUI Applications (like Kivy, Tkinter, PyQt etc. )
 Web frameworks like Django (used by YouTube, Instagram, Dropbox)
 Image processing (like OpenCV, Pillow)
 Web scraping (like Scrapy, BeautifulSoup, Selenium)
 Test frameworks
 Multimedia
 Scientific computing
 Text processing and many more..

History of python:

Python is a widely-used general-purpose, high-level programming language. It was initially designed by


Guido van Rossum in 1991 and developed by Python Software Foundation.

It was mainly developed for emphasis on code readability, and its syntax allows programmers to express
concepts in fewer lines of code.

In the late 1980s, history was about to be written. It was that time when working on Python started. Soon
after that, Guido Van Rossum began doing its application-based work in December of 1989 at Centrum
Wiskunde & Informatica (CWI) which is situated in the Netherlands.

The programming language in which Python is said to have succeeded is ABC Programming Language,
which had interfacing with the Amoeba Operating System and had the feature of exception handling.

He had already helped to create ABC earlier in his career and he had seen some issues with ABC but
liked most of the features.

He had taken the syntax of ABC, and some of its good features.

1
The inspiration for the name came from BBC’s TV Show – ‘Monty Python’s Flying Circus’, as he was a
big fan of the TV show and also he wanted a short, unique and slightly mysterious name for his invention
and hence he named it Python!

He was the “Benevolent dictator for life” (BDFL) until he stepped down from the position as the leader
on 12th July 2018.

For quite some time he used to work for Google, but currently, he is working at Dropbox.
The language was finally released in 1991.

When it was released, it used a lot fewer codes to express the concepts, when we compare it with Java,
C++ & C.

Its design philosophy was quite good too. Its main objective is to provide code readability and advanced
developer productivity.

When it was released it had more than enough capability to provide classes with inheritance, several core
data types exception handling and functions.

Python 3.10.4 is the latest stable version.

The two of the most used versions has to Python 2.x & 3.x. There is a lot of competition between the two
and both of them seem to have quite a number of different fanbases.

For various purposes such as developing, scripting, generation, and software testing, this language is
utilized. Due to its elegance and simplicity, top technology organizations like Dropbox, Google, Quora,
Mozilla, Hewlett-Packard, Qualcomm, IBM, and Cisco have implemented Python.

Python has come a long way to become the most popular coding language in the world. Python has just
turned 30 and just recently at pycon22(python conference) a new feature was released by Anaconda
foundation it’s known as pyscript with this now python can be written and run in the browser like
javascript which was previously not possible, but it still has that unknown charm & X factor which can be
clearly seen from the fact that Google users have consistently searched for

Python much more than they have searched for Kim Kardashian, Donald Trump, Tom Cruise, etc.

Python has been an inspiration for many other coding languages such as Ruby, Cobra, Boo, CoffeeScript
ECMAScript, Groovy, Swift Go, OCaml, Julia, etc.

Why the Name Python?

There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a popular
BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying Circus" for their newly created programming
language.

2
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

Python is also versatile and widely used in every technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.

Python Version List

Python programming language is being updated regularly with new features and supports. There are lots
of update in Python versions, started from 1994 to current release.

A list of Python versions with its released date is given below.

Python Version Released Date


Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
Python 2.5 September 19, 2006
Python 2.6 October 1, 2008
Python 2.7 July 3, 2010
Python 3.0 December 3, 2008
Python 3.1 June 27, 2009
Python 3.2 February 20, 2011
Python 3.3 September 29, 2012
Python 3.4 March 16, 2014
Python 3.5 September 13, 2015
Python 3.6 December 23, 2016
Python 3.7 June 27, 2018
Python 3.8 October 14, 2019

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.

3
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.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official website www.python.org. 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.

4
11. Embeddable

The code of the other programming language can use in the Python source 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 Tokens
Tokens are the smallest units of code that have a specific purpose or meaning. Each token, like a
keyword, variable name, or number, has a role in telling the computer what to do.

1. Identifiers in Python

Identifiers is a user-defined name given to identify variables, functions, classes, modules, or any other
user-defined object in Python. They are case-sensitive and can consist of letters, digits, and underscores.
Yet, they cannot start with a digit.

Examples of valid Python identifiers:


 my_variable
 my_function()

Examples of invalid Python identifiers:

5
 1my_variable (starts with a number)
 my-variable (contains a special character)
 def (keyword)
2. Keywords in Python

Keywords are reserved words in Python that have a special meaning and are used to define the syntax and
structure of the language. These words cannot be used as identifiers for variables, functions, or other
objects. Python has a set of 35 keywords, each serving a specific purpose in the language.
There are 35 keywords in Python 3.11. They are:

and as assert async continue

else if not while def

except import or with del

finally in pass yield elif

for is raise await false

from lambda return break none

global nonlocal try class true

3. Literals in Python
Literals are constant values that are directly specified in the source code of a program. They represent
fixed values that do not change during the execution of the program. Python supports various types of
literals, including string literals, numeric literals, boolean literals, and special literals such as None.

Numeric literals can be integers, floats, or complex numbers. Integers are whole numbers without a
fractional part, while floats are numbers with a decimal point. Complex numbers consist of a real part and
an imaginary part, represented as “x + yj“, where “x” is the real part and “y” is the imaginary part.

6
String literals are sequences of characters enclosed in single quotes (”) or double quotes (“”). They can
contain any printable characters, including letters, numbers, and special characters. Python also supports
triple-quoted strings, which can span multiple lines and are often used for docstrings, multi-line
comments, or multi-line strings

Boolean literals represent the truth values “True” and “False“. They are used in logical expressions and
control flow statements to make decisions based on certain conditions. Boolean literals are often the result
of comparison or logical operations.
Special literals include None, which represents the absence of a value or the null value. It is often used to
indicate that a variable has not been assigned a value yet or that a function does not return anything.

4. Operations in Python

Operators are symbols or special characters to carry out tasks on one or more operands. These include
arithmetic operators, assignments operator, comparison operators, logical operators, identity operators,
membership operators, and even those for handling bits.

Type of Operator Description Example

Arithmetic Perform mathematical operations such as addition, subtraction, +, -, *, /, %, **


Operators multiplication, division, modulus, and exponentiation.

Assignment Assign values to variables, including the equal sign and compound =, +=, -=,
Operators assignment operators. *=, /=, %=

Comparison Compare two values and return a boolean (True or False) based on the ==, !=, >, <,
Operators comparison. >=, <=

Logical Operators Combine conditions and perform logical operations like AND, OR, and and, or, not
NOT.

Identity Operators Compare the memory addresses of objects to check if they are the same is, is not
or different.

Membership Test if a value is present in a sequence (e.g., list, tuple, string). in, not in
Operators

7
Bitwise Operators Perform bit-level operations on binary numbers, allowing manipulation &
of individual bits.

5. Delimiters in Python

Delimiters are characters or symbols used to separate or mark the boundaries of different elements in
Python code. They are used to group statements, define function or class bodies, enclose string literals,
and more. Python uses various delimiters, including parentheses ‘()’, commas ‘,’, brackets ‘[]’, braces
‘{}’, colons ‘:’, and semicolons.

Punctuation Usage
Mark

Parentheses Define function arguments, control the order of operations, and create tuples.

Brackets Create lists, which are mutable sequences of values.

Braces Define sets (unordered collections of unique elements) and dictionaries (key-value pairs).

Commas Separate elements in tuples, lists, sets, and dictionaries. It is also used to separate function
arguments and create multiple variable assignments.

Colons Define the body of control flow statements like if, else, for, while, and def.

Semicolons Separate multiple statements on a single line for brevity or to combine related statements.

6. Whitespace and Indentation in Python

Whitespace and indentation play an important role in Python’s syntax and structure. Python uses
indentation to define blocks of code and determine the scope of statements. The use of consistent
indentation is not only a matter of style but is required for the code to be valid and executable.

Concept Description

Standard In Python, the standard indentation is four spaces.


Indentation

8
Indentation Indentation can be done using spaces or tabs, but it’s recommended to use spaces for
Methods better compatibility and readability. Mixing tabs and spaces can lead to syntax errors.

Indentation in Indentation is used to define the body of control flow statements like if, else, for, while,
Control Flow and def. The indented block of code following a colon (:) is executed when the control
flow condition is met. The indentation level must be the same for all statements within
the same block.

Whitespace Whitespace, including spaces, tabs, and newlines, is used to separate tokens and enhance
and Readability code readability. Excessive whitespace should be avoided, as it can hinder code
comprehension. Python ignores whitespace within parentheses, brackets, and braces,
allowing code formatting for improved readability.

Python Literals

Python Literals can be defined as data that is given in a variable or constant.

Python supports the following literals:

1. String literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as well as double
quotes to create a string.

Example: "Aman" , '12345'

Types of Strings:

There are two types of Strings supported in Python:

a) Single-line String- Strings that are terminated within a single-line are known as Single line Strings.

Example:

1. text1='hello'

b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines string.

There are two ways to create multiline strings:

1) Adding black slash at the end of each line.

9
Example:

1. text1='hello\
2. user'
3. print(text1)

'hellouser'

2) Using triple quotation marks:-

Example:

1. str2='''''welcome
2. to
3. SSSIT'''
4. print str2

Output:

welcome
to
SSSIT

II. Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)

Numbers( can be both Integers of unlimited Real numbers with In the form of a+bj where a forms
positive and negative) size followed by both integer and the real part and b forms the
with no fractional lowercase or uppercase fractional part eg: - imaginary part of the complex
part.eg: 100 L eg: 87032845L 26.2 number. eg: 3.14j

Example - Numeric Literals

1. x = 0b10100 #Binary Literals


2. y = 100 #Decimal Literal
3. z = 0o215 #Octal Literal
4. u = 0x12d #Hexadecimal Literal
5.
6. #Float Literal
7. float_1 = 100.5
8. float_2 = 1.5e2
9.
10. #Complex Literal
11. a = 5+3.14j
12.

10
13. print(x, y, z, u)
14. print(float_1, float_2)
15. print(a, a.imag, a.real)

Output:

20 100 141 301


100.5 150.0
(5+3.14j) 3.14 5.0

III. Boolean literals:

A Boolean literal can have any of the two values: True or False.

Example - Boolean Literals

1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
10. print("a:", a)
11. print("b:", b)

Output:

x is True
y is False
z is False
a: 11
b: 10

IV. 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 the end of lists in Python.

Example - Special Literals

1. val1=10
2. val2=None
3. print(val1)
4. print(val2)

Output:

11
10
None

V. Literal Collections.

Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals, and
Set literals.

List:

 List contains items of different data types. Lists are mutable i.e., modifiable.
 The values stored in List are separated by comma(,) and enclosed within square brackets([]). We
can store different types of data in a List.

Example - List literals

1. list=['John',678,20.4,'Peter']
2. list1=[456,'Andrew']
3. print(list)
4. print(list + list1)

Output:

['John', 678, 20.4, 'Peter']


['John', 678, 20.4, 'Peter', 456, 'Andrew']

Dictionary:

 Python dictionary stores the data in the key-value pair.


 It is enclosed by curly-braces {} and each pair is separated by the commas(,).

Example

1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}


2. print(dict)

Output:

{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}

Tuple:

 Python tuple is a collection of different data-type. It is immutable which means it cannot be


modified after creation.
 It is enclosed by the parentheses () and each element is separated by the comma(,).

Example

1. tup = (10,20,"Dev",[2,3,4])

12
2. print(tup)

Output:

(10, 20, 'Dev', [2, 3, 4])

Set:

 Python set is the collection of the unordered dataset.


 It is enclosed by the {} and each element is separated by the comma(,).

Example: - Set Literals

1. set = {'apple','grapes','guava','papaya'}
2. print(set)

Output:

{'guava', 'apple', 'papaya', 'grapes'}

Taking input in Python

Developers often have a need to interact with users, either to get data or to provide some sort of result.
Python provides two inbuilt functions to read the input from the keyboard.

 input ( prompt )
 raw_input ( prompt )

input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <class ‘str’>. It does not evaluate the expression it just returns the complete
statement as String. For example, Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for the user’s input. When
the user presses enter, the program resumes and returns what the user typed.

Syntax:

inp = input('STATEMENT')

Example:
1. >>> name = input('What is your name?\n'
2. >>> What is your name?
Ram
>>> print(name)
Ram

13
Output:

What is your name?


Ram
Ram

# Program to check input


# type in Python

num = input ("Enter number :")


print(num)
name1 = input("Enter name : ")
print(name1)

# Printing type of input value


print ("type of number", type(num))
print ("type of name", type(name1))

Output:

Output:

Taking input from console in Python


What is Console in Python? Console (also called Shell) is basically a command line interpreter that
takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the
command and gives required output otherwise shows the error message. A Python Console looks like this.

The primary prompt of the python console is the three greater than symbols

>>>

14
Accepting Input from Console User enters the values in the Console and that value is then used in the
program as it was required. To take input from the user we make use of a built-in function input().

# input
input1 = input()

# output
print(input1)

We can also typecast this input to integer, float, or string by specifying the input() function inside the
type.

1. Typecasting the input to Integer: There might be conditions when you might require integer input
from the user/Console, the following code takes two input(integer/float) from the console and typecasts
them to an integer then prints the sum.

# input
num1 = int(input())
num2 = int(input())

# printing the sum in integer


print(num1 + num2)

2. Typecasting the input to Float: To convert the input to float the following code will work out.

# input
num1 = float(input())
num2 = float(input())

# printing the sum in float


print(num1 + num2)

3. Typecasting the input to String: All kinds of input can be converted to string type whether they are
float or integer. We make use of keyword str for typecasting.

we can also take input string by just writing input() function by default it makes the input string

# input
string = str(input())

# output
print(string)

# Or by default
string_default = input()

# output
print(string_default)

15
Python | Output using print() function

Python print() function prints the message to the screen or any other standard output device.

Example

In this example, we have created three variables integer, string and float and we are printing all the
variables with print() function in Python.

name = "John"
age = 30

print("Name:", name)
print("Age:", age)

Python print() Function Syntax

Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters:

 value(s): Any value, and as many as you like.


 sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘

 end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’

 file : (Optional) An object with a write method. Default :sys.stdout

 flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered


(False). Default: False

Return Type: It returns output to the screen.

In this code, we are passing two parameters name and age to the print function.

name = "Alice"
age = 25

print("Hello, my name is", name, "and I am", age, "years


old.")

Python print() Function with Examples

Python String Literals

String literals in Python’s print statement are primarily used to format or design how a specific string
appears when printed using the print() function.

16
 \n: This string literal is used to add a new blank line while printing a statement.

 “”: An empty quote (“”) is used to print an empty line.

Example

This code uses \n to print the data to the new line.

print("GeeksforGeeks \n is best for DSA


Content.")

Output

GeeksforGeeks
is best for DSA Content.

Python “end” parameter in print()

The end keyword is used to specify the content that is to be printed at the end of the execution of the
print() function. By default, it is set to “\n”, which leads to the change of line after the execution of print()
statement.

Example

In this example, we are using print() with end and without end parameters.

# This line will automatically add a new line before the

# next print statement

print ("GeeksForGeeks is the best platform for DSA content")

# This print() function ends with "**" as set in the end argument.

print ("GeeksForGeeks is the best platform for DSA content", end=


"**")

print("Welcome to GFG")

Output

GeeksForGeeks is the best platform for DSA content


GeeksForGeeks is the best platform for DSA content**Welcome to GFG

Python Constants

17
 A Python Constant is a variable whose value cannot be changed throughout the program.

Such types of values are called as Constants.

Rules to be followed while declaring a Constant

1. Python Constants and variable names should contain a combination of lowercase (a-z) or capital
(A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when declaring
a constant.
5. We should come up with a catchy name for the python constants. VALUE, for example, makes
more sense than V. It simplifies the coding process.

Assigning Values to Constants

Constants are typically declared and assigned in a module in Python

Example

Copy Code

# create a separate constant.py file


PI = 3.14
GRAVITY = 9.8

Copy Code

# main.py file
import constant as const

print('Value of PI:', cons.PI)


print('Value of Gravitational force:', cons.GRAVITY)

Output

Value of PI: 3.14


Value of Gravitational force: 9.8

Python Variables

18
 A Variable is a location that is named in order to store data while the program is being run.
 In a programming language, Variables are words that are used to store values of any data type.

Syntax

variable_name = data values

where, variable_name = combination of letters, numbers and an underscore

Rules to be followed while declaring a Variable name

1. A Variable’s name cannot begin with a number. Either an alphabet or the underscore character
should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well as the underscore
character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables in Python.

Assigning values to Variables in Python

There are few different methods to assign data elements to a Variable. The most common ones are
described below –

1. Simple declaration and assignment of a value to the Variable

In this type, the data values are directly assigned to the Variables in the declaration statement.

Example

Copy Code

num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'

print(num)
print(numlist)
print(str)

Output

10
[1, 3, 5, 7, 9]
Hello World

19
2. Changing the value of a Variable

Data values assigned to the variables can be changed at any time.

Example

val = 50
print("Initial value:", val)

val = 100 # assigning new value


print("Updated value:", val)

Output

Initial value: 50
Updated value: 100

In the above program, initially the value of Variable ‘val’ was 50. Later it was reassigned to a value of
100.

3. Assign multiple values to multiple Variables

In Python, we can assign multiple values to multiple variables in the same declaration statement by using
the following method –

Example

Copy Code

name, age, city = 'David', 27, 'New York'

print(name)
print(age)
print(city)

Output

20
David
27
New York

Example

Copy Code

a = b = 'Hello'

print('Value of a:', a)
print('Value of b:', b)

Output –

Value of a: Hello
Value of b: Hello

Python Keywords and Identifiers

Python Keywords

Keywords are predefined, reserved words used in Python programming that have special meanings to the
compiler.

We cannot use a keyword as a variable name, function name, or any other identifier. They are used to
define the syntax and structure of the Python language.

All the keywords except True, False and None are in lowercase and they must be written as they are. The
list of all the keywords is given below.

Python Keywords List

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

21
as def from nonlocal while

assert del global not with

async elif if or yield

Python Identifiers

Identifiers are the name given to variables, classes, methods, etc. For example,

language = 'Python'

Here, language is a variable (an identifier) which holds the value 'Python'.

We cannot use keywords as variable names as they are reserved names that are built-in to Python. For
example,

continue = 'Python'

Rules for Naming an Identifier

 Identifiers cannot be a keyword.


 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter or _. The first
letter of an identifier cannot be a digit.
 It's a convention to start an identifier with a letter rather _.
 Whitespaces are not allowed.
 We cannot use special symbols like !, @, #, $, and so on.

Some Valid and Invalid Identifiers in Python


Valid Identifiers Invalid Identifiers

score @core

return_value return

highest_score highest score

name1 1name

convert_to_string convert to_string

Things to Remember

22
Python is a case-sensitive language. This means, Variable and variable are

not the same.

Python Data Types

Every value has a datatype, and variables can hold values.

Consider the following illustration when defining and verifying the values of various data types.

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types

A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer,
while their name must be stored as a string.

The storage method for each of the standard data types that Python provides is specified by Python. The
following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

23
Numbers

Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with
a Python Numbers datatype.

When a number is assigned to a variable, Python generates Number objects. For instance,

1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three kinds of numerical data.

24
 Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An
integer can be any length you want in Python. Its worth has a place with int.
 Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15
decimal places.
 Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the
genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

String

The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.

Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

List

Lists in Python can contain data of different types.

It is written inside [ ], and elements inside the list are separated by comma.

It is mutable.(can able to change the value after it is assigned)

Example:

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.

25
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple

In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data
types. A parenthetical space () separates the tuple's components from one another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure(immutable).

Example:

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)

26
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary

A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an
associative array or a hash table. Value is any Python object, while the key can hold any primitive data
type.

The comma (,) and the curly braces are used to separate the items in the dictionary.

Look at the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

True and False are the two default values for the Boolean type.

Ex:

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

Output:

27
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set

The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and
has remarkable components. The elements of a set have no set order; It might return the element's altered
sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to
create the set or the built-in function set() is used to create the set. It can contain different kinds of values.

Ex:

1. # Creating Empty set


2. set1 = set()
3. set2 = {'James', 2, 3,'Python'}
4. #Printing Set value
5. print(set2)
6. # Adding element to the set
7. set2.add(10)
8. print(set2)
9. #Removing element from the set
10. set2.remove(2)
11. print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Python Operators

Operators are special symbols that perform operations on variables and values. For example,

print(5 + 6) # 11

Here, + is an operator that adds two numbers: 5 and 6.

Types of Python Operators

1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators

28
6. Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc. For example,

sub = 10 - 5 # 5

Here, - is an arithmetic operator that subtracts two values or variables.

Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2 * 3 = 6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16

Example 1: Arithmetic Operators in Python


a=7
b=2

# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# floor division
print ('Floor Division: ', a // b)

29
# modulo
print ('Modulo: ', a % b)

# a to the power b
print ('Power: ', a ** b)

Output

Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49

In the above example, we have used multiple arithmetic operators,

 + to add a and b
 - to subtract b from a
 * to multiply a and b
 / to divide a by b
 // to floor divide a by b
 % to get the remainder
 ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

# assign 5 to x
var x = 5

Here, = is an assignment operator that assigns 5 to x.

Here's a list of different assignment operators available in Python.

Operator Name Example

= Assignment Operator a=7

+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

*= Multiplication Assignment a *= 4 # a = a * 4

30
/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10

Example 2: Assignment Operators


# assign 10 to a
a = 10

# assign 5 to b
b=5

# assign the sum of a and b to a


a += b #a=a+b

print(a)

# Output: 15

Here, we have used the += operator to assign the sum of a and b to a.

Similarly, we can use any other assignment operators according to the need.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False. For
example,

a=5
b =2

print (a > b) # True

Here, the > comparison operator is used to compare whether a is greater than b or not.

Operator Meaning Example

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

31
< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True

Example 3: Comparison Operators


a=5

b=2

# equal to operator
print('a == b =', a == b)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)

# less than or equal to operator


print('a <= b =', a <= b)

Output

a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False. They are used in decision-
making. For example,

a=5
b=6

print((a > 2) and (b >= 6)) # True

32
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.

Operator Example Meaning

Logical AND:
and a and b
True only if both the operands are True

Logical OR:
or a or b
True if at least one of the operands is True

Logical NOT:
not not a
True if the operand is False and vice-versa.

Example 4: Logical Operators


# logical AND
print(True and True) # True
print(True and False) # False

# logical OR
print(True or False) # True

# logical NOT
print(not True) # False

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence
the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)

33
6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership
operator. They are described below with examples.

Identity operators

In Python, is and is not are used to check if two values are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.

Operator Meaning Example

is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not True

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False


Run Code

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. Same is
the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them
separately in memory although they are equal.

Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is
found in a sequence (string, list, tuple, set and dictionary).

34
In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

Example 5: Membership operators in Python


x = 'Hello world'
y = {1:'a', 2:'b'}

# check if 'H' is present in x string


print('H' in x) # prints True

# check if 'hello' is present in x string


print('hello' not in x) # prints True

# check if '1' key is present in y


print(1 in y) # prints True

# check if 'a' key is present in y


print('a' in y) # prints False
Run Code

Output

True
True
True
False

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).

Similarly,

1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.

Expressions in Python

An expression is a combination of operators and operands that is interpreted to produce some other value.

1. Constant Expressions: These are the expressions that have constant values only.

Example:

# Constant Expressions

35
x = 15 + 1.3
print(x)
Output

16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and


sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic
operators in Python:

Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x % y Remainder

** x ** y Exponentiation

Example:

Let’s see an exemplar code of arithmetic expressions in Python :

# Arithmetic Expressions
x = 40
y = 12

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
print(div)
Output

52
28
480

36
3.3333333333333335

3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.

Example:

# Integral Expressions
a = 13
b = 12.0

c = a + int(b)
print(c)
Output

25

4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.

Example:

# Floating Expressions
a = 13
b=5

c=a/b
print(c)
Output

2.6

5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides
of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then
compared as per relational operator and produce a boolean output in the end. These expressions are also
called Boolean expressions.

Example:

# Relational Expressions
a = 21
b = 13
c = 40
d = 37

p = (a + b) >= (c - d)
print(p)
Output

True

37
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it
is not correct, so it will return False. Studying logical expressions, we also come across some logical
operators which can be seen in logical expressions most often. Here are some logical operators in Python:

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:

Let’s have a look at an exemplar code :

P = (10 == 9)

Q = (7 > 5)

# Logical Expressions

R = P and Q

S = P or Q

T = not P

print(R)

print(S)

print(T)

Output

False
True
True

7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit
level.

Example:

38
# Bitwise Expressions
a = 12

x = a >> 2
y = a << 1

print(x, y)
Output

3 24

8. Combinational Expressions: We can also use different types of expressions in a single expression,
and that will be termed as combinational expressions.

Example:

# Combinational
Expressions
a = 16
b = 12

c = a + (b >> 1)
print(c)
Output

22

But when we combine different types of expressions or use multiple operators in a single expression,
operator precedence comes into play.

Multiple operators in expression (Operator Precedence)

Operator Precedence simply defines the priority of operators that which operator is to be executed first.
Here we see the operator precedence in Python, where the operator higher in the list has more precedence
or priority:

Precedence Name Operator


1 Parenthesis ()[]{}
2 Exponentiation **
3 Unary plus or minus, complement -a , +a , ~a
4 Multiply, Divide, Modulo / * // %
5 Addition

# Multi-operator expression

a = 10 + 3 * 4
print(a)

39
b = (10 + 3) * 4
print(b)

c = 10 + (3 * 4)
print(c)
Output

22
52
22

Hence, operator precedence plays an important role in the evaluation of a Python expression.

Python Type Conversion

In programming, type conversion is the process of converting data of one type to another. For example:
converting int data to str.

There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion


 Explicit Conversion - manual type conversion

Python Implicit Type Conversion

In certain situations, Python automatically converts one data type to another. This is known as implicit
type conversion.

Example 1: Converting integer to float

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))
Run Code

Output

Value: 124.23

40
Data Type: <class 'float'>

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the data type of the
objects.

Example 2: Addition of string and integer Using Explicit Conversion

num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

Key Points to Remember

1. Type Conversion is the conversion of an object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted
using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.

Arrays:

41
The Array is an idea of storing multiple items of the same type together, making it easier to calculate the
position of each element by simply adding an offset to the base value.

The Array can be handled in Python by a module named Array. It is useful when we must manipulate
only specific data values. The following are the terms to understand the concept of an array:

Element - Each item stored in an array is called an element.

Index - The location of an element in an array has a numerical index, which is used to identify the
element's position. The index value is very much important in an Array.

Array Representation:

The important points that should be considered are as follows:

1. The index starts with 0.


2. We can easily find any elements within this Array using the Index value.
3. The length of the Array defines the capacity to store the elements. It is written like x[100], which
means the length of array x is specified by 100.

Array operations

Some of the basic operations supported by an array are as follows:

 Traverse - It prints all the elements one by one.


 Insertion - It adds an element at the given index.
 Deletion - It deletes an element at the given index.
 Search - It searches an element using the given index or by the value.
 Update - It updates an element at the given index.

The Array can be created in Python by importing the array module to the python program.

1. from array import *


2. arrayName = array(typecode, [initializers])

Accessing array elements

We can access the array elements using the respective indices of those elements.

Program code:

Here we give an example of how we access the elements of an array using its index value in Python. The
code is given below -

1. import array as arr


2. a = arr.array('i', [2, 4, 5, 6])
3. print("First element is:", a[0])
4. print("Second element is:", a[1])
5. print("Third element is:", a[2])

42
6. print("Forth element is:", a[3])
7. print("last element is:", a[-1])
8. print("Second last element is:", a[-2])
9. print("Third last element is:", a[-3])
10. print("Forth last element is:", a[-4])
11. print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])

Output:

First element is: 2


Second element is: 4
Third element is: 5
Forth element is: 6
last element is: 6
Second last element is: 5
Third last element is: 4
Forth last element is: 2
24566542

How to change or add elements?

Arrays are mutable, and their elements can be changed similarly to lists.

Program code:

Here in this example, we can change or add or replace any element from the Array in Python. The code is
given below -

1. import array as arr


2. numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
3.
4. # changing first element 1 by the value 0.
5. numbers[0] = 0
6. print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
7.
8. # changing last element 10 by the value 8.
9. numbers[5] = 8
10. print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
11.
12. # replace the value of 3rd to 5th element by 4, 6 and 8
13. numbers[2:5] = arr.array('i', [4, 6, 8])
14. print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

Output:

Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -

array('i', [0, 2, 3, 5, 7, 10])


array('i', [0, 2, 3, 5, 7, 8])

43
array('i', [0, 2, 4, 6, 8, 8])

Why use Arrays in Python?

A combination of arrays saves a lot of time. The Array can reduce the overall size of the code. Using an
array, we can solve a problem quickly in any language. The Array is used for dynamic memory
allocation.

How to Delete Elements from an Array?

The elements can be deleted from an array using Python's del statement. If we want to delete any value
from the Array, we can use the indices of a particular element.

1. import array as arr


2. number = arr.array('i', [1, 2, 3, 3, 4])
3. del number[2] # removing third element
4. print(number) # Output: array('i', [1, 2, 3, 4])

Output:

array('i', [10, 20, 40, 60])

Finding the length of an array

The length of an array is defined as the number of elements present in an array. It returns an integer value
that is equal to the total number of the elements present in that array.

Syntax

The syntax is -

1. len(array_name)

Array Concatenation

We can easily concatenate any two arrays using the + symbol.

Example 1:

1. a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])


2. b=arr.array('d',[3.7,8.6])
3. c=arr.array('d')
4. c=a+b
5. print("Array c = ",c)

Output:

Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])

44
Example 2:

1. import array as arr


2. x = arr.array('i', [4, 7, 19, 22]) # Initialize the array elements
3. print("First element:", x[0])
4. print("Second element:", x[1])
5. print("Second last element:", x[-1])

Output:

First element: 4
Second element: 7
Second last element: 22

45

You might also like