0% found this document useful (0 votes)
25 views18 pages

Python Unit1

Python is an interpreted, general-purpose programming language created by Guido van Rossum. It emphasizes code readability and supports multiple programming paradigms including object-oriented, procedural, and functional programming. Python provides many useful features like being easy to learn and use, having an expressive syntax, being interpreted and cross-platform, and having a large standard library.

Uploaded by

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

Python Unit1

Python is an interpreted, general-purpose programming language created by Guido van Rossum. It emphasizes code readability and supports multiple programming paradigms including object-oriented, procedural, and functional programming. Python provides many useful features like being easy to learn and use, having an expressive syntax, being interpreted and cross-platform, and having a large standard library.

Uploaded by

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

Introduction to Python

THE BASIC ELEMENTS OF PYTHON

 Python is an interpreted, general-purpose programming language


 Created by Guido van Rossum and first released in 1991
 Latest version is 3.8
 Emphasizes code readability
 Object-oriented approach aims to help programmers write clear, logical code for small and
large-scale projects
 Python is Dynamically typed and garbage-collected.
 Supports multiple programming paradigms, including procedural, object-oriented,
and functional programming.
 Comprehensive standard library.

FEATURES

Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential features.
1) Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is straightforward
and much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java or C
takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So,
we can say that Python is a portable language. It enables programmers to develop the software for
several competing platforms by writing a program only once.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official website [Link]. It
has a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source means,
"Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used
further in our Python code. It converts the program into byte code, and any platform can use that byte
code.
8) Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web developer, and
also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web
development.
9) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the
libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc.

BASIC ELEMENTS OF PYTHON


 A Python program, sometimes called a script, is a sequence of definitions and commands.
 These definitions are evaluated and the commands are executed by the Python interpreter in
the shell.
 Typically, a new shell is created whenever execution of a program begins.
 A command, often called a statement, instructs the interpreter to do something.
 The sequence of commands
 print (‘Welcome to Python!‘)
 print ('But not in Boston!‘)
 print (‘Once bitten,', ‘Twice shy!’)
 Welcome to Python!
 Once bitten,', ‘Twice shy!

OBJECTS, EXPRESSIONS, AND NUMERICAL TYPES


Objects are the core things that Python programs manipulate. Every object has a type that defines the
kinds of things that programs can do with objects of that type. Types are either scalar or non-scalar.
Scalar objects are indivisible. Think of them as the atoms of the language. Non-scalar objects, for
example strings, have internal structure.
Python has four types of scalar objects:
 int is used to represent integers. Literals of type int are written in the way we typically denote
integers (e.g., -3 or 5 or 10002).
 float is used to represent real numbers. Literals of type float always include a decimal point
(e.g., 3.0 or 3.17 or -28.72
 bool is used to represent the Boolean values True and False.
 None is a type with a single value. We will say more about this when we get to variables
Ex: The built-in Python function type can be used to find out the type of an object:
>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>

VARIABLES AND ASSIGNMENT

Variables provide a way to associate names with objects. Ex: pi = 3,radius = 11

NAMING OF VARIABLES
• Variable names can contain uppercase and lowercase letters, digits (But they cannot start with
a digit), and the special character _.
• Python variable Names are case-sensitive e.g., Julie and julie are different names.
• There are a small number of reserved words (sometimes called keywords) in Python that
have built-in meanings and cannot be used as variable names.
DECLARING VARIABLE AND ASSIGNING VALUES
Python does not bound us to declare variable before using in the application. It allows us to create
variable at required time. We don't need to declare explicitly variable in Python. When we assign any
value to the variable that variable is declared automatically. The equal (=) operator is used to assign
value to a variable.
Eg:

MULTIPLE ASSIGNMENT
Python allows us to assign a value to multiple variables in a single statement which is also known as
multiple assignment. We can apply multiple assignments in two ways either by assigning a single value
to multiple variables or assigning multiple values to multiple variables. Lets see given examples.
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print x
print y
print z
Output:
>>>
50
50
50
>>>
[Link] multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
>>>
5
10
15
The values will be assigned in the order in which variables appears.
RESERVED WORDS
• Some of the reserved words in python are: and, as, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise,
return, try, with, while, and yield.

OPERATIONS ON OBJECTS

The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built
in a particular programming language. Python provides a variety of operators described
as follows.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators

ARITHMETIC OPERATORS
Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent
(**).
Consider the following table for a detailed explanation of arithmetic operators

COMPARISON OPERATOR
Comparison operators are used to comparing the value of the two operands and returns boolean true
or false accordingly. The comparison operators are described in the following table.

Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value result negative. For
example, if a = 20, b = 10 => a ? b = 10

/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2

* It is used to multiply one operand with the other. For example, if a = 20, b =
(Multiplication) 10 => a * b = 200

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first operand


power to second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)
PYTHON ASSIGNMENT OPERATORS
The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.

Operator Description

== If the value of two operands is equal, then the condition


becomes true.

!= If the value of two operands is not equal then the condition


becomes true.

<= If the first operand is less than or equal to the second


operand, then the condition becomes true.

>= If the first operand is greater than or equal to the second


operand, then the condition becomes true.

<> If the value of two operands is not equal, then the condition
becomes true.

> If the first operand is greater than the second operand, then
the condition becomes true.

< If the first operand is less than the second operand, then the
condition becomes true.

Operator Description

= It assigns the the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.

-= It decreases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand
and assign the reminder back to left operand. For example, if a = 20, b
= 10 => a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will
assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will


assign 4//3 = 1 to a.

LOGICAL OPERATORS
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators

Operator Description

and If both the expression are true, then the condition will be true. If a and b
are the two expressions, a → true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b
are the two expressions, a → true, b → false => a or b → true.

not If an expression a is true then not (a) will be false and vice versa.

PYTHON COMMENTS
Comments in Python can be used to explain any program code. It can also be used to hide the code
as well. Comments are the most helpful stuff of any program. It enables us to understand the way, a
program works. In python, any statement written along with # symbol is known as a comment. The
interpreter does not interpret the comment. Comment is not a part of the program, but it enhances
the interactivity of the program and makes the program readable.
Python supports two types of comments:
1. Single Line Comment:
In case user wants to specify a single line comment, then comment must start with #
Eg:
# This is single line comment.
print "Hello Python"
Output:
Hello Python
2. Multi Line Comment:
Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multipline comment'''
eg:
#single line comment
print "Hello Python"
'''''This is
multiline comment'''

BRANCHING PROGRAMS
Two types of computations in python are:
1. Straight line programs
They execute one statement after another in the order in which they appear, and stop
when they run out of statements. The kinds of computations we can describe with
straight-line programs
2. Branching programs
Branching statements are conditional. A conditional statement has three parts
– A test
– Block of code to be executed if test is true
– Optional block of code if test is false

PYTHON IF-ELSE STATEMENTS


Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.
In python, decision making is performed by the following statements.
1. If Statement - The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.
The syntax of the if-statement is given below.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

2. If - else Statement - The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.

The syntax of the if-else statement is given below.


if condition:
#block of statements
else:
#another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Example 2: Program to check whether a number is even or not.


num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

3. The elif statement

The elif statement enables us to check multiple conditions and execute the specific block
of statements depending upon the true condition among them. We can have any number
of elif statements in our program depending upon our need. However, using elif is
optional. The elif statement works like an if-else-if ladder statement in C. It must be
succeeded by an if [Link] syntax of the elif statement is given below.

if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

CONTROL STRUCTURES AND ITERATION


The flow of the programs written in any programming language is sequential by default. Sometimes
we may need to alter the flow of the program. The execution of a specific code may need to be
repeated several numbers of times. For this purpose, The programming languages provide various
types of loops which are capable of repeating some specific code several numbers of times. Consider
the following diagram to understand the working of a loop statement.

Advantages of loops
There are the following advantages of loops in Python.
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.


1. for loop
The for loop in Python is used to iterate the statements or a part of the program several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary. The syntax of
for loop in python is given below.
for iterating_var in sequence:
statement(s)
Python for loop example : printing the table of the given number
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));

Using else statement with for loop


Unlike other languages like C, C++, or Java, python allows us to use the else statement with the for
loop which can be executed only when all the iterations are exhausted. Here, we must notice that if
the loop contains any of the break statement then the else statement will not be executed.
Ex:
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.");

In the above example, for loop is executed completely since there is no break statement in the loop.
The control comes out of the loop and hence the else block is executed.
Ex:
for i in range(0,5):
print(i)
break;
else:
print("for loop is exhausted");
print("The loop is broken due to break statement...came out of loop")

In the above example, the loop is broken due to break statement therefore the else statement will
not be executed. The statement present immediate next to else block will be executed.

2. Python while loop


The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to
be executed as long as the given condition is true.
It can be viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in [Link] syntax is given below.
while expression:
statements
Here, the statements can be a single statement or the group of statements. The expression should be
any valid python expression resulting into true or false. The true is any non-zero value.

Ex:
i=1;
while i<=10:
print(i);
i=i+1;

Infinite while loop


If the condition given in the while loop never becomes false then the while loop will never terminate
and result into the infinite while loop. Any non-zero value in the while loop indicates an always-true
condition whereas 0 indicates the always-false condition. This type of approach is useful if we want
our program to run continuously in the loop without any disturbance.
Ex:
while (1):
print("Hi! we are inside the infinite while loop");

Using else with Python while loop


Python enables us to use the while loop with the while loop also. The else block is executed when the
condition given in the while statement becomes false. Like for loop, if the while loop is broken using
break statement, then the else block will not be executed and the statement present after else block
will be executed.
Consider the following example.
c=0
while c < 5:
print (c)
c=c+1
else:
print("c is no longer less than 6")

STRINGS AND INPUT


Python String
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Consider the following example in python to create a string.
str = "Hi Python !"
Here, if we check the type of the variable str using a python script
print(type(str)), then it will print string (str).
In python, strings are treated as the sequence of strings which means that python doesn't support the
character data type instead a single character written as 'p' is treated as the string of length 1.
Like other languages, the indexing of the python strings starts from 0. For example, The string "HELLO"
is indexed as given in the below figure.

1. slicing - the slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in python to access the substring. Consider the following
example
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str =
'python' is given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and nothing else.

Reassigning strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't
support item assignment i.e., A string can only be replaced with a new string since its content can not
be partially replaced. Strings are immutable in python.
Consider the following example.
Example 1
str = "HELLO"
str[0] = "h"
print(str)

2. len() function is an inbuilt function in Python programming language that returns the
length of the string.
Syntax:
len(string)

Ex:
string = "geeks"
print(len(string))

output =5

Ex:
# Length of below string is 15
string = "geeks for geeks"
print(len(string))

INPUT
Values can be accepted from the user using input() function
E.g1:
name=input(“Enter the name”)
print(“you entered“, name)
E.g 2:
a = float(input('Enter a: '))
b = float(input('Enter b: '))
print('The values are {0} and {1}'.format(a, b))

FUNCTIONS
• We can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
• Any input parameters or arguments should be placed within these parentheses.
• The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
• Syntax
def functionname( parameters ):
"function_docstring"
return [expression]

In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python prompt.
To call the function, use the function name followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
def hello_world():
print("hello world")

hello_world()

PYTHON PASS
In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code,
the pass can be used to execute empty. It is same as the name refers to. It just makes the control to
pass by without executing any code. If we want to bypass any code pass statement can be used.
Python Pass Syntax
pass

Python Pass Example


for i in [1,2,3,4,5]:
if i==3:
pass
print "Pass when value is",i
print i
Output:
1. >>>
2. 1 2 Pass when value is 3
3. 345
4. >>>

SCOPING AND ABSTRACTION


Functions and scoping,
• Scope defines portion of programs where we can access a particular identifier
• Two types of scopes
– Global variables
– Local variables
• Variables defined inside a function have local scope & outside have global scope
• Global variables can be accessed throughout the program
• Ex:
def f(x):
y=1
x=x+y
print("x =",x)
return x

x=3
y =2
z = f(x)
print('z =', z)
print('x =', x)
print('y =', y)

SPECIFICATIONS
• Specifications: Standards maintained by developer
• Assumptions: Conditions that must be met by the client
• Guarantees: Conditions that must be met by the functions
• Decomposition: Ability to break down the program into sub parts for better understanding
• Abstraction: Hiding non essential details

RECURSION
• When a function call itself is knows as recursion
• A base condition is must in every recursive programs otherwise it will continue to execute
forever like an infinite loop.
• A recursive program needs to have a termination condition
Ex:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)

print(fact(0))
print(fact(5))

GLOBAL VARIABLES
• Global variables are the one that are defined and declared outside a function and we need
to use them inside a function.
• # This function uses global variable s
def f():
print s

# Global scope
s = “Python is easier to learn"
f()

MODULES
• Allows user to logically organize Python code.
• Grouping related code into a module makes the code easier to understand and use.
• A module is a Python object with arbitrarily named attributes that user can bind and
reference.
• Simply, a module is a file consisting of Python code.
• A module can define functions, classes and variables. A module can also include runnable
code.
FILE
• What is a file?
– File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
• A file operation takes place in the following order.
– Open a file
– Read or write (perform operation)
– Close the file
• Open a file
• Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
• f = open("[Link]",'w') # write in text mode

• How to close a file Using Python?


• Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
• [Link]()

File Operations
• Syntax
• file object = open(file_name [, access_mode][, buffering]) Here are parameter details −
– file_name − Name of the file to be opened
– access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. This is optional parameter and the default file
access mode is read (r).
– buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the
indicated buffer size. If negative, the buffer size is the system default(default
behavior).
Access Modes
• r-
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
• rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
• r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
• rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
• wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
• a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
• ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
• w
• Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
• wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
• w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
• a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
• ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Ex:
#a file named "test1", will be opened with the reading mode.

file1 = open('[Link]', 'r')


print([Link]())

# This will print every line one by one in the file


for each in file1:
print (each)

# Read file Linewise


print([Link]())

#closing a file
[Link]()

You might also like