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

Variables and Data Types

variables in python
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Variables and Data Types

variables in python
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

Comments

2
Comments in python
 Describes what a block of code means

 Readability of the program

 Precise and Clear

 Short and relevant

 Specific to block of code

 Types of Comments: Single-Line and


Multi-Line

3
How to write Comments in
Python :
 Comments in python starts with # character

(e.g.)
# way of writing comments
print(“Comments in python starts with # character”)

 Whenever # symbol is encountered, everything


after it will be omitted by the interpreter till the
line ends

4
Types of Comments:
 Single-Line: Can appear either in an individual line or
inline with other code
(e.g.) # Addition of 2 numbers
a=10
b=10
print(a+b) # Result

Multi-Line: Can appear anywhere in code, but each line


should be prefixed with # character
 (e.g.) # Example of multi-line comment
 #Perform Arithmetic operations
a=1
b=2
a+b
5
Python Line Structure
A Python program comprises logical lines. A NEWLINE token
follows each of those. The interpreter ignores blank lines.

print("Welcome \
to Python Programming")
Output: Welcome to Python Programming

print(“Welcome
to Python Programming")
Output: Welcome
to Python Programming

6
Variables

7
Python Variables
• Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in 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 variables, you can store integers, decimals in these
variables.

In Python, we don’t define the type of the variable. It is assumed on the basis of
the value it holds.
x=10
print(x)
x='Hello'
print(x)
Here, we declared a variable x, and assigned it a value of 10. Then we printed
its value. Next, we assigned it the value ‘Hello’, and printed it out. So, we
see, a variable can hold any type of value at a later instant. Hence, Python
is a dynamically-typed language.

8
Variables(Cont..)

Python variables can only begin with a letter(A-Z/a-z) or an


underscore(_).

Python variables are case sensitive.

Reserved words (keywords) cannot be used as identifier


names.

9
Naming Rules
• Reserved words (keywords).

and def False import not True

as del finally in or try

assert elif for is pass while

break else from lambda print with

class except global None raise yield

continue exec if nonlocal return

Mohammed Zabeeulla 03/2


7/22
10
Multiple Assignment
• We can assign values to multiple python variables in one
statement.
Example: 1)
age,city=20,"Bangalore“
print(age,city)

Example 2)
a=b=c=0
print(a,b,c)

Mohammed Zabeeulla 03/2


7/22
11
Swapping variables
• Swapping means interchanging values. To swap Python variables,
we don’t need to do much.
>>> a,b='red','blue'
>>> a,b=b,a
>>> print(a,b)

Mohammed Zabeeulla 03/2


7/22
12
Deleting variables
• We can delete python variables using the keyword ‘del’.
>>> a=10
>>> del a

Mohammed Zabeeulla 03/2


7/22
13
Redeclare a variable

• a=12
• print(a)
• a=‘Jain’
• print(a)

Mohammed Zabeeulla 03/2


7/22
14
Object Identity

• The built-in function id () returns the identity of an object as an integer. This


integer usually corresponds to the object’s location in memory, although this is
specific to the Python implementation and the platform being used. 

• Example:
• n=300
• m=n
• id(n)
• id(m)
• m=400
• id(m)
Mohammed Zabeeulla 03/2
7/22
15
Output Variable

• The python ‘print’ statement is often used to output variables.


• To combine both text and variable , it uses + character.

• Example:
• q='Jain'
• print("College name is " + q)

Mohammed Zabeeulla 03/2


7/22
16
Python Data Types

Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. 
a) Numbers

b) Strings

c) Lists

d) Tuples

e) Dictionaries

f) Bool

g) Sets
Mohammed Zabeeulla 03/2
7/22
17
Numbers
• Numerical data types mainly have numerical values.
• There are four numeric Python data types: int, float, complex and bool.

1.int:
• int stands for integer.
• This Python Data Type holds signed integers.
• An integer can be of any length, with the only limitation being the
available memory.
• We can use the type() function to find which class it belongs to.
Example:
a=-10
type(a)
<class 'int'>
Mohammed Zabeeulla 03/2
7/22
18
• 2) float: It holds floating point(real number) values.
• Example:
• a=2.55
• type(a)
• <class 'float'>
• 3) long – It holds a long integer of unlimited length. But this construct
does not exist in Python 3.x.
• 4) complex- It holds a complex number. A complex number looks like
this: x+yj Here, x and y are the real parts of the number, and i is
imaginary.
• Example:
• x=2+3j
• type(x)
• <class 'complex'>
Mohammed Zabeeulla 03/2
7/22
19
Numbers
 Boolean : True and False
num = 10 > 9

20
String
• A string is a sequence of characters.
• Python does not have a char data type, unlike C++ or Java.
• We can enclose a string using single quotes or double quotes or
triple quotes.
Example:
name=“Sachin"
type(name)
<class 'str'>
Example: s = “Python”
s1=‘python’
print(“Example: “,s,s1)

21
String
#Using single quotes
str1 = 'Hello Python'
(str1)
#Using double quotes
str2 = "Honest_People"
(str2)
#Using triple quotes
str3 = '''12345'''
(str3)
#Strings indexing
(str1[0])
(str1[1])
(str1[2])
(str1[3])
(str1[4])
(str1[5])
(str1[6])
(str1[7])
(str1[8])
(str1[9])
(str1[10])
(str1[11])

22
String
# use of slice operator
(str2[0:]) # Start Oth index to end
(str2[1:5]) # Starts 1th index to 4th index
(str2[2:4]) # Starts 2nd index to 3rd index
(str2[:3]) # Starts 0th to 2nd index
(str2[4:7]) #Starts 4th to 6th index

(str2))
(str2.upper())
(str2.lower())

23
String
#We can do the negative slicing in the string; it starts from the
#rightmost character, which is indicated as -1.
#The second rightmost index indicates -2, and so on.
(str2[-1])
(str2[-2])
(str2[-3])
(str2[-4])
(str2[-4:])
(str2[-13:])

# Reversing the given string


(str2[::-1])

24
String
• The [::-1] syntax is added at the end of the variable that contains
our “Python” string value.

• This is an effective method to use because it is short and simple.


You only need to add [::-1] to the end of a string to reverse it.

• str1="welcome to jain"
• Str1
• reversedstr=str1[::-1]

25
List

26
List Methods

27
List

28
List

29
List
• #list
• a=[1,23,3,1,23,4,5,6,2,3]

• def checkIfDuplicates_1(a):
• ''' Check if given list contains any duplicates '''
• if len(a) == len(set(a)):
• return False
• else:
• return True

• result = checkIfDuplicates_1(a)
• if result:
• print('Yes, list contains duplicates')
• else:
• print('No duplicates found in list')

30
List

l1=[1,2,3,4,5,6]
listl1=len(l1)

# Python program to demonstrate working of len()


n = len([10, 20, 30])
print("The length of list is: ", n)

31
List
• # Python program to demonstrate working of len()
• a = []
• a.append("Hello")
• a.append(“and")
• a.append(“Welcome to")
• a.append(“Jain")
• print("The length of list is: ", len(a))

32
Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuple is one of the built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary,
all with different qualities and usage.
Tuples allow duplicate values
Tuples are written with round brackets.
Example :
t1 = ("apple", "banana", "cherry")
print(t1)

33
Tuple(Cont…)
Tuple items can be of any data type: String, int and boolean data
types.

Example :
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
 A tuple can contain different data types:A tuple with strings,
integers and boolean values.
 Example :
t11= ("apple",12,True)

34
Set
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Tuple, and Dictionary,
all with different qualities and usage.
• A set is a collection which is both unordered and unindexed.
Python's set class represents the mathematical notion of a set. This
is based on a data structure known as a hash table.
Duplicate values will be ignored:
tt11= {"apple", "banana", "cherry", "apple"}
print(tt11)
Set items can be of any data type.
A set can contain different data types.

35
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered, changeable and does
not allow duplicates.
Example :
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

36
37

You might also like