0% found this document useful (0 votes)
2 views

Module 2 Lecture 3 Data Types

Uploaded by

u.navya25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 2 Lecture 3 Data Types

Uploaded by

u.navya25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Problem Solving Using Python

(ITFC0101)
Lecture 3
Variable
In C, Java or some other programming languages, a variable is an identifier or
a name, connected to memory location.

a = 30
10 b = 10 c = 20
a b c
10
30 10 20
12114 12115 12117

y=a
y
30
12678
Variable
In Python, a variable is considered as tag that is tied to some value. Python
considers value as objects.
a = 10 b = 10 a = 20
a b a
10 10 20
12114 12115 12117

y=a
y
20
12678
Variable
In Python, a variable is considered as tag that is tied to some value. Python
considers value as objects.
a = 10 a = 20
a a
10 20
12114 12115

Since value 10 becomes unreferenced object,


it is removed by garbage collector.
Rules
• Every variable name should start with alphabets or underscore (_).

• No spaces are allowed in variable declaration.

• Except underscore ( _ ) no other special symbol are allowed in the middle of the variable declaration

• A variable is written with a combination of letters, numbers and special characters _ (underscore)

• No Reserved keyword
Examples

Do Don’t
• A • and
• 15name
• a
• $city
• name
• Full$Name
• name15
• Full Name
• _city
• Full_name
• FullName
DataType
Datatype represents the type of data stored into a variable or memory.
Type of Data type :-
• Built-in Data type
• User Defined Data type
Data Types
Following are standard or built-in data types in
Python:
● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary

None
Numeric Data Type
Represents the data that has a numeric value
● Integers – Value is represented by int class

○ Contains positive or negative whole numbers (without fractions or decimals)

○ E.g. 100, -334, 976676576787998796764321323456767789889987898987

○ In Python, there is no limit to how long an integer value can be

>>> type(17)
<class 'int’>

>>> type(3.2)
<class 'float’>
Numeric Data Type
Represents the data that has a numeric value
● Float – Value is represented by float class

○ A real number with floating-point representation

○ Specified by a decimal point

○ (9.54, -7667.6545, 4E+2,

667575676787877897878.76)

○ Optionally, the character e or E followed

by a positive or negative integer may be

appended to specify scientific notation


Numeric Data Type

● Complex Numbers – Complex number is represented by a complex class

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


Sequence Data Type

Ordered collection of similar or different data types


● Sequences allow storing of multiple values in an organized and efficient fashion

Following sequence types in Python –


● Python String
● Python List
● Python Tuple
String Data Type
A collection of one or more characters put in a single, double, or triple quote

● Arrays of bytes representing Unicode characters


● In python: No character data type, a character is a string of length one
● Represented by str class
String Data Type
● String with Single Quote:

● Single quoted strings can


have double quotes inside
them, as in
'The knights who say "Ni!"'
String Data Type

String with Double Quote:

● Double quoted strings can


have Single quotes inside
them, as in
“I’m the best”
String Data Type
String with Triple Quote:
● Strings enclosed with three
occurrences of either quote symbol

● They can contain either


single or double quotes:
1. Using ''' '''

2. Using """ """


String Data Type
String with Triple Quote:
● Strings with multiple lines
Using triple quotes

1. Using ''' '''

2. Using """ """


String Data Type

>>> type("Hello, World!")


<class 'str’>
>>> type("17")
<class 'str’>
>>> type("3.2")
<class 'str’>
>>> 'This is a string.'
'This is a string.'
>>> """And so is this."""
'And so is this.’
String Data Type
>>> type('This is a string.')
<class 'str’>
>>> type("And so is this.")
<class 'str’>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str’>
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken!"
String Data Type
Triple quoted strings can even span multiple lines:
>>> message = """This message will
... span several
... lines."""
>>> print(message)
This message will
span several
lines.
>>>
String Data Type

● Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to surround
strings
● Once it has parsed the text of your program or command

○ The way it stores the value is identical in all cases


● Surrounding quotes are not part of the value

○ When the interpreter wants to display a string

○ It has to decide which quotes to use to make it look like a string


String Data Type
Accessing List Elements
● Individual characters of a String can be accessed by using Indexing
● Negative Indexing allows 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.


>>> 42000
42000
>>> 42,000
(42, 0)
List data type
List – A list represents a group of elements. A list can store different types of elements
which can be modified. Lists are dynamic which means size is not fixed. Lists are
represented using square bracket [ ].
Ex:- data = [10, 20, -50, 21.3, ‘Python’]

[0] 10 [-5] 10 data[1] = 40


[1] 20 [-4] 20
data [2] -50 data [-3] -50
[3] 21.3 [-2] 21.3
[4] Python [-1] Python
List Data Types

● Creating an empty list:

● Creating a list with multiple string values:


List Data Types
Multi-dimensional List

● 2D List
List Data Types
Multi-dimensional List
● 3D List
List Data Types
List with Duplicate elements
● List may have duplicate items
List Data Types
List with mixed type values (heterogeneous data elements)
● List supports heterogeneous data items
List Data Types
Accessing list with negative index
● In Python, negative sequence indexes represent positions from the end
● Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last
item, etc.
● Offset List[len(List)-2] == List[-2]
● len(list): Number of elements in list
List Data Types
len() function in multidimensional list
Tuple Data Types

● Similar to list, a tuple is also an ordered collection of Python objects


● Difference: tuples are immutable

○ tuples cannot be modified after creation


● represented by a tuple class
● Support mixed data elements
Typle data type
Tuples are represented using parentheses ( ).
Ex:- data = (10, 20, -50, 21.3, ‘Python’)

[0] 10 [-5] 10 data[1] = 40

[1] 20 [-4] 20
data [2] -50 data [-3] -50
[3] 21.3 [-2] 21.3
[4] Python [-1] Python
Range – Range used to generate a sequence of numbers.

range(stop): Generates a sequence from 0 to (stop-1).


range(start, stop): Generates a sequence from start to (stop-1).
range(start, stop, step): Generates a sequence from start to (stop-1) with the
specified step size
Ex:- rg = range(5) 01234
rg = range(10, 20, 2) 10 12 14 16 18

[0] 0 [-5] 0 [0] 10


[1] 1 [-4] 1 [1] 12
rg [2] 2 rg rg
[-3] 2 [2] 14
[3] 3 [-2] 3 [3] 16
[4] 4 [-1] 4 [4] 18
Boolean Data Type

● Data type with one of the two built-in values: True or False
● Non-Boolean objects can be evaluated in a Boolean context as well

○Determined to be true or false


● Denoted by the class bool

● Python internally represents True as 1 and False as 0.

Ex:- True, False

True + True = 2

True – False = 1
None data type

•The None keyword in Python is a data type and an object of the NoneType class.
None datatype represents an object that doesn’t contain any value.

Interesting Facts about None in Python


● None keyword in Python is not the same as the False.
● None is the same as 0 in Python.
● None is also not considered an empty string in Python.
● If we compare None to anything, it will always return False in Python, except while
comparing it to None itself.
● A variable can be returned to its initial, empty state by being assigned the value of
None.
● None keyword provides support for both is and == operators.
Boolean Data Type
Mapping Type/ dict / Dictionary
A map represents a group of elements in the form of key value pairs.
Ex:-
data = {101: ‘Rahul’, 102: ‘Raj’, 103: ‘Sonam’ }
data = {‘rahul’:2000, ‘raj’:3000, ‘sonam’:8000, }

[101] Rahul [‘rahul’] 2000


data [102] Raj data [‘raj’] 3000
[103] Sonam [‘sonam 8000
’]
Character
There is no concept of char data type in Python to represent individual
character.
Variables
Assignment Statement

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159
The assignment token, =, should not be confused with equals, which uses the
token ==
>>> 17 = n // Error Message
File "<interactive input>", line 1
SyntaxError: can't assign to literal
Variables
Rules

● Must start with a letter or the underscore character


● Variable name cannot start with a number
● Only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
● Case-sensitive (name, Name, and NAME are three different
variables)
● Reserved words(keywords) in cannot be used to name the
variable
Variable names and keywords
Contain both letters and digits, but they have to begin with a letter or an underscore

>>> 76trombones = "big parade"


SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = "Computer Science 101"
SyntaxError: invalid syntax
Keywords or Reserved Words
Python language uses the following keywords which are not available to users
to use them as identifiers.

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
Variables
Valid Variable Names
Identifier

• An identifier is a sequence of one or more character used to provide


a name for a given program element.

• Identifier may contain letters and digits, but cannot begin with a digit.

• It should not be used as first character, however, as identifiers


beginning with an underscore have special meaning in python.

• Spaces are not allowed as part of an identifier.


Identifier

Valid Identifiers Invalid Identifiers Reason Invalid


totalSales ‘totalSales’ Quotes not allowed
totalsales total sales Space not allowed
salesFor2024 2024Sales Cannot begin with a
digit
sales_for_2024 _2024Sales Should not begin with
as underscore

You might also like