0% found this document useful (0 votes)
7 views20 pages

Python Notes - Unit1

sfsfsf

Uploaded by

benim15823
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views20 pages

Python Notes - Unit1

sfsfsf

Uploaded by

benim15823
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

What is Python?

Python is a popular programming language. It was created by Guido van


Rossum, and released in 1991. Python is a case-sensitive language. Python
is named after the comedy television show Monty Python’s Flying Circus. Python is used
for software development at companies and organizations such as Google, Yahoo, CERN,
Industrial Light and Magic, and NASA. It is not named after the Python snake.
Python allows developers to build their applications using multiple
approaches, including both object-oriented programming and functional
programming.There are so many applications of Python, here are some of the them.

1. Web development – Web framework like Django and Flask are based on Python.
They help you write server side code which helps you manage database, write backend
programming logic, mapping urls etc.

2. Machine learning – There are many machine learning applications written in Python.
Machine learning is a way to write a logic so that a machine can learn and solve a
particular problem on its own. For example, products recommendation in websites like
Amazon, Flipkart, eBay etc. is a machine learning algorithm that recognises user’s
interest. Face recognition and Voice recognition in your phone is another example of
machine learning.

3. Data Analysis – Data analysis and data visualisation in form of charts can also be
developed using Python.

4. Scripting – Scripting is writing small programs to automate simple tasks such as


sending automated response emails etc. Such type of applications can also be written
in Python programming language.

5. Game development – Python is also used in the development of interactive games.


There are libraries such as PySoy which is a 3D game engine supporting Python
3, PyGame which provides functionality and a library for game development. Games
such as Civilization-IV, Disney’s Toontown Online, Vega Strike etc. have been built
using Python.

6. You can develop Embedded applications in Python.

7. Desktop applications – You can develop desktop application in Python using library
like TKinter or QT.

8. Scientific and Numeric Applications : Python has become a crucial tool in scientific
and numeric computing. In fact, Python provides the skeleton for applications that deal
with computation and scientific data processing. Apps like FreeCAD (3D modeling
software) and Abaqus (finite element method software) are coded in Python.
Features of Python programming language

1. Readable: Python is a very readable language.

2. Easy to Learn: Learning python is easy as this is a expressive and high level
programming language, which means it is easy to understand the language and thus
easy to learn.

3. Cross platform: Python is available and can run on various operating systems such
as Mac, Windows, Linux, Unix etc. This makes it a cross platform and portable
language.

4. Open Source: Python is a open source programming language.

5. Large standard library: Python comes with a large standard library that has some
handy codes and functions which we can use while writing code in Python.

6. Free: Python is free to download and use. This means you can download it for free
and use it in your application.. Python is an example of a FLOSS (Free/Libre Open
Source Software), which means you can freely distribute copies of this software, read its
source code and modify it.

7. Supports exception handling: An exception is an event that can occur during


program excution and can disrupt the normal flow of program. Python supports
exception handling which means we can write less error prone code and can test
various scenarios that can cause an exception later on.

8. Advanced features: Supports generators and list comprehensions. We will cover


these features later.
9. Automatic memory management: Python supports automatic memory
management which means the memory is cleared and freed automatically. You do not
have to bother clearing the memory.

Python Syntax as compared to other programming languages


• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.

• Python uses new lines to complete a command, as opposed to other


programming languages which often use semicolons or parentheses.

• Python relies on indentation, using whitespace, to define scope; such


as the scope of loops, functions and classes. Other programming
languages often use curly-brackets for this purpose.

Python Versions :

Python Version Released Date

Python 1.0 January 1994

Python 2.0 October 2000

Python 3.0 December 2008

Python 3.9 October 2020


How to Write first python program and execute it :

Best approach is to type the program into an editor, save the code you type to a file,
and then execute the program. Most of the time we use an editor to enter and run our
Python programs. The interactive interpreter is most useful for experimenting with
small snippets of Python code. There are two ways to write python program.

(i) enter the program directly into IDLE’s interactive shell

print("This is a simple Python program")

(ii) enter the program into IDLE’s editor, save it, and run it.

1. Select File->New to create a python program using editor.


2. Write program
print("This is a simple Python program")
3. Save the file with name first.py
4. Press F5 to execute the program.
Python Keywords : Keywords are the reserved words in Python.
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

Python Identifiers :
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another. Rules for naming identifiers :

✓ Identifiers must contain at least one character.


✓ The first character must be an alphabetic letter (upper or lower case) or the underscore
✓ The remaining characters (if any) may be alphabetic characters (upper or lower case),
the underscore, or a digit
✓ No other characters (special characters including spaces) are permitted in identifiers.
✓ A reserved word cannot be used as an identifier.

Python Data Types


Data types are the classification or categorization of data items. Since everything is an
object in Python programming, data types are actually classes and variables are
instance (object) of these classes.

Following are the standard or built-in data type of Python:


• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary

Numeric : In Python, numeric data type represent the data which has numeric value.
Numeric value can be integer, floating number or even complex numbers. These
values are defined as int, float and complex class in Python.

• Integers – This value is represented by int class. It contains positive or negative


whole numbers (without fraction or decimal). In Python there is no limit to how long
an integer value can be.
➢ Binary : A number starting with 0b or 0B in the combination of 0 and 1
represent the binary numbers in Python. For example, 0b11011000 is a binary
number equivalent to integer 216.

➢ Octal : A number having 0o or 0O as prefix represents an octal number. For


example, 0O12 is equivalent to integer 10.

➢ Hexadecimal: A number with 0x or 0X as prefix


represents hexadecimal number. For example, 0x12 is equivalent to integer
18.

• Float – This value is represented by float class. It is a real number with floating
point representation. It is specified by a decimal point. Optionally, the character e or
E followed by a positive or negative integer may be appended to specify scientific
notation.

• Complex Numbers – Complex number is represented by complex class. It is


specified as (real part) + (imaginary part)j. For example – 2 + 3j

type() function is used to determine the type of data type. For example
>>> type('abc')
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(3.2)
<class 'float'>
>>> type(3+4j)
<class 'complex'>
>>>

Built-in Functions
A numeric object of one type can be converted in another type using
the following functions:

Built-in Function Description

int Returns the integer object from a float or a string containing digits.

float Returns a floating-point number object from a number or string containing


digits with decimal point or scientific notation.

complex Returns a complex number with real and imaginary components.

hex Converts a decimal integer into a hexadecimal number with 0x prefix.

oct Converts a decimal integer in an octal representation with 0o prefix.

pow Returns the power of the specified numbers.

abs Returns the absolute value of a number without considering its sign.

round Returns the rounded number.

Sequence Type : In Python, sequence is the ordered collection of similar or different


data types. Sequences allows to store multiple values in an organized and efficient
fashion. There are several sequence types in Python –

• String
• List
• Tuple

String : In Python, Strings are arrays of bytes representing Unicode characters. A


string is a collection of one or more characters put in a single quote, double-quote or
triple quote. In python there is no character data type, a character is a string of length
one. It is represented by str class. In Python, individual characters of a String can be
accessed by using the method of Indexing. String index starts from 0. Indexing allows
negative address references to access characters from the back of the String, e.g. -1
refers to the last character, -2 refers to the second last character and so on.

Example :

str="HELLO"
print(str)
print(type(str))
#print first character of string
print(str[0])
#print last character of string
print(str[-1])
#print second last character of string
print(str[-2])

Output :
HELLO
<class 'str'>
H
O
L

String Operators
Obviously, arithmetic operators don't operate on strings. However,
there are special operators for string processing.

Operator Description Example


+ Appends the second string to the first >>> a='hello'
>>> b='world'
>>> a+b
'helloworld'
* Concatenates multiple copies of the same string >>> a='hello'
>>> a*3
'hellohellohello'
[] Returns the character at the given index >>> a = 'Python'
>>> a[2]
t
[:] Fetches the characters in the range specified by two >>> a = 'Python'
index operands separated by the : symbol >>> a[0:2]
'Py'
in Returns true if a character exists in the given string >>> a = 'Python'
>>> 'x' in a
False
>>> 'y' in a
True
>>> 'p' in a
False
not in Returns true if a character does not exist in the given >>> a = 'Python'
string >>> 'x' not in a
True
>>> 'y' not in a
False
String Methods
Method Description

str.capitalize() Returns the copy of the string with its first character capitalized and the rest of the
letters are in lowercased.

string.casefold() Returns a lowered case string. It is similar to the lower() method, but the casefold()
method converts more characters into lower case.

string.center() Returns a new centered string of the specified length, which is padded with the
specified character. The deafult character is space.

string.count() Searches (case-sensitive) the specified substring in the given string and returns an
integer indicating occurrences of the substring.

string.endswith() Returns True if a string ends with the specified suffix (case-sensitive), otherwise returns
False.

string.expandtabs() Returns a string with all tab characters \t replaced with one or more space, depending
on the number of characters before \t and the specified tab size.

string.find() Returns the index of the first occurence of a substring in the given string (case-
sensitive). If the substring is not found it returns -1.

string.index() Returns the index of the first occurence of a substring in the given string.

string.isalnum() Returns True if all characters in the string are alphanumeric (either alphabets or
numbers). If not, it returns False.

string.isalpha() Returns True if all characters in a string are alphabetic (both lowercase and uppercase)
and returns False if at least one character is not an alphabet.

string.isascii() Returns True if the string is empty or all characters in the string are ASCII.

string.isdecimal() Returns True if all characters in a string are decimal characters. If not, it returns False.

string.isdigit() Returns True if all characters in a string are digits or Unicode char of a digit. If not, it
returns False.

string.isidentifier() Checks whether a string is valid identifier string or not. It returns True if the string is a
valid identifier otherwise returns False.

string.islower() Checks whether all the characters of a given string are lowercased or not. It returns True
if all characters are lowercased and False even if one character is uppercase.

string.isnumeric() Checks whether all the characters of the string are numeric characters or not. It will
return True if all characters are numeric and will return False even if one character is
Method Description

non-numeric.

string.isprintable() Returns True if all the characters of the given string are Printable. It returns False even if
one character is Non-Printable.

string.isspace() Returns True if all the characters of the given string are whitespaces. It returns False
even if one character is not whitespace.

string.istitle() Checks whether each word's first character is upper case and the rest are in lower case
or not. It returns True if a string is titlecased; otherwise, it returns False. The symbols
and numbers are ignored.

string.isupper() Returns True if all characters are uppercase and False even if one character is not in
uppercase.

string.join() Returns a string, which is the concatenation of the string (on which it is called) with the
string elements of the specified iterable as an argument.

string.ljust() Returns the left justified string with the specified width. If the specified width is more
than the string length, then the string's remaining part is filled with the specified fillchar.

string.lower() Returns the copy of the original string wherein all the characters are converted to
lowercase.

string.lstrip() Returns a copy of the string by removing leading characters specified as an argument.

string.maketrans() Returns a mapping table that maps each character in the given string to the character in
the second string at the same position. This mapping table is used with the translate()
method, which will replace characters as per the mapping table.

string.partition() Splits the string at the first occurrence of the specified string separator sep argument
and returns a tuple containing three elements, the part before the separator, the
separator itself, and the part after the separator.

string.replace() Returns a copy of the string where all occurrences of a substring are replaced with
another substring.

string.rfind() Returns the highest index of the specified substring (the last occurrence of the
substring) in the given string.

string.rindex() Returns the index of the last occurence of a substring in the given string.

string.rjust() Returns the right justified string with the specified width. If the specified width is more
than the string length, then the string's remaining part is filled with the specified fill
char.
Method Description

string.rpartition() Splits the string at the last occurrence of the specified string separator sep argument
and returns a tuple containing three elements, the part before the separator, the
separator itself, and the part after the separator.

string.rsplit() Splits a string from the specified separator and returns a list object with string elements.

string.rstrip() Returns a copy of the string by removing the trailing characters specified as argument.

string.split() Splits the string from the specified separator and returns a list object with string
elements.

string.splitlines() Splits the string at line boundaries and returns a list of lines in the string.

string.startswith() Returns True if a string starts with the specified prefix. If not, it returns False.

string.strip() Returns a copy of the string by removing both the leading and the trailing characters.

string.swapcase() Returns a copy of the string with uppercase characters converted to lowercase and vice
versa. Symbols and letters are ignored.

string.title() Returns a string where each word starts with an uppercase character, and the remaining
characters are lowercase.

string.translate() Returns a string where each character is mapped to its corresponding character in the
translation table.

string.upper() Returns a string in the upper case. Symbols and numbers remain unaffected.

string.zfill() Returns a copy of the string with '0' characters padded to the left. It adds zeros (0) at
the beginning of the string until the length of a string equals the specified width
parameter.

Python Input, Output


two built-in functions print() and input() are used to perform I/O task in Python.
Python Output Using print() function :
Syntax of the print() function :

print(objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.


The sep separator is used between the values. defaults is space character.
After all values are printed, end value is printed. defaults is a new line.
The file is the object where the values are printed and its default value
is sys.stdout (screen).

>>> print('Welcome')
Welcome
>>> a=5
>>> print(a)
5
>>> print(type(a))
<class 'int'>
>>> a="hello"
>>> print(a)
hello
>>> print(type(a))
<class 'str'>
>>> a=5
>>> b=4
>>> print(a,b)
54
>>> print(a,b,sep="#")
5#4
>>> print(a,b,sep="#",end="&")
5#4&
>>> c=6
>>> print(a,b,c,sep=",")
5,4,6
>>> print("Value of a : ",a)
Value of a : 5
>>> print("Value of a and b : ",a,b)
Value of a and b : 5 4

Output formatting : This can be done by using


the str.format() method. This method is visible to any string object
>>> a=4; b=6
>>> print("Value of a is {} and Value of b is {}".format(a,b))
Value of a is 4 and Value of b is 6
>>>
The curly braces {} are used as placeholders. We can specify the order in
which they are printed by using numbers (tuple index).

>>> a=1
>>> b=2
>>> print("A={} and B={}".format(a,b))
A=1 and B=2
>>> print("B={1} and A={0}".format(a,b))
B=2 and A=1
>>> print("A={} and B={} and A={}".format(a,b))
IndexError: tuple index out of range
>>> print("A={0} and B={1} and A={0}".format(a,b))
A=1 and B=2 and A=1
>>>

Control codes within Strings : \n \t \b \a \f


Escape character \ can be used to escape the meaning of special characters in string.

Python Input : In Python, input() method is used to take input from

user.

Syntax : input([prompt])

Note : By default input method read string and store in variable. To perform calculations we need to
convert them in numeric value by using int() and float() methods.
>>> a=input('Input a Value : ')
Input a Value : 23
>>> print(a)
23
>>> print(type(a))
<class 'str'>

Q. Write a program to input two numbers and print sum.

a=int(input('Input first number : '))


b=int(input('Input second number : '))
c=a+b
print('Sum is ',c)

Eval Function : if we wish x to be of type integer if the user enters 2 and x to be floating point if the user enters
2.0? Python provides the eval function that attempts to evaluate a string

Exercise
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))

Q. Write a program to input two real numbers and print sum.

a=float(input('Input first number : '))


b=float(input('Input second number : '))
c=a+b
print('Sum is {:.2f} '.format(c))

Python - Basic Operators


Types of Operator
Python language supports the following types of operators.

• Arithmetic Operators : + - * / % ** (a power b) // (floor division)


• Comparison (Relational) Operators : < <= > >= == !=
• Assignment Operators = += -= *= /= %= **= //=
• Logical Operators and or not
• Bitwise Operators
• Membership Operators
• Identity Operators

(i) Arithmetic Operators :


Assume a=10 and b=20

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.
* Multiplies values on either side of the operator a * b = 200
Multiplication

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on a**2 =100


operators

// Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 =
result is the quotient in which the digits after the 4.0, -11//3 = -4, -
decimal point are removed. But if one of the 11.0//3 = -4.0
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity) −

BITWISE OPERATORS

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits


<< Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost bit in from
right shift the left, and let the rightmost bits fall off

Python Identity Operators : Identity operators are used to


compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:

Operator Description Example

is Returns True if both variables are x is y


the same object

is not Returns True if both variables are x is not y


not the same object

Python Membership Operators : Membership


operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with x in y


the specified value is present in
the object
not in Returns True if a sequence with
the specified value is not present
in the object

Memory Management in Python


Memory allocation is important part in any software development to write
memory efficient code. Memory allocation can be defined as allocating a block
of space in the computer memory to a program. In Python memory allocation
and deallocation method is automatic as the Python developers created
a garbage collector for Python so that the user does not have to do manual
garbage collection.

Garbage Collection is a process in which the interpreter frees up the memory


when not in use to make it available for other objects.
Reference Counting : Reference counting works by counting the number of
times an object is referenced by other objects in the system. When references
to an object are removed, the reference count for an object is decremented.
When the reference count becomes zero, the object is deallocated.

For Example :

x = 20 #When we assign the value to the x. the integer object 20 is created in the
Heap memory and its reference is assigned to x.

y = x

It means the y object will refer to the same object because Python allocated the same
object reference to new variable if the object is already exists with the same value.
if id(x) == id(y):
print("x and y refer to the same object")

x += 1

In this case two objects will be there x will be pointing to 21 Object and y will be
pointing to 20 object.

If id(x) == id(y):
print("x and y do not refer to the same object")

>>> a=1
>>> id(a)
1797707952
>>> b=a
>>> id(a)
1797707952
>>> a=a+1
>>> id(a)
1797707968
>>> id(b)
1797707952
>>>del a # to delete a object reference

Python Memory Allocation


Memory allocation is an essential part of the memory management for a developer.
This process basically allots free space in the computer's virtual memory, and there are
two types of virtual memory works while executing programs.

o Static Memory Allocation

o Dynamic Memory Allocation


Static Memory Allocation : Static memory allocation happens at the compile time.
The Stack data structure is used to store the static memory. It is only needed inside
the particular function or method call. Call stack (stack data structure) holds the
program's operational data such as subroutines or function call in the order they are to
be called.

Dynamic Memory Allocation : Dynamic memory allocates the memory at the runtime
to the program. Memory is allocated to the objects at the run time. We use
the Heap for implement dynamic memory management. everything in Python is an
object means dynamic memory allocation inspires the Python memory management.
Python memory manager automatically vanishes when the object is no longer in use.

You might also like