Python Fundamentals – Data Types,Variables and Constants
CONCEPT OF DATA TYPES
The kind of data that a variable may hold in a programming language is called the data type. The ability to divide data into different types in Python enables you to work with complex objects.
STANDARD DATA TYPES
The data stored m memory can be of many types. For example, a person’s age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python is known as a dynamically typed language, which means that you don’t have to explicitly identify the data type when you initialize a variable. Python knows, based on the value it has been given, that it should allocate memory for a string, integer or float. Python has various standard types that are used to define the operations possible on them and the storage method for each of them. Python has five standard data types such as Number, String, List, Tuple and Dictionary.
Number
Number data types store numeric values. They are immutable (value of its object can-not be changed) data types, which means that changing the value of a number data type results in a newly allocated object
Number objects are created when you assign a value to them. For example,
numl = 5 num2 = 7
Python automatically converts different types of numbers so that you (usually) don’t need to think about the compatibility of different number types. For example, if you do a math operation with both integers and floats, Python converts the integers to floats and gives the result as a float.
Python supports four different numerical types:
- int (signed integer) : int is the basic integer data type. It is treated as an integer (whole number) in that it cannot hold fractional values. For example, 5, 34, 92, -43, etc. Don’t use commas to separate digits and also integers should not have leading zeros.
- long (long integers) : Python displays long integers with an uppercase L. Long integers can also be represented in octal and hexadecimal numbers.
- float (floating point real values): Integers are not adequate for representing very large numbers and fractions. For this purpose, we need floating point types of data representation. Numbers with fractions or decimal point are called floating point number. For example, 0.34, .07, -12.9, 34.2963, etc. A floating point numbers can also be used to represent a number in scientific notation. For example, -3.0 X 105 is represented as -3.0e5.
- complex (complex numbers) : Complex number is an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number. The imaginary part is written with a j suffix, e.g., 3+lj. Python has built-in support for complex numbers.
For example,
>>> x=3+lj >>> print x.real,x.imag 3.0 1.0
Python provides a special function called type that tells us the data type of any value.
>>> type(4) <type 'int'> >>> type(3.14) <type 'float'> >>> type (2.0) ctype 'float'> >>> a= -53 >>> type(a) ctype 'int'>
String
Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes. A string can have any number of characters in it, including 0. The empty string is ” (two quote characters with nothing between them). The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator. Strings are defined using quotes (“,’, or”””).
>>> st = "Hello World" >>> st = 'Hello World' >>> st = """This is a multi-line string that uses triple quotes."""
# Program demonstrating working with string str = 'Hello Python' print str # Prints complete string print str[0] # Prints first character of the string print str [2:5] # Prints characters starting from 3rd to 5th print str [2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "PROGRAMMING" # Prints concatenated string
Figure 10.1 Program demonstrating working with string
This will produce following result:
Hello Python H llo llo Python Hello PythonHello Python Hello PythonPROGRAMMING
List
Python has a basic notation of a kind of data structure called a container, which is basi-cally any object that can contain other objects. The two main kinds of containers are sequences (such as, lists and tuples) and mappings (such as, dictionaries).
Lists are the most versatile form of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]). For example,
»> li = [” abc”, 34, 4.34, 23]
To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type (heterogeneous). The values stored in a list can be accessed using the slice operator ([ ] and [: ] ) with indexes start¬ing at 0 in the beginning of the list and working their way to end-1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( *) is the repetition operator.
We can access individual members of a list.
>>> li = ["abc", 34, 4.34, 23] >>> li[l] # Second item in the list. 34
Unlike strings, which are immutable, it is possible to change individual elements and size of a list.
Tuples
A tuple is like a list whose values cannot be modified once they have been created (en-closed in regular brackets). In other words, a tuple is immutable. Another way to think about tuples is to consider them to be a constant list. Tuples have elements which are indexed starting at 0. Items in a tuple are accessed using a numeric index.
>>> x = ('Vivek', 'Abhishek', 'Arti') >>> print x[2] Arti ' >>> y = (1, 9, 2 ) >>> print y (1, 9, 2) . >>> print max(y) 9
Dictionary
Dictionaries are Python’s most powerful data collection. Dictionaries store a mapping between a set of keys and a set of values. Dictionaries allow us to do fast database-like operations in Python. Dictionary literals use curly braces and have a list of key : value pairs. You can make an empty dictionary using empty curly braces. Dictionaries are written like this:
>>> pword = { 'Amit' : 'chuck' , 'Beena' : 'permit', 'Deepak': 'grant'} >>> print pword { 'Amit' : 'chuck' , 'Beena' : 'permit', 'Deepak': 'grant'} >>> ooo = { } >>> print ooo {}
Dictionaries consist of pairs (called items) of keys and their corresponding values. In this example, the names are the keys and the password are the values. Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary (without any items) is written with just two curly braces, like this: {}.
VARIABLE
A variable is basically a name that represents (or refers to) some value. For example, you might want the name x to represent 5. To make it so, simply execute the following:
>>> x = 5
This is called an assignment. We assign the value 5 to the variable x. Another way of putting this is to say that we bind the variable x to the value (or object) 5. After you have assigned a value to a variable, you can use the variable in expressions:
>>> x * 2 10
A value is one of the basic things a program works with, like letter or a number. These values belong to different types such as 7 is an integer, 3.5 is float (number with decimal point), ‘Hello, Python’ is a string, because it contains string of letters. Variable is a name that refers to a value.
In Python, a name refers to an object. A name is actually a label for a memory location in the computer that stores something. A value, is a chunk of code, or any sort of thing that Python understands. For example when you enter a statement such as x = 5 in Python, you are binding a name (x) to an object (5).
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, or characters in these variables.
Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable.
For example:
counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "Abhishek" # A string
Here 100, 1000.0 and “Abhishek” are the values assigned to counter, miles and name variables, respectively.
Python allows you to assign a single value to several variables simultaneously.
For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location.
You can also assign multiple objects to multiple variables.
For example:
a, b, c = 1, 2, "Abhishek"
Here two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value “Abhishek” is assigned to the variable c.
In Python, None is special data type with a single value.
For example,
begin = None
The line assigns a special value called None, to variable begin. None is Python’s way of representing nothing. None makes a good placeholder for a value. It also evaluates to false when treated as a condition.
Remember following while giving variable name:
(a) They begin with either a letter or an underscore, and they can contain letters, underscores, or digits. Generally, they are written in lower case letters.
(b) They cannot contain punctuation marks.
(c) Variable name should be meaningful and short.
(d) Examples of valid identifier names are i, my_name, name_23.
Mutable and Immutable Variables
A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable. For example,
>>> x=5 # will create a value 5 referenced by x >>> y=x # will make y refer to 5 of x >>> x= x+y # in this statement LHS(x), will rebuild to 10 so, x —> 10 y -> 5
Immutable is an object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored.
KEYWORDS/RESERVED WORDS
At the time of designing a language, some words are reserved to do specific tasks. Such words are called as keywords or reserved words. Keywords cannot be used as variable. Table 10.1 gives a list of Python language reserved words.
Difference between Keywords and Identifiers
Keywords are the words used by Python interpreter to recognize the structure of pro-gram. As these words have specific meaning for interpreter, they cannot be used for any other purpose. So keywords are reserved.
An identifier is a unique name that enables you to identify something. Identifiers are used to label variables, functions, classes, objects, and modules. They begin with either a letter or an underscore, and they can contain letters, underscores, or digits. They cannot contain punctuation marks.
CONSTANTS
Constants are the items which represent values directly and whose values cannot be changed during the execution of the program. Fixed values such as numbers, letters, and strings are called constants, because their value does not change. Spring constants use single-quotes (‘) or double-quotes (“).
For example:
>>> print 123 123 >>> print 98.6 98.6 >>> print 'Hello world' Hello world >>> VOWELS = "aeiou"
Variable name in all caps called constant and refer to value that is not meant to change (i.e., their value is constant).
Constants are valuable to programmers in two ways:
(a) They make program clearer. Here variable name VOWELS can be used anywhere you need the sequence of vowels instead of string “aeiou”
(b) Constant save retyping. Constants are especially useful if you have a long value like very long number or string.
Use a constant in programs where you have the same, unchanging value used in multiple places. Note when you create constants use all caps variable name.
Literal Constants
An example of a literal constant is a number like 5,1.23, or a string like ‘This is a string’ or “It’s a string!”. It is called a literal because it will use its value literally. The number 2 always represents itself and nothing else, it is a constant because its value cannot be changed. Hence, all these are referred to as literal constants.
Solved Exercise
Question 1.
Define data type.
Answer:
The kind of data that a variable may hold in a programming language is called the data type.
Question 2.
What is string?
Answer:
A string is a sequence of characters. Strings are basically just a bunch of words.
Question 3.
What is Single Quote string and Double Quotes string?
Answer:
You can specify strings using single quotes such as ‘Quote me on this’. All white space, i.e. spaces and tabs are preserved as it is.
Strings in double quotes work exactly the same way as strings in single quotes. An example is “What’s your name?”
Question 4.
“Strings are Immutable”. What do you mean by this?
Answer:
This means that once you have created a string, you cannot change it.
Question 5.
What are the rules for naming Identifier?
Answer:
Rules for nameing identifier are:
(a) The first character of the identifier must be a letter of the alphabet or an underscore.
(b) The rest of the identifier name can consist of letters , underscores (_) or digits (0-9).
(c) Identifier names are case-sensitive. For example, myname and myName are not the same.
Question 6.
A variable is the same as a constant. True or False?
Answer:
False. The value of a variable is intended to change during the execution of the program. The value of a constant is not intended to change.
Question 7.
Python programmers must declare all variables. True or False?
Answer:
False. Variable declarations are not required in Python. All that is required to cause a variable to come into existence is to invent a new name for a variable and assign a value to it.
Question 8.
Variable names can begin with the digit characters. True or False?
Answer:
False. Variable names must begin with a letter or underscore character.
Question 9.
Describe three different ways to format string literals.
Answer:
Surround with matching pairs of single quotes, double quotes, or triple quotes.
Question 10.
Explain type function with an example.
Answer:
Python provides a special function called type that tells us the data type of any value.
>>> type (4) ctype 'int'> >>> type(3.14) ctype 'float'> >>> type (2.0) ctype 'float'> >>> a= -53 >>> type(a) ctype 'int'>
Question 11.
What are keywords? Explain with example.
Answer:
At the time of designing a language, some words are reserved to do specific tasks. Such words are called as keywords or reserved words. Keywords cannot be used as variable. For example def,for, print, etc.
Question 12.
Explain None datatype with example.
Answer:
In Python, None is special data type with a single value. For example, begin = None
The line assigns a special value called None, to variable begin. None is Python’s way of representing nothing. None makes a good placeholder for a value. It also evaluates to false when treated as a condition.
Question 13.
What is the difference between + and * operators of List?
Answer:
The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.
Question 14.
What is difference between keyword and identifier?
Answer:
Keywords are the words used by Python interpreter to recognize the structure of program. As these words have specific meaning for interpreter, they cannot be used for any other purpose. So keywords are reserved.
An identifier is a unique name that enables you to identify something. Identifiers are used to label variables, functions, classes, objects, and modules. They begin with either a letter or an underscore, and they can contain letters, underscores, or digits. They cannot contain punctuation marks.
Multiple Choice questions
Question 1.
(a) Concatenation operator
(b) Repetition operator
(c) Both (a) and (b)
(d) None of these
Answer: (a)
Question 2.
An example of a literal constant is:
(a) 5
(b) 1.23
(c) ‘This is a string’
(d) All of the above
Answer: (d)
Question 3.
Examples of valid identifier names are:
(a) i
(b) my_name
(c) Both (a) and (b)
(d) 67Jim
Answer: (c)
Question 4.
Strings are defined using quotes (“,’, or “””):
(a) Single quote (‘)
(b) Double quote (“)
(c) Triple quote (“””)
(d) All of the above
Answer: (d)
Question 5.
Which of the following is not a keyword in Python?
(a) for
(b) if
(c) print
(d) All are keywords
Answer: (d)