0% found this document useful (0 votes)
1 views78 pages

2. Unit 1 - Basics of Python(Duplicate)

The document provides an overview of Python programming, covering its features, history, limitations, applications, and future prospects. It compares Python with C, discusses basic programming concepts such as variables, data types, and operators, and includes examples of Python syntax. Additionally, it explains how to write and execute Python programs, emphasizing the language's simplicity and versatility.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views78 pages

2. Unit 1 - Basics of Python(Duplicate)

The document provides an overview of Python programming, covering its features, history, limitations, applications, and future prospects. It compares Python with C, discusses basic programming concepts such as variables, data types, and operators, and includes examples of Python syntax. Additionally, it explains how to write and execute Python programs, emphasizing the language's simplicity and versatility.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

UNIT 1

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

Public License (GPL). Python is currently maintained by a core development team at


Limitations of Python
Parallel processing can be done in Python but not as elegantly as done in some other
languages (like JavaScript and Go Lang).
• Being an interpreted language, Python is slow as compared to C/C++. Python is not a
very good choice for those developing a high-graphic 3d game that takes up a lot of CPU.
• It lacks true multiprocessor support.
• It has very limited commercial support point.
• Python is slower than C or C++ when it comes to computation heavy tasks and desktop
applications.
• It is difficult to pack up a big Python application into a single executable file. This
makes it difficult to distribute Python to non-technical.
4
Applications of Python
• Embedded scripting language: Python is used as an embedded scripting language for
various testing/ building/ deployment/ monitoring frameworks, scientific apps, and
quick scripts.
• 3D Software: 3D software like Maya uses Python for automating small user tasks, or
for doing more complex integration such as talking to databases and asset
management systems.
• Web development: Python is an easily extensible language that provides good
integration with database and other web standards.
GUI-based desktop applications: Simple syntax, modular architecture, rich text
processing tools and the ability to work on multiple operating systems makes Python a
preferred choice for developing desktop-based applications.
• Image processing and graphic design applications: Python is used to make 2D 5
Applications of Python
• Scientific and computational applications: Features like high speed, productivity and
availability of tools, such as Scientific Python and Numeric Python, have made Python a
preferred language to perform computation and processing of scientific data. 3D
modeling software, such as FreeCAD, and finite element method software, like Abaqus,
are coded in Python.
Games: Python has various modules, libraries, and platforms that support development
of games. Games like Civilization-IV, Disney's Toontown Online, Vega Strike, etc. are
coded using Python.
• Enterprise and business applications: Simple and reliable syntax, modules and
libraries, extensibility, scalability together make Python a suitable coding language for
6
customizing larger applications. For example, Reddit which was originally written in
Common Lips, was rewritten in Python in 2005. A large part of Youtube code is also
The Future of Python
• Python has a huge user base that is constantly growing. It is a stable language
that is going to stay for long time.

• 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.

• Python is a high-speed dynamic language. It works well in applications like photo


development and has been embedded in programs such as GIMP and Paint Shop
Pro.

• 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.

It is easier to write a code in Python as


Usage the number of lines is less
comparatively. Program syntax is harder than Python.

There is no need to declare the type of


In C, the type of a variable must be
variable. Variables are untyped in
declared when it is created, and only
Declaration of variables Python. A given variable can be stuck on
values of that type must be assigned to
values of different types at different
it.
times during the program execution

Error debugging is simple. This means it In C, error debugging is difficult as it is


takes only one in instruction at a time a compiler dependent language. This
Error Debugging and compiles and executes means that it takes the entire source
8
simultaneously. Errors are shown code, compiles it and then shows all the
instantly and the execution is stopped, at errors.
that instruction.
Supports function renaming C does not support function
mechanism i.e, the same renaming mechanism. This
Function renaming mechanism
function can be used by two means the same function cannot
different names. be used by two different names.

Complexity Syntax of Python programs is The syntax of a C program is


easy to learn, write and read. harder than Python.
Python uses an automatic

In C, the Programmer has to do


garbage collector for memory
Memory-management memory management on their
management.
own.

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)

© Oxford University Press 2017. All rights reserved. 10


Writing and Executing First Python Program
Download Python from www.Python.org
Once installed, the Python console can be accessed in several ways.
First, using the command line and running the Python interpreter directly.
Second, using a GUI software that comes installed with Python called Python’s Integrated
Development and Learning Environment (IDLE).

Writing Python Programs & Executing it


Step 1: Open an editor.
Step 2: Write the instructions
Step 3: Save it as a file with the filename having the extension .py.
Step 4: Run the interpreter with the command python program_name.py or use IDLE to run the
programs.
To execute the program at the command prompt, simply change your working directory to C:\ 11

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.

© Oxford University Press 2017. All rights reserved. 18


• LITERAL CONSTANT:
• THE WORD LITERAL HAS BEEN DERIVED FROM LITERALLY.THE VALUE OF A
LITERAL CONSTANT CAN BE USED DIRECTLY IN PROGRAMS.
• EXAMPLE:7,3.9,’A’, AND “HELLO” ARE LITERAL CONSTANTS.

© Oxford University Press 2017. All rights reserved. 19


DATA TYPES
NUMERIC TYPES:
• int
• float
• Complex
Ex:a=57
Float types:
Eg:Num=55.678
Complex type
a+bi form
Eg:3+2j
20
Sequences in python:
• Str
• Bytes
• Bytearray
• List
• Tuple
• Range

• Sets
• Frozen set
• set

© Oxford University Press 2017. All rights reserved. 21


DATATYPES EXAMPLES
>>> FLOAT(1)/FLOAT (3)
0.3333333333333333
>>> FORMAT("FLOAT(1)/FLOAT(3)",'.2F')
TRACEBACK (MOST RECENT CALL LAST):
FILE "<PYSHELL#63>", LINE 1, IN <MODULE>
FORMAT("FLOAT(1)/FLOAT(3)",'.2F')
VALUEERROR: UNKNOWN FORMAT CODE 'F' FOR OBJECT OF TYPE 'STR'
>>> FORMAT(FLOAT(1)/FLOAT(3),".2F")
'0.33'
>>> FORMAT(FLOAT(16)/FLOAT(3),".3F") 22

'5.333'
>>> PRINT('WHAT'S YOUR NAME?’)

SYNTAXERROR: INVALID SYNTAX

>>> PRINT('WHAT\'S YOUR NAME?”)

SYNTAXERROR: INVALID SYNTAX

>>> PRINT('WHAT\'S YOUR NAME?')

WHAT'S YOUR NAME?

>>> PRINT("HELLO ALL \T WELCOME TO THE WORLD OF PYTHON")

HELLO ALL WELCOME TO THE WORLD OF PYTHON

>>> PRINT("HELLO ALL \N WELCOME TO THE WORLD OF PYTHON")

HELLO ALL

WELCOME TO THE WORLD OF PYTHON

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

TRACEBACK (MOST RECENT CALL LAST):

FILE "<PYSHELL#87>", LINE 1, IN <MODULE>

X_Y

NAMEERROR: NAME 'X_Y' IS NOT DEFINED

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

>>> print(a is not c)


IDENTITY OPERATOR

x="hello learning python is very easy!!!"


print('h' in x)
print('d' in x)
print('d' not in x)
print('python' in x)

© Oxford University Press 2017. All rights reserved. 42


Expressions
An expression is any legal combination of symbols (like variables, constants and
operators) that represents a value. In Python, an expression must have at least one
operand (variable or constant) and can have one or more operators. On evaluating an
expression, we get a value. Operand is the value on which operator is applied.
Constant Expressions: One that involves only constants. Example: 8 + 9 – 2
Integral Expressions: One that produces an integer result after evaluating the
expression. Example:
a = 10
• Floating Point Expressions: One that produces floating point results. Example: a * b / 2
• Relational Expressions: One that returns either true or false value. Example: c = a>b
• Logical Expressions: One that combines two or more relational expressions and returns
43

a value as True or False. Example: a>b && y! = 0


• Bitwise Expressions: One that manipulates data at bit level. Example: x = y&z
Operations on Strings

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

© Oxford University Press 2017. All rights reserved. 48


>>> x=txt.center(20,'c')
>>> print(x)
cvr college of engineering
>>> txt="cvr college of engineering !!! welcome to cvr"
>>> print(txt.count('cvr'))
2
>>> print(txt.find('cvr'))
0
>>> print(txt.find('welcome'))
31

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}

© Oxford University Press 2017. All rights reserved. 60


frozenset data type:
• It Is Exactly Same As Set Except That It Is Immutable. Hence We Cannot Use Add Or Remove Functions.
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> fs
frozenset({40, 10, 20, 30})
>> fs.add(10)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
fs.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
61
byte data type
• byte data type represents a group of byte no's just like an array.
• This function returns bytes object that is an immutable sequence of integers in the
range 0<=x<256
• Example:

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

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

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

new_number = integer_number + float_number

# display new value and resulting data type


75
print("Value:",new_number)
print("Data Type:",type(new_number))
EXPLICIT TYPE CONVERSION
• In Explicit Type Conversion, Users Convert The Data Type Of An Object To Required Data
Type.
• We Use The Built-in Functions Like Int(), Float(), Str(), Etc To Perform Explicit Type
Conversion.
• This Type Of Conversion Is Also Called Typecasting Because The User Casts (Changes) The
Data Type Of The Objects.

76
num_string = '12'
num_integer = 23

print("data type of num_string before type casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("data type of num_string after type casting:",type(num_string))

num_sum = num_integer + num_string

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy