[go: up one dir, main page]

0% found this document useful (0 votes)
23 views50 pages

Unit 1

python

Uploaded by

CS BCA
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)
23 views50 pages

Unit 1

python

Uploaded by

CS BCA
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
You are on page 1/ 50

PYTHON PROGRAMMING

Python Programming
Python is a simple, general purpose, high level, and object-oriented programming
language.

Python is an interpreted scripting language also. Guido Van Rossum is known as


the founder of Python programming.

What is Python?
Python is a general-purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop applications. It
is simple and easy to learn and provides lots of high-level data structures.

Python is an easy-to-learn, powerful and versatile scripting language, which makes


it attractive for Application Development.

Python supports multiple programming patterns, including object-oriented,


imperative, and functional or procedural programming styles.

➢ 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: You 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.

History of Python
➢ Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 1
PYTHON PROGRAMMING

➢ Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, Unix shell, and other scripting languages.

➢ At the time when he began implementing Python, Guido van Rossum was also reading
the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from
the seventies, in the unlikely case you didn't know). It occurred to him that he needed a
name that was short, unique, and slightly mysterious, so he decided to call the language
Python.

➢ Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.

➢ Python 1.0 was released on 20 February, 1991.

➢ Python 2.0 was released on 16 October 2000 and had many major new features,
including a cycle detecting garbage collector and support for Unicode. With this release
the development process was changed and became more transparent and community-
backed.

➢ Python 3.0 (which early in its development was commonly referred to as Python 3000
or py3k), a major, backwards-incompatible release, was released on 3 December 2008
after a long period of testing. Many of its major features have been back ported to the
backwards-compatible Python 2.6.x and 2.7.x version series.

➢ In January 2017 Google announced work on a Python 2.7 to go transcompiler, which


The Register speculated was in response to Python 2.7's planned end-of-life.

Python Features
Python provides many useful features to the programmer. These features make it the
most popular and widely used language. We have listed below few-essential features of
Python.

o Easy to use and Learn: Python has a simple and easy-to-understand syntax,
unlike traditional languages like C, C++, Java, etc., making it easy for beginners to
learn.
o Expressive Language: It allows programmers to express complex concepts in just
a few lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 2
PYTHON PROGRAMMING

o Object-Oriented Language: It supports object-oriented programming, making


writing reusable and modular code easy.
o Open Source Language: Python is open source and free to use, distribute and
modify.
o Extensible: Python can be extended with modules written in C, C++, or other
languages.
o Learn Standard Library: Python's standard library contains many modules and
functions that can be used for various tasks, such as string manipulation, web
programming, and more.
o GUI Programming Support: Python provides several GUI frameworks, such as
Tkinter and PyQt, allowing developers to create desktop applications easily.
o Integrated: Python can easily integrate with other languages and technologies,
such as C/C++, Java, and . NET.
o Embeddable: Python code can be embedded into other applications as a scripting
language.
o Dynamic Memory Allocation: Python automatically manages memory allocation,
making it easier for developers to write complex programs without worrying about
memory management.
o Wide Range of Libraries and Frameworks: Python has a vast collection of
libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be
used to solve a wide range of problems.
o Versatility: Python is a universal language in various domains such as web
development, machine learning, data analysis, scientific computing, and more.
o Large Community: Python has a vast and active community of developers
contributing to its development and offering support. This makes it easy for
beginners to get help and learn from experienced developers.
o Career Opportunities: Python is a highly popular language in the job market.
Learning Python can open up several career opportunities in data science, artificial
intelligence, web development, and more.
o High Demand: With the growing demand for automation and digital
transformation, the need for Python developers is rising. Many industries seek
skilled Python developers to help build their digital infrastructure.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 3


PYTHON PROGRAMMING

o Increased Productivity: Python has a simple syntax and powerful libraries that
can help developers write code faster and more efficiently. This can increase
productivity and save time for developers and organizations.
o Big Data and Machine Learning: Python has become the go-to language for big
data and machine learning. Python has become popular among data scientists and
machine learning engineers with libraries like NumPy, Pandas, Scikit-learn,
TensorFlow, and more.

LITERAL
Literals in Python are defined as the raw data assigned to variables or constants
while programming.

Types of Literals in Python

There are five types of literal in Python, which are as follows-

 String Literals
 Numeric Literals
 Boolean Literals
 Literal Collections
 Special Literals

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.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 4


PYTHON PROGRAMMING

Example:

"Amala" , '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:

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.

Example:

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

'helloworld'

2) Using triple quotation marks:-

Example:

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

Output:

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 5


PYTHON PROGRAMMING

welcome
to
BHARATHI

Numeric literals:

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

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


integers) integers) point)

Numbers( ca Integers of Real numbers In the form of a+bj


n be both unlimited with both where a forms the real
positive and size followed integer and part and b forms the
negative) by lowercase fractional part imaginary part of the
with no or uppercase eg: -26.2 complex number. eg:
fractional L eg: 3.14j
part.eg: 100 87032845L

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.
13.print(x, y, z, u)
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 6
PYTHON PROGRAMMING

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.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 7


PYTHON PROGRAMMING

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:

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:

o List contains items of different data types. Lists are mutable i.e., modifiable.
o 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,'AMALA']
3. print(list)
4. print(list + list1)

Output:

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

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

Dictionary:
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 8
PYTHON PROGRAMMING

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


o 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:

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


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

Example

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

Output:

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

Set:

o Python set is the collection of the unordered dataset.


o 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:

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 9


PYTHON PROGRAMMING

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

Python Constants

A constant is a special type of variable whose value cannot be changed.

In Python, constants are usually declared and assigned in a module (a new file containing
variables, functions, etc which is imported to the main file).
Let's see how we declare constants in separate file and use it in the main file,

Create a constant.py:

# declare constants
PI = 3.14
GRAVITY = 9.8
Create a main.py:

# import constant file we created above


import constant

print(constant.PI) # prints 3.14


print(constant.GRAVITY) # prints 9.8

In the above example, we created the constant.py module file. Then, we assigned the
constant value to PI and GRAVITY.
After that, we create the main.py file and import the constant module. Finally, we
printed the constant value.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 10


PYTHON PROGRAMMING

Comparison chart

Constant versus Literal comparison chart

Constant Literal

Exampl const PI = 3.14; var radius = 5; var var radius = 5; var circumference
e circumference = 2 * PI * radius; = 2 * 3.14 * radius;

VARIABLES

A variable in a program is uniquely identified by a name (identifier). Variable in


Python refers to an object — an item or element that is stored in the memory. Value of a
variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or any
combination of alphanumeric characters (CD67). In Python we can use an assignment
statement to create new variables and assign specific values to them.

gender = 'M'
message = "Keep Smiling"
price = 987.9

Program : Write a program to display values of variables in Python.

#Program To display values of variables

message = "Keep Smiling"


print(message)
userNo = 101
print('User Number is', userNo)

Output:
Keep Smiling
User Number is 101

In the program 5-2, the variable message holds string type value and so its content is
assigned within double quotes " " (can also be within single quotes ' '), whereas the value
of variable userNo is not enclosed in quotes as it is a numeric value. Variable declaration
is implicit in Python, means variables are automatically declared and defined when they

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 11


PYTHON PROGRAMMING

are assigned a value the first time. Variables must always be assigned values before they
are used in expressions as otherwise it will lead to an error in the program. Wherever a
variable name occurs in an expression, the interpreter replaces it with the value of that
particular variable.

Program : Write a Python program to find the area of a rectangle given that its length is
10 units and breadth is 20 units.

#Program To find the area of a rectangle


length = 10
breadth = 20
area = length * breadth
print(area)
Output:

200

Consider the following valid variables name.

1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11.print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56
me)

Output:

ABCDEDEFGFI

Python Variable Types

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 12


PYTHON PROGRAMMING

There are two types of variables in Python - Local variable and Global variable.
Let's understand the following variables.

Local Variable

Local variables are the variables that declared inside the function and have scope
within the function. Let's understand the following example.

Example -

1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10.add()

Output:

The sum is: 50

Explanation:

In the above code, we declared a function named add() and assigned a few variables
within the function. These variables will be referred to as the local variables which have
scope only inside the function.

Global Variables

Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.

A variable declared outside the function is the global variable by default. Python
provides the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the
following example.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 13
PYTHON PROGRAMMING

Example -

1. # Declare a variable and initialize it


2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.
13.mainFunction()
14.print(x)

Output:

101

Welcome ToJavatpoint

Welcome ToJavatpoint

Explanation:

In the above code, we declare a global variable x and assign a value to it. Next, we
defined a function and accessed the declared variable using the global keyword inside the
function. Now we can modify its value. Then, we assigned a new string value to the
variable x.

Now, we called the function and proceeded to print x. It printed the as newly assigned
value of x.

Delete a variable

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 14


PYTHON PROGRAMMING

We can delete the variable using the del keyword. The syntax is given below.

Syntax -

1. del <variable_name>

In the following example, we create a variable x and assign value to it. We deleted
variable x, and print it, we get the error "variable x is not defined". The variable x will
no longer use in future.

Example -

1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)

Output:

Traceback (most recent call last):

File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line


389, in

print(x)

NameError: name 'x' is not defined

Print Single and Multiple Variables in Python

We can print multiple variables within the single print statement. Below are the example
of single and multiple printing values.

Example - 1 (Printing Single Variable)

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 15


PYTHON PROGRAMMING

1. # printing single value


2. a=5
3. print(a)
4. print((a))
Output:

Example - 2 (Printing Multiple Variables)

1. a=5
2. b=6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)

Output:

56

12345678

IDENTIFIERS
In programming languages, identifiers are names used to identify a variable,
function, or other entities in a program. The rules for naming an identifier in Python are
as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore sign
(_). This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore
(_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

PYTHON KEYWORDS

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 16


PYTHON PROGRAMMING

Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which it
has been defined. As Python is case sensitive.

Python contains thirty-five keywords in the most recent version, i.e., Python 3.8.
Here we have shown a complete list of Python keywords for the reader's reference.

False await else import pass

None break except in raise

True class finally is return

And continue for lambda try

As def from nonlocal while

assert del global not with

async elif if or yield

DATA TYPES

Every value belongs to a specific data type in Python. Data type identifies the type
of data values a variable can hold and the operations that can be performed on that data.
Figure 5.6 enlists the data types available in Python.

Number

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 17


PYTHON PROGRAMMING

Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.

Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting
of two constants, True and False. Boolean True value is non-zero, non-null and non-
empty. Boolean False is the value zero.
Let us now try to execute few statements in interactive mode to determine the data type
of the variable using built-in function type().
Example
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2))
(-3+7.2j) <class 'complex'>

Variables of simple data types like integers, float, boolean, etc., hold single values.
But such variables are not useful to hold a long list of information, for example, names of
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 18
PYTHON PROGRAMMING

the months in a year, names of students in a class, names and numbers in a phone book or
the list of artefacts in a museum. For this, Python provides data types like tuples, lists,
dictionaries and sets.

Sequence

A Python sequence is an ordered collection of items, where each item is indexed


by an integer. The three types of sequence data types available in Python are Strings,
Lists and Tuples. We will learn about each of them in detail in later chapters. A brief
introduction to
these data types is as follows:

(A) String
String is a group of characters. These characters may be alphabets, digits or special
characters including spaces. String values are enclosed either in single quotation marks
(e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”). The quotes are not a part of
the string, they are used to mark the beginning and end of the string for the interpreter.
For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a
numeric
value, as in str2.

(B) List
List is a sequence of items separated by commas and the items are enclosed in
square
brackets [ ].
Example 5.4
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]

(C) Tuple

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 19


PYTHON PROGRAMMING

Tuple is a sequence of items separated by commas and items are enclosed in


parenthesis ( ). This is unlike list, where values are enclosed in brackets [ ]. Once created,
we cannot change the tuple.
Example 5.5
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')

Set

Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have duplicate
entries. Once created, elements of a set cannot be changed.
Example 5.6
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set

>>> set2 = {1,2,1,3}


>>> print(set2)
{1, 2, 3}

None

None is a special data type with a single value. It is used to signify the absence of
value in a situation. None supports no special operations, and it is neither same as False
nor 0 (zero).
Example 5.7
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None

Mapping
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 20
PYTHON PROGRAMMING

Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called dictionary.

(A) Dictionary

Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }.
Dictionaries permit faster access to data. Every key is separated from its value using a
colon (:) sign. The key : value pairs of a dictionary can be accessed using the key. The
keys are usually strings and their values can be any data type. In order to access any value
in the
dictionary, we have to specify its key in square brackets [ ].
Example 5.8
#create a dictionary
>0>> dict1 = {'Fruit':'Apple',
'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold',
'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120

Mutable and Immutable Data Types

Sometimes we may require to change or update the values of certain variables used
in a program. However, for certain data types, Python does not allow us to change the
values once a variable of that type has been created and assigned values. Variables whose
values can be changed after they are created and assigned are called mutable. Variables
whose values cannot be changed after they are created and assigned are called immutable.
When an attempt is made to update the value of an immutable variable, the old variable is
destroyed and a new variable is created by the same name in memory.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 21


PYTHON PROGRAMMING

Python data types can be classified into mutable and immutable as shown in Figure 5.7.

INPUT / OUTPUT and IMPORT Function


Python input() Function

Python input() function is used to get input from the user. It prompts for the user
input and reads a line. After reading data, it converts it into a string and returns that. It
throws an error EOFError if EOF is read.

Signature
1. input ([prompt])
Parameters

prompt: It is a string message which prompts for the user input.

Return

It returns user input after converting into a string.

Let's see some examples of input() function to understand it's functionality.

Python input() Function Example 1

Here, we are using this function get user input and display to the user as well.

1. # Python input() function example


2. # Calling function
3. val = input("Enter a value: ")
4. # Displaying result
5. print("You entered:",val)

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 22


PYTHON PROGRAMMING

Output:

Enter a value: 45

You entered: 45

Python input() Function Example 2

The input() method returns string value. So, if we want to perform arithmetic operations,
we need to cast the value first. See the example below.

1. # Python input() function example


2. # Calling function
3. val = input("Enter an integer: ")
4. # Displaying result
5. val = int(val) # casting into string
6. sqr = (val*val) # getting square
7. print("Square of the value:",sqr)

Output:

Enter an integer: 12

Square of the value: 144

Input function

In Python, we have the input() function for taking the user input. The input()
function prompts the user to enter data.It accepts all user input as string. The user may
enter a number or a string but the input() function treats them as strings only. The syntax
for input() is:

input ([Prompt])

Prompt is the string we may like to display on the screen prior to taking the input,
and it is optional. When a prompt is specified, first it is displayed on the screen after
which the user can enter data. The input() takes exactly what is typed from the keyboard,
converts it into a string and assigns it to the variable on left-hand side of the assignment
operator (=). Entering data for the input function is terminated by pressing the enter key.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 23
PYTHON PROGRAMMING

Example

>>> fname = input("Enter your first name: ")


Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<class 'str'>

The variable fname will get the string ‘Arnab’, entered by the user. Similarly, the
variable age will get the string ‘19’. We can typecast or change the datatype of the string
data accepted from user to an appropriate numeric value. For example, the following
statement will convert
the accepted string to an integer. If the user enters any non-numeric value, an error will
be generated.

Example
#function int() to convert string to integer
>>> age = int( input("Enter your age:"))
Enter your age: 19
>>> type(age)
<class 'int'>

Python print() Function

Python print() function prints the given object on the screen or other standard
output devices.

Signature
1. print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameters

object(s): It is an object to be printed. The Symbol * indicates that there may be more
than one object.

sep='separator' (optional): The objects are separated by sep. The default value of sep is
' '.

end='end' (optional): it determines which object should be print at last.


R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 24
PYTHON PROGRAMMING

file (optional): - The file must be an object with write(string) method. If it is omitted,
sys.stdout will be used which prints objects on the screen.

flush (optional): If True, the stream is forcibly flushed. The default value of flush is
False.

Return

It does not return any value.

Python print() Function Example 1

The below example shows the working of print().

1. print("Python is programming language.")


2.
3. x=7
4. # Two objects passed
5. print("x =", x)
6.
7. y=x
8. # Three objects passed
9. print('x =', x, '= y')

Output:

Python is programming language.

x=7

x=7=y

Python print() Function Example 2

The below example use print() with separator and end parameters.

1. x = 7
2. print("x =", x, sep='00000', end='\n\n\n')
3. print("x =", x, sep='0', end='')

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 25


PYTHON PROGRAMMING

Output:

a =000007

a =07

Python import Function

In Python, we may import functions from one module into our program, or as we
say into, another module.

For this, we make use of the import Python keyword. In the Python window, we
add the next to import keyword, the name of the module we need to import.

There are several standard modules for Python. The complete list of Python standard
modules is available.

Code

1. # Python program to show how to import a standard module


2. # We will import the math module which is a standard module
3.
4. import math
5. print( "The value of euler's number is", math.e )

Output:

The value of euler's number is 2.718281828459045

COMMENTS

Comments are used to add a remark or a note in the source code. Comments are
not executed by interpreter.
They are added with the purpose of making the source code easier for humans to
understand..
In Python, a comment starts with # (hash sign).Everything following the # till the
end of that line is treated as a comment and the interpreter simply ignores it while
executing the statement.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 26


PYTHON PROGRAMMING

Example

Program : Write a Python program to find the sum of two numbers.


#Program

#To find the sum of two numbers


num1 = 10
num2 = 20
result = num1 + num2
print(result)

Output:

30

There are two types of comments in Python:


Single line comments:

Python single-line comment starts with a hashtag symbol with no white spaces
(#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag
on the next line and continue the comment. Python’s single-line comments are proved
useful for supplying short explanations for variables, function declarations, and
expressions. See the following code snippet demonstrating single line comment:
Code 1:
 Python3

# This is a comment

print("BHARATHI WOMEN’S COLLEGE")

Output
BHARATHI WOMEN’S COLLEGE
Code 2:

 Python3

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 27


PYTHON PROGRAMMING

a, b =1, 3# Declaring two integers

sum=a +b # adding two integers

print(sum) # displaying the output

Multi-line string as a comment:

Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each


end of the comment. Again there should be no white space between delimiter (“””).
They are useful when the comment text does not fit into one line; therefore need to span
across lines. Multi-line comments or paragraphs serve as documentation for others
reading your code. See the following code snippet demonstrating multi-line comment:
Code 1:
 Python3

"""

A Computer Science portal for geeks. It contains


well written, well thought and well-explained
computer science and programming articles, quizzes
and more.

"""

print("HELLO")

Output
HELLO

INDENTATION IN PYTHON

o Indentation refers to the proper participation of white space while starting a


particular block of code.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 28


PYTHON PROGRAMMING

o It is not too much complicated and not more focused on the syntax.
o It is much faster and efficient than the other programming languages.
o Python code can be easily implemented and easily written, and easily be
executable.

Some basic Indentation Rules that are used in Python programming Language
o There is a proper indentation for a particular block of code that must be maintained
while beginning and ending any code block.
o A programmer can split the indentation into multiple lines by using a backslash.
o If any block where proper indentation is not maintained, the python compile will
throw the indentation error.
o Being consistent in following the indentation rule is quite confusing for a
programmer if the code is too large or contains lots of lines of code.
o But indentation helps us implement the code using simple syntax, rather than
applying brackets for every block of code, as we do in other programming
languages.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 29


PYTHON PROGRAMMING

o Not only it is easy for us, but also it saves our time and reduces the lines of code;
hence ultimately, speed increases and execution tile reduces.
o The number of whitespace for a particular block of code is already fixed. If we use
nested conditional statements, then the number of whitespaces has increased,
according to the rule of sub-sub statements.

Example program

if 5 > 2:

print("Five is greater than two!")

output:

File "demo_indentation_test.py", line 2


print("Five is greater than two!")
^
IndentationError: expected an indented block

OPERATORS

An operator is used to perform specific mathematical or logical operation on


values. The values that the operators work on are called operands. For example, in the
expression 10 + num, the value 10, and the variable num are operands and the + (plus)
sign is an operator. Python supports several kinds of operators whose categorisation is
briefly explained in this section.

ARITHMETIC OPERATORS
Python supports arithmetic operators that are used to perform the four basic
arithmetic operations as well as modular division, floor division and exponentiation.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 30


PYTHON PROGRAMMING

Relational Operators

Relational operator compares the values of the operands on its either side and determines
the relationship among them. Assume the Python variables num1 = 10, num2 = 0, num3
= 10, str1 = "Good", str2 = "Afternoon" for the following examples:

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 31


PYTHON PROGRAMMING

Table 5.4 Relational operators in Python

Assignment Operators

Assignment operator assigns or changes the value of the variable on its left.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 32


PYTHON PROGRAMMING

Logical Operators

There are three logical operators supported by Python. These operators (and, or,
not) are to be written in lower case only. The logical operator evaluates to either True or
False based on the logical operands on either side. Every value is logically either True or
False. By default, all values are True except None, False, 0 (zero), empty collections "",
(), [], {}, and few other special values. So if we say num1 = 10, num2 = -20, then both
num1 and num2 are logically True.
Table 5.6 Logical operators in Python

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 33


PYTHON PROGRAMMING

Identity Operators
Identity operators are used to determine whether the
value of a variable is of a certain type or not. Identity
operators can also be used to determine whether twovariables are referring to the same
object or not. There are two identity operators.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 34


PYTHON PROGRAMMING

Membership Operators

Membership operators are used to check if a value is a


member of the given sequence or not.

TYPE CONVERSION

Consider the following program

num1 = input("Enter a number and I'll double it: ")


num1 = num1 * 2
print(num1)

The program was expected to display double the value of the number received and
store in variable num1. So if a user enters 2 and expects the program to display 4 as the
output, the program displays the following result:

Enter a number and I'll double it: 2


22
This is because the value returned by the input function is a string ("2") by default.
As a result, in statement num1 = num1 * 2, num1 has string value and * acts as repetition
operator which results in output as "22". To get 4 as output, we need to convert the data
type of the value entered by the user to integer. Thus, we modify the program as follows:

num1 = input("Enter a number and I'll double it: ")


num1 = int(num1) #convert string input to integer
num1 = num1 * 2
print(num1)
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 35
PYTHON PROGRAMMING

Now, the program will display the expected output as follows:

Enter a number and I'll double it: 2


4
Let us now understand what is type conversion and how it works. As and when
required, we can change the data type of a variable in Python from one type to another.
Such data type conversion can happen in two ways: either explicitly (forced) when the
programmer specifies for the interpreter to convert a data type to another type; or
implicitly, when the interpreter understands such a need by itself and does the type
conversion automatically.

Explicit Conversion

Explicit conversion, also called type casting happens when data type conversion
takes place because the programmer forced it in the program. The general form of an
explicit data type conversion is:

(new_data_type) (expression)

With explicit type conversion, there is a risk of loss of information since we are
forcing an expression to be of a specific type. For example, converting a floating value of
x = 2 0.67 into an integer type, i.e., int(x) will discard the fractional part .67. Following
are some
of the functions in Python that are used for explicitly converting an expression or a
variable to a different type.

#Program :Explicit type conversion from int to float

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 36


PYTHON PROGRAMMING

num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:
30
<class 'int'>
30.0
<class 'float'>

Program : Program of explicit type conversion from float to int.

#Program
#Explicit type conversion from float to int
num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Output:
30.8
<class 'float'>
30
<class 'int'>

Program :Example of type conversion between numbers and strings.

#Program :Type Conversion between Numbers and Strings


priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + totalPrice )

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 37


PYTHON PROGRAMMING

On execution, program gives an error as shown in Figure 5.11, informing that the
interpreter cannot convert an integer value to string implicitly. It may appear quite
intuitive that the program should convert the integer value to a string depending upon the
usage.
However, the interpreter may not decide on its own when to convert as there is a
risk of loss of information. Python provides the mechanism of the explicit type
conversion so that one can clearly state the desired outcome. Program 5 works perfectly
using explicit type casting:

Program 5 Program to show explicit type casting.


#Program 5
#Explicit type casting
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice))
Output:
The total in Rs.70

Similarly, type casting is needed to convert float to string. In Python, one can
convert string to integer or float values whenever required.

Program : Program to show explicit type conversion.

#Program
#Explicit type conversion
icecream = '25'
brownie = '45'
#String concatenation

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 38


PYTHON PROGRAMMING

price = icecream + brownie


print("Total Price Rs." + price)
#Explicit type conversion - string to integer

price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))
Output:
Total Price Rs.2545
Total Price Rs.70

Implicit Conversion

Implicit conversion, also known as coercion, happens when data type conversion is
done automatically by Python and is not instructed by the programmer.

Program : Program to show implicit conversion from int to float.

#Program : Implicit type conversion from int to float


num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float
and an integer
print(sum1)
print(type(sum1))

Output:
30.0
<class 'float'>

EXPRESSION

Expression: An expression is a combination of operators, constants and


variables. An expression may consist of one or more operands, and zero or more
operators to produce a value.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 39


PYTHON PROGRAMMING

Example:
a+b
c
s-1/7*f
Types of Expressions:

Expressions may be of the following types:

 Constant expressions: Constant Expressions consists of only constant values. A


constant value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 40


PYTHON PROGRAMMING

# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3

 Integral expressions: Integral Expressions are those which produce integer results
after implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.

# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)

Output
25

 Floating expressions: Float Expressions are which produce floating point results
after implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
 Relational expressions: Relational Expressions yield results of type bool which
takes a value true or false. When arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:
x <= y, x + y > 2

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 41


PYTHON PROGRAMMING

 Logical expressions: Logical Expressions combine two or more relational


expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
 Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
 Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level.
They are basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 42


PYTHON PROGRAMMING

PYTHON - ARRAYS
Array is a container which can hold a fix number of items and these items should be of
the same type. Most of the data structures make use of arrays to implement their
algorithms. Following are the important terms to understand the concept of Array.
 Element− Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.

As per the above illustration, following are the important points to be considered.
 Index starts with 0.
 Array length is 10 which means it can store 10 elements.
 Each element can be accessed via its index. For example, we can fetch an element
at index 6 as 9.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 43


PYTHON PROGRAMMING

PROCESSING ARRAYS:

An array in Python:

import array as arr


numbers = arr.array('i',[10,20,30])
print(numbers)

#output
#array('i', [10, 20, 30])

 First we included the array module, in this case with import array as arr .
 Then, we created a numbers array.
 We used arr.array() because of import array as arr .
 Inside the array() constructor, we first included i, for signed integer. Signed integer
means that the array can include positive and negative values. Unsigned integer,
with H for example, would mean that no negative values are allowed.
 Lastly, we included the values to be stored in the array in square brackets.
Keep in mind that if you tried to include values that were not of i typecode, meaning they
were not integer values, you would get an error:

import array as arr


numbers = arr.array('i',[10.0,20,30])
print(numbers)

#output
#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
# numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error
because this is meant to be an integer array only.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 44
PYTHON PROGRAMMING

Another way to create an array is the following:

from array import *

#an array of floating point values


numbers = array('d',[10.0,20.0,30.0])
print(numbers)

#output
#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an
array numbers of float data type. This means that it holds only floating point numbers,
which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-
in len() method.
It will return the integer number that is equal to the total number of elements in the array
you specify.

import array as arr


numbers = arr.array('i',[10,20,30])
print(len(numbers))

#output
#3

In the example above, the array contained three elements – 10, 20, 30 – so the length
of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing
their index number.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 45


PYTHON PROGRAMMING

Indexing in Python, and in all programming languages and computing in general, starts
at 0. It is important to remember that counting starts at 0 and not at 1.
To access an element, you first write the name of the array followed by square brackets.
Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr


numbers = arr.array('i',[10,20,30])
print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output
#10
#20
#30

ARRAY METHODS:
Following are the basic operations supported by an array.
 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the
array is declared as shown eblow.

from array import *

arrayName = array(typecode, [Initializers])

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 46


PYTHON PROGRAMMING

Typecode are the codes that are used to define the type of value the array will hold. Some
common typecodes used are:

Typecode Value

b Represents signed integer of size 1 byte/td>

B Represents unsigned integer of size 1 byte

c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes

Before lookign at various array operations lets create and print an array using python.
The below code creates an array named array1.
from array import *

array1 = array('i', [10,20,30,40,50])

for x in array1:
print(x)
When we compile and execute the above program, it produces the following result −
Output

10
20
30
40
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 47
PYTHON PROGRAMMING

50

Accessing Array Element


We can access each element of an array using the index of the element. The below code
shows how

from array import *

array1 = array('i', [10,20,30,40,50])

print (array1[0])

print (array1[2])
When we compile and execute the above program, it produces the following result −
which shows the element is inserted at index position 1.
Output

10
30

Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of
array.
Here, we add a data element at the middle of the array using the python in-built insert()
method.

from array import *

array1 = array('i', [10,20,30,40,50])

array1.insert(1,60)

for x in array1:
print(x)

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 48


PYTHON PROGRAMMING

When we compile and execute the above program, it produces the following result which
shows the element is inserted at index position 1.
Output

10
60
20
30
40
50

Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Here, we remove a data element at the middle of the array using the python in-built
remove() method.

from array import *

array1 = array('i', [10,20,30,40,50])

array1.remove(40)

for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which
shows the element is removed form the array.
Output
10
20
30
50
Search Operation
You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method.

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 49


PYTHON PROGRAMMING

from array import *

array1 = array('i', [10,20,30,40,50])

print (array1.index(40))
When we compile and execute the above program, it produces the following result which
shows the index of the element. If the value is not present in the array then th eprogram
returns an error.
Output
3

Update Operation
Update operation refers to updating an existing element from the array at a given index.
Here, we simply reassign a new value to the desired index we want to update.

from array import *

array1 = array('i', [10,20,30,40,50])

array1[2] = 80

for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which
shows the new value at the index position 2.
Output
10
20
80
40
50

R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 50

You might also like