DATA TYPES AND VARIABLES
LEARNING OBJECTIVES
At the end of this chapter students will be able to understand
Concept of tokens: keywords, identifiers, literals, operators and delimiters
Notion of a variable and methods to manipulate it
Assigning values to variables
output a variable
input a variable
Data Types: Numbers, String, List, Tuple, Dictionary
Data type conversion: Implicit and Explicit
Comments
TOKENS
Tokens are the smallest individual unit of a program. Following are the tokens in Python:
keywords, identifiers, literals, operators, and delimiters .
KEYWORDS
They 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. To get a list of Keywords in the Python version installed on your computer, you can type the following commands at the prompt:
>>>import keyword >>>keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
NOTE : All these keywords are in small alphabets, except for False, None, True, which are starting with capital alphabets.
IDENTIFIERS: These are the names given to identify any memory block, program unit or program objects, function, or module. Examples of identifiers are: num, roll_no, name etc.
LITERALS : A fixed numeric or non-numeric value is called a literal. Examples of literals are: 502, -178.76, “Rajan� etc.
OPERATORS : They perform some action on data. Examples of operators are: +, -, **, / etc.
DELIMITERS: Delimiters are the symbols which can be used as separators of values, or to enclose some values. Examples of delimiters are: ( ) { } [ ] , ; :
NOTE : # symbol used to insert comments is not a token. Any comment itself is not a token.
WHAT IS A VARIABLE?
Variables are like containers which are used to store the values for some input, intermediate result of calculations or the final result of a mathematical operation in computer memory. The characteristics of a variable are:
It has a name.
It is capable of storing values of certain type.
It provides temporary storage.
VARIABLE NAMING CONVENTIONS
Variable names are case sensitive. For eg. num and NUM are treated as two different variable names.
Keywords or words, which have special meaning, should not be used as the variable names.
Variable names should be short and meaningful.
All variable names must begin with a letter or an underscore (_).
After the first initial letter, variable names may contain letters and digits (0 to 9) and an underscore (_), but no spaces or special characters are allowed.
Examples of valid variable names: sum, marks1, first_name, _money
Examples of invalid variables names: marks%, 12grade, class, last-name
ASSIGNING VALUES TO VARIABLES
Python is a loosely typed language. We do not need to explicitly declare the variable. Variables are declared automatically when they are assigned value. The assignment operator (=) is used to assign value to a variable.
EXAMPLES
a=10 # value 10 is assigned to variable a
name='Rachit' # value 'Rachit' is assigned to variable name
num=10.5 # value 10.5 is assigned to variable num
NOTE : Variables do not need to be declared with any particular type and can even change type after they have been set.
EXAMPLE
num=10 # value 10 is assigned to variable num
num = 'Raman' # value 'Raman' is assigned to variable num
In Python a variable act as a pointer and stores the address of a memory location. For example, the statement num=10 will store a value 10 in some memory location and variable num will point to that memory location. We can also say that num refers to 10.
In the next statement the variable num is assigned a value "Raman". Now " Raman" will be stored in some other memory location and num will now point to that location. We can now say that num refers to "Raman".
NOTE : Whenever we assign a new value to a variable, it no more refers to any of the previous values. It always refers to a new value.
We can use id() function to know the address of memory location to which a variable is referring. For example:
>>>num=10
>>> id(num)
56897487
which is the address of the memory location where 10 is stored.
In Python, we can assign a single value to several variables simultaneously. For example:
>>> x=y=z=10
The above statement will assign value 10 to variables x,y,z.
We can also assign multiple values to multiple variables in a single statement. For example:
>>> x,y,z=12, 70.5, "Vikul"
The above statement will declare variables x,y and z with values 12, 70.5 and “Vikul� respectively.
L-value and R-value
L-value is a value which has an address. Thus, all variables are l-values since variables have addresses. As the name suggests l-value appears on left hand side but it can appear on right hand side of an assignment operator(=). l-value often represents as identifier.
R-value refers to data value that is stored at some address in memory. An r-value is a value which is assigned to an l-value. An r-value appears on right but not on left hand side of an assignment operator(=).
EXAMPLE
>>>a=1 # here the variable a refers to as l-value and 1 is the R-value
>>> b = a # valid, as l-value can appear on right
>>> 9=a # error, as 9 is not a l-value
>>>a + 1 = b # Error, left expression is not variable
>>>a = p + 5 # valid, as "p + 5" is an r-value
OUTPUT A VARIABLE
The print statement is used to display the value of a variable.
PRINT STATEMENT
The print statement is used to display the value of a variable. If an expression is given with the print statement, it first evalutes the expression and then print it. To print more than one item on a single line, comma (,) may be used.
By default, print uses a single space as a separator and a \n as a terminator (appears at the end of the string). Both of these defaults can be changed to desired values.
>>>x="welcome"
>>>print (x)
welcome
>>> x="Year"
>>> y="New"
>>> print(y + x)
New Year
>>> print('a', 'b', 'c', 'd')
a b c d
>>> print('a', 'b', 'c', 'd', sep='@', end='!!')
a@b@c@d!!
NOTE : print can also be called with no arguments to print a blank line.
INPUT A VARIABLE
input statement
The input statement is used to read text (strings) from the user:
SYNTAX
input ([prompt])
where prompt is the string we wish to display on the screen. It is optional. During execution, input() shows the prompt to the user and waits for the user to input a value from the keyboard. When the user enters value from the keyboard, input() returns this value which is usually stored in a variable. For example:
>>>name = input("What is your name?")
What is your name? Raman
The result of input statement (Raman in this case) can be stored into a variable. Thus, after the execution of above statement name will refer to "Raman".
To input numeric data from input() function we can use typecasting, i.e., changing the datatype using function. The string data accepted from the user can be converted to appropriate numeric data type using int(), float() and eval() functions.
int() and float() take a number, expression, or a string as an argument and return the corresponding integer and float value respectively.
>>>y=int (input("enter your marks"))
enter your marks 98
Data entered by the user is converted from string to integer and then assigned to y.
eval() takes a string as an argument, evaluates this string as a number(it can be integer or float), and returns the numeric result.
>>>maths=eval(input("enter marks in Maths"))
>>>English=eval(input("enter marks in English"))
>>>Science=eval(input("enter marks in Science"))
>>>total=maths + English + Science
>>>print("total=", total)
NOTE :
If the string argument contains any character other than leading +/- sign or digits, then int() and float() functions will result in an error. For example, the following statements will result in error:
>>>int("45*2")
SyntaxError: invalid character in identifier
>>> float('78/5+3')
SyntaxError: invalid character in identifier
If no argument is passed, int() returns 0 and float() returns 0.0.
The function eval() results in an error if the given argument is not a string, or if it cannot be evaluated as a number. For example:
>>eval("rollno1")
Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> eval("rollno1") File "<string>", line 1, in <module> NameError: name 'rollno1' is not defined
DATA TYPES
Data type states the way the values of that type are stored, the operations that can be done on that type, and the range for that type.
Different types of data like character, integer and numbers with decimals etc. can be stored in variables.
Different kinds of data require different amount of memory for storage.
These different types of data can be manipulated through specific data types.
Python offers five standard data types:
Numbers
String
List
Tuple
Dictionary
1. Number
Number data type is used to store Numerical Values. Python supports three different numerical types −
integer
float point numbers
complex numbers
In addition, Booleans are a subtype of integers.
a) Integer are whole numbers without decimal point. They can be positive or negative with unlimited length. For example:
>>>a=20
Integers contain Boolean Type which is a unique data type, consisting of two constants, True & False. A Boolean True value is Non-Zero, Non-Null and Non-empty. For example:
>>>entry=true
b) Numbers with fractions or decimal point are called floating point numbers. For example:
>>> k=200.789
Float can also be scientific numbers with an "e" to indicate the power of 10. For example:
127.8+e12, 89.2-E15
c) A complex number is an ordered pair of two floating-point numbers denoted by a + bj, where a and b are the real numbers and j is the imaginary unit. For example:
>>>x=10+5j
For accessing different parts of variable a; we will use a.real and a.image. Imaginary part of the number is represented by “j‟.
>>>print (x.real, x.image)
10.0 5.0
2. STRINGS
String is an ordered set of characters enclosed in single or double quotation marks. For example:
EXAMPLE
>>>str="I love Python"
3. LISTS
A list is a collection of comma-separated values (items) within square brackets. Values in the list can be modified, i.e. it is mutable. The values that make up a list are called its elements. Elements in a list need not be of the same type.
EXAMPLES
list1=[100, 200, 300, 400, 500]
list2=["Raman", 100, 200, 300, "Ashwin"]
list3=["A", "E", "I", "O", "U"]
4. TUPLE
A tuple is a sequence of comma separated values. Values in the tuple cannot be modified, i.e. it is immutable. The values that make up a tuple are called its elements. Elements in a tuple need not be of the same type. The comma separated values can be enclosed in parenthesis but parenthesis are not mandatory.
EXAMPLES
tup1=("Sunday", "Monday", 10, 20)
tup2=("a", "b", "c", "d", "e")
tup3=(1,2,3,4,5,6,7,8,9)
5. DICTIONARY
Python dictionary is an unordered collection of items where each item is a key: value pair. We can also refer to a dictionary as a mapping between a set of keys/indices and a set of values.
Each key is separated from its value by a colon (:), the items are separated by commas, and the entire dictionary is enclosed in curly braces. Keys are unique within a dictionary while values may not be. Dictionary is mutable. We can add new items or change the value of existing items.
EXAMPLES
dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}
dict2={1: 'robotics', 2:'AR' , 3:'AI' , 4:'VR'}
dict3={'num':10, 1:20}
In Python, a variable has no data type. When we say data type of a variable, we are actually referring to the data type of the value that it represents. As a variable does not have any fixed data type and its data type keeps changing depending upon the value it represents. We can use the type() function to know the data type of a variable. For example:
>>>num=10
>>> type(num)
<class 'int'>
>>> name='Kapil'
>>> type(name)
<class 'str'>
DATA TYPE CONVERSION
It is a conversion of one data type into another data type. The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically converts the data type).
Implicit Conversion An implicit type conversion is a conversion performed by the Python interpreter without programmer’s intervention. An implicit conversion is applied generally whenever different data types are intermixed in an expression. The C++ compiler converts all operands to the data type of the largest data type of the expression. It is also called type promotion.
Explicit Conversion An explicit type conversion is user-defined that forces an expression or identifier to be of specific data type. It is also called Type casting. It allows you to convert a data item of a given type to another data type. For explicit type casting, we use functions:
int ()
float ()
str ()
bool ()
EXAMPLE
>>> x= 158.19
>>> y= int(x)
>>> print (y)
158
EXAMPLE
>>>x=165
>>>y=float(x)
>>>print y
165.0
COMMENTS
Comments are non-executable statements which are ignored by Python interpreter. They are used to make the code more readable and understandable.
In Python, comment start with "#" symbol and extends till the end of the physical line. Anything written after # in a line is ignored by interpreter, i.e. it will not have any effect on the program. A comment can appear on a line by itself or they can also be at the end of line.
Example
# This program calculates the sum of two numbers
>>>n1=10
>>>n2=20
>>>sum= n1 + n2 # sum of numbers 10 and 20
>>>print ("sum=", sum)
For adding multi-line comment in a program, we can:
Place "#" in front of each line
Use triple quoted string. They will only work as comment, when they are not being used as docstring. (A docstring is the first thing in a class/function /module and will be taken up in details when we study functions).
EXAMPLE
'''This is a
multiline comment'''
or
"""This is a
multiline comment"""
Comments
Post a Comment