2. Unit 1 - Basics of Python(Duplicate)
2. Unit 1 - Basics of Python(Duplicate)
Basics of Python
Programming
1
Features of Python
• Simple • Embeddable
• Easy to Learn • Extensive
• Versatile • Easy maintenance
• Free and Open Source • Secure
• High-level Language • Robust
• Interactive • Multi-threaded
• Portable • Garbage Collection
• Object Oriented
• Interpreted
• Dynamic
2
• Extensible
History of Python
• Python was developed by Guido van Rossum in the late 1980’s and early 1990’s at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
• It has been derived from many languages like ABC, Modula-3, C, C++, Algol-68,
SmallTalk, UNIX Shell and other scripting languages.
• Its version 1.0 was released in 1991, which introduced several new functional
programming tools. While version 2.0 included list comprehensions and was released
in 2000 by the BeOpen Python Labs team.
• Python 2.7 is supported till 2020 and concentrate further development of Python 3.
Currently 3.11.8 is readily available. The newer versions have better features like
flexible string representations, etc.
• Although Python is copyrighted, its source code is available under the GNU General
3
• The strength of Python can be understood from the fact that this programming
language is the most preferred language of companies, such as Nokia, Google,
and YouTube, as well as NASA for its easy syntax.
• Python has become an ideal choice for the programmers. Based on the data from
Google Trends and other relevant websites, Python is amongst the top five most
preferred languages in academics as well as in industry.
• The best part is that more and more companies have started using Python for a7
broader range of applications ranging from social networks, through automation
to science calculations.
DIFFERENCE BETWEEN C AND PYTHON
Metrics Python C
Python is an interpreted, high-level, C is a general-purpose, procedural
Introduction
general-purpose programming language. computer programming language.
Interpreted programs execute slower as Compiled programs execute faster as
Speed
compared to compiled programs. compared to interpreted programs.
Python is a General-Purpose
Applications C is generally used for hardware
programming language.
related applications.
Built-in functions Python has a large library of built- C has a limited number of built-in
in functions. functions.
9
Implementing Data Structures Gives ease of implementing data Implementing data structures
structures with built-in insert, requires its functions to be
FUNCTION RENAMING EXAMPLE:
def mul_two_add_three(number):
print(number*2+3)
def mul_x_add_y(number,x,y):
print(number*x+y)
def bananas(number,x,y): mul_x_add_y(number,x,y):
print(number*x+y)
bananas(1,3,1)
mul_x_add_y(1,3,1)
Python34 (or move to the directory where you have saved Python) then type python
program_name.py.
Variables and Identifiers
Variable means its value can vary. You can store any piece of information in a
variable. Variables are just parts of your computer’s memory where information is
stored. To be identified easily, each variable is given an appropriate name.
Identifiers are names given to identify something. This something can be a variable,
function, class, module or other object. For naming any identifier, there are some
basic rules like:
• The first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
• The rest of the identifier name can be underscores ('_'), letters (upper or
lowercase), or digits (0-9).
12
• Identifier names are case-sensitive. For example, myvar and myVar are not the
same.
© Oxford University Press 2017. All rights reserved. 13
Assigning or Initializing Values to Variables
In Python, programmers need not explicitly declare variables to reserve memory space.
The declaration is done automatically when a value is assigned to the variable using the
equal sign (=). The operand on the left side of equal sign is the name of the variable and
the operand on its right side is the value to be stored in that variable.
Example: a=10
b=20
c=30
14
Input Operation
To take input from the users, Python makes use of the input() function. The input()
function prompts the user to provide some information on which the program can
work and give the result. However, we must always remember that the input function
takes user’s input as a string.
Exampl
e:
15
Comments
Comments are the non-executable statements in a program. They are just added to
describe the statements in the program code. Comments make the program easily
readable and understandable by the programmer as well as other users who are
seeing the code. The interpreter simply ignores the comments.
In Python, a hash sign (#) that is not inside a string literal begins a comment. All
characters following the # and up to the end of the line are part of the comment
Exampl
e:
16
Indentation
Whitespace at the beginning of the line is called indentation. These whitespaces or the
indentation are very important in Python. In a Python program, the leading whitespace
including spaces and tabs at the beginning of the logical line determines the
indentation level of that logical line.
Exampl
e:
17
TOKENS
• TOKENS ARE SMALL
UNITS OF A
PROGRAMMING
LANGUAGE. PYTHON
SUPPORTS TOKENS AS
MENTIONED.
• Sets
• Frozen set
• set
'5.333'
>>> PRINT('WHAT'S YOUR NAME?’)
HELLO ALL
>>> FORMAT('HELLO','<30')
'HELLO '
>>> FORMAT('HELLO','>30')
' HELLO'
>>> FORMAT('HELLO','^30')
23
' HELLO
>>> str=hello
traceback (most recent call last):
file "<pyshell#75>", line 1, in <module>
str=hello
nameerror: name 'hello' is not defined
>>> str="hello"
>>> print(str.lower())
hello
>>> print(str.upper())
HELLO
>>> print("hello" *5)
24
hellohellohellohellohello
>>> X=10+20J
>>> Y=10.5+2.3J
>>> TYPE(X)
<CLASS 'COMPLEX'>
>>> X+Y
(20.5+22.3J)
>>> X_Y
X_Y
>>> X-Y
(-0.5+17.7J)
>>> X/Y
(1.3069066989787086+1.6184871040332351J)
25
>>> A.REAL
10
>>> True+True
2
>>> True+False
1
>>> b=True
>>> type(b)
<class 'bool'>
>>> a=10
>>> b=20
>>> c=a<b
>>> print(c)
True
26
Arithmetic Operators
27
28
Comparison Operators
29
EXAMPLES
>>> print(a==b)
false
>>> print(a!=b)
true
>>> print(a>=b)
false
>>> print(a<=b)
true
>>> print(a<b)
true
>>> print(a>b)
false 30
Unary Operators
Unary operators act on single operands. Python supports unary minus operator. Unary
minus operator is strikingly different from the arithmetic operator that operates on
two operands and subtracts the second operand from the first operand. When an
operand is preceded by a minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary
minus operator. Similarly, if the number is negative, it becomes positive after applying
the unary minus operator. Consider the given example.
b = 10 a = -(b)
The result of this expression, is a = -10, because variable b has a positive value. After
applying unary minus operator (-) on the operand b, the value becomes -10, which
31
indicates it as a negative value.
EXAMPLES
>>> a=(b)
>>> a=b
>>> print(a)
200
>>> a=-(b)
>>> print(a)
-200
>>> b=-200
>>> print(a)
-200
>>> a=-(b)
>>> print(a)
32
200
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level. These
operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators. Bitwise
operators expect their operands to be of integers and treat them as a sequence of bits.
The truth tables of these bitwise operators are given below.
33
EXAMPLES
>>> ~12
-13
>>> ~2
-3
>>> 12&13
12
>>> 12|13
13
>>> 12^13
1 34
Shift Operators
Python supports two bitwise shift operators. They are shift left (<<) and shift right
(>>). These operations are used to shift bits to the left or to the right. The syntax for
aExampl
shift operation can be given as follows:
es: If we have X = 0001 1101,
then
X << 4 gives result = 1101
0000
>
> 35
EXAMPLES:
>>> 10<<2
40
>>> 13,,3
SYNTAXERROR: INVALID SYNTAX
>>> 13<<3
104
>>> 13>>3
1
>>> 8>>3
1
>>>
36
PYTHON TERNARY OPERATOR
• the PYTHON ternary operator determines if a condition is true or false and then returns
the appropriate value in accordance with the result. the ternary operator is useful in
cases where we need to assign a value to a variable based on a simple condition, and
we want to keep our code more concise — all in just one line of code
• Syntax: [on_true] if [expression] else [on_false]
Example:
a if a<b else b
a if a<b and a<c else b if b<c else c
a if a>b and a>c else b if b>c else c
37
Logical Operators
Logical AND (&&) operator is used to simultaneously evaluate two conditions or
expressions with relational operators. If expressions on both the sides (left and right
side) of the logical operator are true, then the whole expression is true. For example, If
we have an expression (a>b) && (b>c), then the whole expression is true only if both
expressions are true. That is, if b is greater than a and c.
Logical OR (||) operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If one or both the expressions of the logical operator is true,
then the whole expression is true. For example, If we have an expression (a>b) || (b>c),
then the whole expression is true if either b is greater than a or b is greater than c.
Logical not (!) operator takes a single expression and negates the value of the
expression. Logical NOT produces a zero if the expression evaluates to a non-zero value
38
and produces a 1 if the expression produces a zero. In other words, it just reverses the
value of the expression. For example, a = 10, b b = !a; Now, the value of b = 0. The value
EXAMPLES
>>> a<8 and b<2
false
>>> a<8 or b<2
true
>>> x=true
>>> print(x)
true
>>> not x
false
39
Membership and Identity Operators
Python supports two types of membership operators–in and not in. These operators,
test for membership in a sequence such as strings, lists, or tuples.
in Operator: The operator returns true if a variable is found in the specified sequence
and false otherwise. For example, a in nums returns 1, if a is a member of nums.
not in Operator: The operator returns true if a variable is not found in the specified
sequence and false otherwise. For example, a not in nums returns 1, if a is not a
member of nums.
Identity Operators
is Operator: Returns true if operands or values on both sides of the operator point to
the same object and false otherwise. For example, if a is b returns 1, if id(a) is same as
40
id(b).
is not Operator: Returns true if operands or values on both sides of the operator does
EXAMPLES
>>> a=10
>>> b=10
>>> print(a is b)
True
>>> print(a is not b)
False
>>> id(a)
1977113668176
>>> id(b)
1977113668176
c=13
>>> print(a is c)
False 41
Exampl
es:
44
Slice Operations on Strings
You can extract subsets of strings by using the slice operator ([ ] and [:]). You need to
specify index or the range of index of characters to be extracted. The index of the first
character is 0 and the index of the last character is n-1, where n is the number of
characters in the string.
If you want to extract characters starting from the end of the string, then you must
Exampl
specify the index as a negative number. For example, the index of the
on is easy !!!last character is -
es: !
1.
Pytho
python is easy !!!python is
easy !!!
python is easy !!!is in it?
45
EXAMPLES
>>> str1="hello world"
>>> print(str1[::-1])
dlrow olleh
>>> print('new''line’)
New line
>>> print(r"\nhello")
\nhello
>>> print(max("what are you"))
y
>>> print('welcome to python progrmming'.replace('o','*',3))
welc*me t* pyth*n progrmming
46
>>> print('welcome to python progrmming'.replace('o','*',3))
welc*me t* pyth*n progrmming
>>> print('*'.join('abcd'))
a*b*c*d
>>>line1="And then there were None"
>>> line2="famous in love"
>>> line3="famous were the kol and klus"
>>> line4=line1+line2+line3
>>> print(line1.find('were'),line4.count('And'))
15 1
47
>>> txt="cvr college of engineering“
>>> x=txt.capitalize()
>>> print(x)
cvr college of engineering
>>> x=txt.casefold()
>>> print(x)
cvr college of engineering
>>> x=txt.center(20)
>>> print(x)
cvr college of engineering
49
>>> print(txt.index('welcome'))
31
>>> print(txt.isalnum())
false
>>> txt="cvr college of engineering !!! welcome to cvr12"
>>> print(txt.isalnum())
false
>>> print(txt.isalpha())
false
>>> print(txt.isdigit())
false
>>> print(txt.islower())
true
>>> print(txt.isupper())
false
50
>>> print(txt.isspace())
false
>>> print(txt.isspace())
false
>>> txt=" cvr college of engineering !!! welcome to cvr12"
>>> x=txt.lstrip()
>>> print(x)
cvr college of engineering !!! welcome to cvr12
>>> txt1=" banana "
>>> x=txt1.lstrip()
>>> print(x)
banana
51
>> print("of all fruits",x,"is my fav")
of all fruits banana is my fav
>>> txt.split()
['cvr', 'college', 'of', 'engineering', '!!!', 'welcome', 'to', 'cvr12']
>>> txt="10"
>>> x=txt.zfill(5)
>>> print(x)
00010
>>> x="*".join(txt)
>>> print(x)
1*0 52
>>> print("%".join(txt1))
>>> txt="i like ds-a"
>>> print(x.replace("ds-a","ds-b"))
1*0
>>> print(txt.replace("ds-a","ds-b"))
i like ds-b
53
Lists
Lists are the most versatile data type of Python language. A list consist of items
separated by commas and enclosed within square brackets. The values stored in a list
are accessed using indexes. The index of the first element being 0 and n-1 as that of the
last element, where n is the total number of elements in the list. Like strings, you can
also use the slice, concatenation and repetition operations on lists.
Exampl
es:
54
1. Insertion Order Is Preserved
2. Heterogeneous Objects Are Allowed
3. Duplicates Are Allowed
4. Growable In Nature
5. Values Should Be Enclosed Within Square Brackets.
55
Tuples
A tuple is similar to the list as it also consists of a number of values separated by
commas and enclosed within parentheses. The main difference between lists and tuples
is that you can change the values in a list but not in a tuple. This means that while tuple
is a read only data type, the list is not.
Exampl
tuple data type is exactly same as list data type except that it is immutable.i.e we cannot chage
es:
values.
56
EXAMPLE:
T=(10,20,30,40)
Type(t)
T[0]=100
Typeerror: 'Tuple' Object Does Not Support Item Assignment
57
SET DATA TYPE:
• If We Want To Represent A Group Of Values Without Duplicates Where Order Is Not Important
Then We Should Go For Set Data Type.
1. Insertion Order Is Not Preserved
2. Duplicates Are Not Allowed
3. Heterogeneous Objects Are Allowed
4. Index Concept Is Not Applicable
5. It Is Mutable Collection
6. Growable In Nature
58
EXAMPLE:
>>> s={200,0,20,100,20.5,'cvr'}
>>> s
{0, 100, 20, 'cvr', 20.5, 200}
>>> s[0]
traceback (most recent call last):
file "<pyshell#2>", line 1, in <module>
s[0]
typeerror: 'set' object is not subscriptable
59
>>> S.ADD(60)
>>> S
{0, 100, 20, 'CVR', 20.5, 200, 60}
>>> S.REMOVE(100)
>>> S
{0, 20, 'CVR', 20.5, 200, 60}
>>> x=[10,20,30,40]
>>> b=byte(x)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
b=byte(x)
NameError: name 'byte' is not defined
62
>>> bytes(x)
b'\n\x14\x1e('
>>> print(x[0])
10
>>> print(x[1])
20
>>> print(x[-1])
40
>>> b=bytes(x)
>>> b[0]=100
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
b[0]=100
TypeError: 'bytes' object does not support item assignment
63
byte array data type
• byte array is exactly same as bytes data type except that its elements can be modified.
• This byte array() function returns a byte array object that contains the array of bytes from the input
source.
• Example:
>>> x=[10,20,30,40]
>>> b=bytearray(x)
>>> for i in b:
print(i)
10
20 64
30
>>> b[0]=100
>>> for i in b:
print(i)
100
20
30
40
65
Dictionary
Python’s dictionaries stores data in key-value pairs. The key values are usually strings
and value can be of any data type. The key value pairs are enclosed with curly braces
({ }). Each key value pair separated from the other using a colon (:). To access any value
in the dictionary, you just need to specify its key in square braces ([]).Basically
dictionaries
Exampl are used for fast retrieval of data
e:
66
Type Conversion
In Python, it is just not possible to complete certain operations that involves different
types of data. For example, it is not possible to perform "2" + 4 since one operand is an
Exampl and the other is of string type.
integer
e:
67
Type Casting vs Type Coercion
we have done explicit conversion of a value from one data type to another. This is
known as type casting.
However, in most of the programming languages including Python, there is an implicit
conversion of data types either during compilation or during run-time. This is also
known type coercion. For example, in an expression that has integer and floating point
numbers (like 21 + 2.1 gives 23.1), the compiler will automatically convert the integer
into floating point number so that fractional part is not lost.
68
x = 2 # int
y = 4.8 # float
z = 10j # complex
print(a)
print(b)
print(c)
69
>>> int(123.897)
123
>>> int(10+50j)
traceback (most recent call last):
file "<pyshell#1>", line 1, in <module>
int(10+50j)
typeerror: can't convert complex to int
>>> int(true)
1
>>> int(false)
0
70
>>> int("10")
10
>>> float(10+5j)
traceback (most recent call last):
file "<pyshell#7>", line 1, in <module>
float(10+5j)
typeerror: can't convert complex to float
>>> float(true)
1.0
>>> float("10")
10.0
>>> complex(10)
(10+0j)
>>> complex(10.5)
(10.5+0j)
>>> complex("10")
71
(10+0j)
>>> complex(true)
• BOOL:
>>> bool(0)
false
>>> bool(1)
true
>>> bool(10)
true
>>> bool(10.5)
true
>>> bool(0+10.5j)
true
>>> bool("true")
true
72
>>> complex(10)
(10+0j)
>>> complex(10.5)
(10.5+0j)
>>> complex("10")
(10+0j)
>>> complex(true)
(1+0j)
73
>>> str(10)
'10'
>>> str(105)
'105'
>>> str(10.5)
'10.5'
>>> str(10+5j)
'(10+5j)'
>>> str(true)
'true'
74
Here Are Two Types Of Type Conversion In Python.
Implicit Conversion - Automatic Type Conversion
Explicit Conversion - Manual Type Conversion
Python Implicit Type Conversion
Python Automatically Converts One Data Type To Another. This Is Known As Implicit Type Conversion.
Python Promotes The Conversion Of The Lower Data Type (Integer) To The Higher Data Type (Float) To
Avoid Data Loss.
EXAMPLE:
integer_number = 123
float_number = 1.23
76
num_string = '12'
num_integer = 23
print("sum:",num_sum)
print("data type of num_sum:",type(num_sum))
77
SUMMARY ABOUT TYPE CASTING
1. Type Conversion Is The Conversion Of An Object From One Data Type To Another Data Type.
2. Implicit Type Conversion Is Automatically Performed By The Python Interpreter.
3. Python Avoids The Loss Of Data In Implicit Type Conversion.
4. Explicit Type Conversion Is Also Called Type Casting, The Data Types Of Objects Are
Converted Using Predefined Functions By The User.
5. In Type Casting, Loss Of Data May Occur As We Enforce The Object To A Specific Data Type.
78