2 Python Varibles and Data types
2 Python Varibles and Data types
1. Variables
2. Data Types
1.0 Variables
Introduction.
Variables help programs become much more dynamic, and allow a program to always reference
a value in one spot, rather than the programmer needing to repeatedly type it out, and, worse,
change it if they decide to use a different definition for it.
Variables can be called just about whatever you want. You wouldn't want them
to conflict with function names, and they also cannot start with a number.
Variables are containers for storing data values. Unlike other programming languages, Python
has no command for declaring a variable. A variable is created the moment you first assign a
value to it
Objectives
Objectives by the end of this topic you should be able to:
• Create variables
• Assign value to multiple variables
• Differentiate between global and local variables
Learning activities
Learning Activity 4.1: Reading
Read further on declaring local and global variables.
Learning Activity 4.2: Journal
Write a python program to demonstrate usage of different variables.
Learning Activity 4.3: Discussion
Write a Python program to check the sum of three elements (each from an array) from three
arrays is equal to a target value. Print all those three-element combinations.
Assessment
Topic resources
1. The Python Tutorial¶. (n.d.). Retrieved from https://docs.python.org/3/tutorial/index.html
2. Mueller, J. P. (n.d.). Beginning Programming with Python For Dummies. S.l.: For
Dummies.
3. (n.d.). Python 3.7.4 documentation. Retrieved from https://docs.python.org/3
4. (n.d.). Git Handbook. Retrieved from https://guides.github.com/introduction/git-
handbook/
5. Shaw, Z. (2017). Learn Python 3 the hard way: a very simple introduction to the
terrifyingly beautiful world of computers and code. Boston: Addison-Wesley.
6. Bader, D. (2018). Python tricks: the book. Vancouver, BC: Dan Bader.
7. Downey, A. B. (2015). Think Python. Sebastopol: OReilly.
8. Ramalho, L. (2016). Fluent Python:Beijing: OReilly.
URL Links
https://www.tutorialspoint.com//python_variable_types.htm
https://www.geeksforgeeks.org/global-local-variables-python/
https://www.geeksforgeeks.org/python-scope-of-variables/?ref=rp
https://www.geeksforgeeks.org/private-variables-python/?ref=rp
https://www.geeksforgeeks.org/python-program-to-swap-two-variables/?ref=rp
https://www.youtube.com/watch?v=wrb7Gge9yoE - How to push Code to Github
TOPIC 4 NOTES
Python is not “statically typed”. We do not need to declare variables before using them, or
declare their type. A variable is created the moment we first assign a value to it.
Output:
45
1456.8
John
Rules for creating variables in Python are same as they are in other high-level languages. They
are:
a) A variable name must start with a letter or the underscore character.
b) A variable name cannot start with a number.
c) A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
d) Variable names are case-sensitive (name, Name and NAME are three different variables).
e) The reserved words(keywords) cannot be used naming the variable.
Output:
10
10
10
Output:
1
20.2
Python Prorgamming
Output:
Python Programming
Output:
30
Programming in Python
Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Creating objects (or variables of a class type):
Please refer Class, Object and Members for more details.
Output:
cse
cse
101
cse
Global and Local Variables in Python
Global variables are the one that are defined and declared outside a function and we need to use
them inside a function
Output:
I love programming in Python
If a variable with same name is defined inside the scope of function as well then it will print the
value given inside the function only and not the global value.
Output:
Me too.
I love programming in Python.
The variable s is defined as the string “I love programming in Python”, before we call the
function f(). The only statement in f() is the “print s” statement. As there is no local s, the value
from the global s will be used.
The question is, what will happen, if we change the value of s inside of the function f()? Will it
affect the global s as well? We test it in the following piece of code:
Output:
Line 2: undefined: Error: local variable 's' referenced before assignment
To make the above program work, we need to use “global” keyword. We only need to use global
keyword in a function if we want to do assignments / change them. global is not needed for
printing and accessing. Why? Python “assumes” that we want a local variable due to the
assignment to s inside of f(), so the first print statement throws this error message. Any variable
which is changed or created inside of a function is local, if it hasn’t been declared as a global
variable. To tell Python, that we want to use the global variable, we have to use the
keyword “global”, as can be seen in the following example:
Revision questions
1. What is the output of the following code
x = 50
def fun1():
x = 25
print(x)
fun1()
print(x)
2. What is the output of the following code
def func1():
x = 50
return x
func1()
print(x)
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can
be integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
• Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fraction or decimal). In Python there is no limit to how
long an integer value can be.
• Float – This value is represented by float class. It is a real number with floating
point representation. It is specified by a decimal point. Optionally, the character e or
E followed by a positive or negative integer may be appended to specify scientific
notation.
• Complex Numbers – Complex number is represented by complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
# Python program to
a = 5
b = 5.0
c = 2 + 4j
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences
allows to store multiple values in an organized and efficient fashion. There are several
sequence types in Python –
• String
• List
• Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection
of one or more characters put in a single quote, double-quote or triple quote. In python there is
no character data type, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
print(type(String1))
# Creating a String
print(String1)
print(type(String1))
For
Life'''
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
# Python program to demonstrate
# Creation of List
# Creating a List
List = []
print(List)
List = ['GeeksForGeeks']
print(List)
print(List[0])
print(List[2])
print(List)
Output:
Initial blank List:
[]
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print(List[-1])
print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer Python List.
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference between
tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of the data sequence. Tuples can contain any
number of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
# creation of Set
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
Tuple1 = tuple('Geeks')
print(Tuple1)
# Creating a Tuple
Tuple1 = (0, 1, 2, 3)
Output:
Initial empty Tuple:
()
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the index operator [ ] to access
an item in a tuple. The index must be an integer. Nested tuples are accessed using nested
indexing.
# Python program to
print(tuple1[0])
# negative indexing
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])
Output:
First element of tuple
1
Boolean
Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can
be evaluated in Boolean context as well and determined to be true or false. It is denoted by the
class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw
an error.
# Python program to
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set need
not be the same, various mixed-up data type values can also be passed to the set.
# Creating a Set
set1 = set()
print(set1)
set1 = set("GeeksForGeeks")
print(set1)
print(set1)
print(set1)
Output:
Initial blank Set:
set()
# Creating a set
print("\nInitial set")
print(set1)
# for loop
# using in keyword
print("Geeks" in set1)
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
‘comma’.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can
be duplicated, whereas keys can’t be repeated and must be immutable. Dictionary can also be
created by the built-in function dict(). An empty dictionary can be created by just placing it to
curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
Dict = {}
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Creating a Dictionary
print(Dict['name'])
# method
print(Dict.get(3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks