Python Notes June
Python Notes June
Python is most widely used general purpose high level programming language like
Java, C, C++ etc. 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. Python is derived from many other languages, including ABC, Modula-3, C, C+
+, Algol-68, SmallTalk, and Unix shell and other scripting languages. Rossum was a fan of a
comedy series from late seventies. Python is named after a TV Comedy Show called ‘Monty
Python’s Flying Circus’ and not after Python-the snake. Python 3.13.5 is the latest version of
Python.
FEATURES OF PYTHON
• High level language - High-level language is any programming language that enables
development of a program in a much more user-friendly programming context and is
generally independent of the computer's hardware architecture. Like JAVA, C ,C++
Python is a Highlevel programming language.
• Interactive - We can actually sit at a Python prompt and interact with the interpreter
directly to write your programs and It allows interactive testing and debugging of
snippets of code.
• Portable - Python can run on a wide variety of hardware platforms like Windows,
Linux, MAC OS and has the same interface on all platforms. You can move Python
programs from one platform to another, and run it without any changes.
• Easy to Learn - Python has a simple syntax similar to the English language. This
makes python easier to learn. Python has syntax that allows developers to write
programs with fewer lines than some other programming languages. Most of other
high level languages like JAVA, C, C++ has so many syntactical constructs like
Punctuation marks, semicolon, braces etc to indicate the ending of a statement or to
identify block of code. But in Python, It has fewer syntactical constructions than
other languages.
For eg:
In JAVA
String name=”BOB”;
But
In Python
We write name=”BOB”
In JAVA,
int x=1;
x=(int)x/2;
In order to store integer values to a variable x first we have to declare its type as
int. it means that x always store integer values .In the first line we assign value 1 to
integer variable x.
If we take x=x/2; the value of x becomes ½. x can never equal 0.5. So first we have to
cast the result into type integer using (int) function. Now the result becomes 0.
In python,
x=1
x=x/2
In this case, Python itself take care of type management we don’t need to worry
about it.
If we write x=1 at this point type of x is int because we assign integer value to x. if we
write x=x/2 now x equals 0.5 and the type of x at this point is float. We don’t need
to explicitly type cast the result into float. According to the type of values we store to
a variable its type is decided by the interpreter at runtime. We don’t need to worry
about it.
• Large Community Support-Python was founded around 30 years ago and so it has a
vast community of efficient developers. These developers are constantly helping out
the beginners through their constant support and in-depth journals. There is plenty
of documentation and guides that the newbie programmers could learn and
enhance their Python.
Setting up of Environment
In order to use python first it must be installed on our computer, Follow these steps
1).Go to the Python website [Link] and click the Download menu choice.
3).When the download is completed, double-click the file and follow the instructions to
install it.
Type the following text at the Python prompt and press Enter –
>>>Hello, Python!
Using Script Mode, we can write our Python code in a separate file of any
editor in our Operating System. Let us write a simple Python program in a script.
Python files have the extension .py. Type the following source code in a [Link] file –
>>>Hello, Python!
• USING IDLE
When Python is installed, a program called IDLE is also installed along with it.
It provides graphical user interface to work with Python.
Open IDLE, copy the following code below and press enter.
>>>print("Hello, World!")
Or
print("Hello, World!")
Go to Run > Run module (Shortcut: F5) and we can see the output.
IDENTIFIERS
• Identifier is the name given to entities like class, functions, variables etc. in Python. It
helps differentiating one entity from another.
• An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly
fine.
>>> global = 1
global = 1
>>> a@ = 0
a@ = 0
^
• Python is a case-sensitive language. This means, Variable and variable are not the
same. Always name identifiers that make sense.
Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as variable
name, function name or any other identifier. They are used to define the syntax and
structure of the Python language. In Python, keywords are case sensitive. All the keywords
except True, False and None are in lowercase and they must be written as it is. The list of all
the keywords are given below.
Python does not use braces ({}) to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced. The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example −
if (True):
print ("True")
else:
print ("False")
Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the use
of the line continuation character (\) to denote that the line should continue. For example
−
total = item_one + \
item_two + \
item_three
The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string. The triple quotes are
used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
Comments in Python
In case user wants to specify a single line comment, then comment must start with #
eg: # This is single line comment.
Is
Multipline comment'''
For eg:
Variables
Variables are nothing but reserved memory locations to store values. It means that
when you create a variable, you reserve some space in the memory. Based on the data type
of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to the variables, you can
store integers, decimals or characters in these variables.
print (c)
print (m)
1000.0
John
Multiple Assignment
For example −
a=b=c=1
Here, an integer object is created with the value 1, and all the three variables are assigned
to the same memory location. We can also assign multiple objects to multiple variables.
For example −
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Number data types store numeric values. Number objects are created when you
assign a value to them. For example −
var1 = 1
We can also delete the reference to a number object by using the del statement.
The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement.
For example −
del var
Python Strings
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at
0 in the beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
OUTPUT:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
!
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists are
similar to arrays in C. One of the differences between them is that all the items belonging
to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
OUTPUT:
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parenthesis.
The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ( ( )
) and cannot be updated. Tuples can be thought of as read-only lists.
For example −
OUTPUT:
Python Dictionary
They work like associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]).
For example −
dict = {}
OUTPUT−
This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])
Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.
Set
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().It can have any number of items and they may
be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable
element, like list, set or dictionary, as its element.
For eg:
my_set = {1, 2, 3}
print(my_set) Output:{1,2,3}
print(my_set) Output:{1.0,”Hello”,(1,2,3)}
my_set = {1,2,3,4,3,2}
print(my_set) Output:{1,2,2,4}
my_set = {1, 2
my_set = set([1,2,3,2])
Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements we use the set() function without any argument.
For eg:
a = set()
*We cannot access or change an element of set using indexing or slicing. Set does not
support it. We can add single element using the add() method and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
For eg:
my_set = {1,3}
print(my_set) Output:{1,3}
my_set.add(2)
print(my_set) Output:{1,2,3}
my_set.update([2,3,4])
print(my_set) Output:{1,2,3,4}
my_set.update(((4,5), 1,6,8}))
*A particular item can be removed from set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not
exist in the set, it remains unchanged. But remove() will raise an error in such condition.
# initialize my_set
my_set = {1, 3, 4, 5, 6}
#discard an element
my_set.discard(4)
# remove an element
my_set.remove(6)
# discard an element
my_set.discard(2)
# remove an element
None is a data type of its own (NoneType) and only None can be None.
The None keyword is used to define a null value, or no value at all. None is not the same as
0, False, or an empty string
Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type-names as a function. There are several
built-in functions to perform conversion from one data type to another. These functions
return a new object representing the converted value.
1 int(x [,base])
2 float(x)
3 complex(real [,imag])
4 str(x)
5 repr(x)
6 eval(str)
7 tuple(s)
Converts s to a tuple.
8 list(s)
Converts s to a list.
9 set(s)
Converts s to a set.
10 dict(d)
11 frozenset(s)
12 chr(x)
13 unichr(x)
14 ord(x)
15 hex(x)
16 oct(x)
OPERATORS
Operators are the constructs, which can manipulate the value of operands.
Types of Operator
• Arithmetic Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Assume variable a holds the value 10 and variable b holds the value 21, then −
% Modulus Divides left hand operand by right hand operand and b%a=1
returns remainder
These operators compare the values on either side of them and decide the relation among
them. They are also called Relational operators.
Assume variable a holds the value 10 and variable b holds the value 20, then −
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.
Assume variable a holds the value 10 and variable b holds the value 20, then −
+= Add AND It adds right operand to the left operand and assign the c += a is
result to left operand equivalent
to c = c + a
-= Subtract AND It subtracts right operand from the left operand and c -= a is
assign the result to left operand equivalent
to c = c - a
/= Divide AND It divides left operand with the right operand and assign c /= a is
the result to left operand equivalent
to c = c /
ac /= a is
equivalent
to c = c / a
//= Floor It performs floor division on operators and assign value c //= a is
Division to the left operand equivalent
to c = c // a
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
Python's built-in function bin() can be used to obtain binary representation of an integer
number.
& Binary AND Operator copies a bit, to the result, if it exists in (a & b) (means
both operands 0000 1100)
<< Binary Left Shift The left operand's value is moved left by the a << = 240
number of bits specified by the right operand. (means 1111
0000)
>> Binary Right Shift The left operand's value is moved right by the a >> = 15
number of bits specified by the right operand. (means 0000
1111)
and Logical If both the operands are true then condition becomes (a and b)
AND true. is False.
not Logical NOT Used to reverse the logical state of its operand. Not (a
and b) is
True.
Identity operators compare the memory locations of two objects. There are two
Identity operators as explained below −
Operator Description Example
The following table lists all operators from highest precedence to the lowest.
1 **
2 ~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)
3 * / % //
4 +-
5 >> <<
6 &
Bitwise 'AND'
7 ^|
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators