0% found this document useful (0 votes)
12 views52 pages

Basic Data Types

This chapter covers the fundamental elements of the Python programming language, including identifiers, literals, variables, and data types. It explains the rules for naming identifiers, the types of built-in data types, and the concept of literals as constant values. Additionally, it introduces variables, operators, expressions, assignment statements, and the object-oriented nature of Python.

Uploaded by

munish
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views52 pages

Basic Data Types

This chapter covers the fundamental elements of the Python programming language, including identifiers, literals, variables, and data types. It explains the rules for naming identifiers, the types of built-in data types, and the concept of literals as constant values. Additionally, it introduces variables, operators, expressions, assignment statements, and the object-oriented nature of Python.

Uploaded by

munish
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Data Types,

CHAPTER Literals
4 and Variables

Contents
4.1 Introduction
4.2 Identifier
4.2.1 Naming Convention for Identifiers
4.3 Keywords or Reserved Words
4.4 Built-in Data Type
4.5 Literal or Constant
4.5.1 Integer Literal
4.5.2 Float Literal
4.5.3 Complex Literal
4.5.4 Boolean Literal
4.5.5 String Literal
4.6 Variable, Operator, Expression
4.7 Assignment Statement
4.8 Object
4.8.1 Scalar and Non-scalar Objects
4.8.2 Mutable and Immutable Objects
4.9 Simple Input Output
4.9.1 Output Statement
4.9.2 Input Statement
4.10 Writing a Program (Python Syntax)
4.10.1 Python Lines – Logical, Physical, Blank
4.10.2 Comment
4.10.3 Indentation
4.11 Solved Questions with Explanation
4.12 Programming Examples
Summary
Keywords
Programming Language Keywords
Assessment
Answers

4.1 Introduction
Python programming language has a defined set of fundamental elements and
rules that are to be used for writing the programs. There is a need to
understand the basic building blocks of the language, to start writing programs
in Python language. The ways to describe the data, supported data types, rules
for defining identifiers, literals, variables and assigning values to variables are
some of the basics that need to be understood. Also, Python has a defined
structure along with rules for the structure that have to be followed while
writing a program.
In this chapter, we shall discuss the key terminologies like, identifier, literal,
variables, assignment statement and objects. Next, we shall analyze the basic
data types in Python and describe some of the simple input and code with the
basic elements.
Learning Outcomes of this chapter
After completion of the chapter, the learner will be able to:
• List the rules of naming an identifier
• Identify the literals of different data types
• Differentiate between scalar and non-scalar objects
• Use input and output statements
• List the features of basic data types
• Recognize errors in Python code
• Critically evaluate a Python code for the provided functionality
• Develop simple programs based on the concepts discussed
• Distinguish between correct and incorrect program based on the concepts
discussed.

4.2 Identifier
In Python, identifier is the name of an object. The object can be a variable,
function, module, class or another object. Python follows some rules to define
an identifier. The rules are stated as follows:
• Identifier is a combination of letters A–Z, a–z, underscore (_), and digits
(0–9).
• Other characters like,), @, and % are not allowed for defining the
identifier.
• The first character of identifier must be a letter or an underscore. The first
character of an identifier cannot be a digit.
• Python is a case-sensitive language. Thus, identifiers are case-sensitive.
SUM_TOTAL, sum_total, Sum_Total are three different identifiers.
The following identifiers are valid:
_sum,
sum_total
number1,
n01,
add_first_number
The following identifiers are invalid:
3Street,
@45,
root-node
root node

4.2.1 Naming Convention for Identifiers


The Python language provides guidelines for the naming convention of
identifiers. Some key points are stated as follows:
• Names should be easy to read. For example, sum_total is better read than
sumtotal.
• Names may be chosen according to their use. For example, sum, fact, fib
and marks are names than can identify with sum, factorial, Fibonacci, and
marks, respectively.
• Descriptive names are useful instead of short ones. For example,
last_name, first_name, insertValue are better than ln, fn and iV.
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• An identifier that starts with a single leading underscore indicates a private
identifier.
• An identifier that starts with two leading underscores indicates a strongly
private identifier.
• An identifier that starts with two leading and two trailing underscores
indicates that the identifier is a language-defined special name.
• An identifier cannot be a reserved word (discussed in next section).
According to Google Python Style Guide
([Link] the naming convention for
identifiers, some ways of naming identifiers are as follows:
• module_name, package_name, method_name, function_name,
global_var_name, instance_var_name, function_parameter_name,
local_var_name. For example, student_info, car_details.
• ClassName, ExceptionName. For example, TempEmployee, BankAccount.
• GLOBAL_CONSTANT_NAME. For example, STUD_COUNT,
TOTAL_EMP.

4.3 Keywords or Reserved Words


Keywords are reserved words of the Python language. The reserved words have
a predefined meaning in Python and cannot be used as identifiers. There are 33
keywords in Python 3. However, this number may vary in course of time.
Keywords are case sensitive. Table 4.1 shows the list of keywords.
Table 4.1 Keywords in Python

False class finally is return


None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Kindly note that all keywords except True, False, and None are in
lowercase letters.
None represents absence of value. The truth value represented by None is
False

4.4 Built-in Data Type


A program, as we know, is a set of instructions for the computer to perform
certain tasks or operations. While writing a program, we may need to use data
on which certain operations can be performed. For example, a program may
process numbers like, 2, 4, 2.3 or strings like “Good Morning” and many
more. To understand the data, we must know an important concept of ‘data
type’.
Data type is defined as a set of values and a set of allowed operations on the
values. A data type defines –
(1) values that the type of a data hold, and
(2) the operations that can be performed on the data of
that type.
Python supports several built-in data types.
The data type in Python are of two types – Simple and Compound (Figure
4.1).
• Simple Type are the ones whose elements cannot be broken down further.
The numeric type and Boolean data type are simple type. The numeric type
consists of three data types – integer (int), float (float) and complex
number (complex).
• Compound Type are the ones whose elements can be broken down further.
It consists of the sequence type, set and dictionary. The sequence type
consists of the three data types – string, list and tuple.

Figure 4.1 Common data types in Python.


Here, we discuss the simple type and introduce the string data type.
• int data type represents integers (e.g., 23, 45, 23242434).
• float data type represents floating-point numbers (e.g., 11.3, 6.02, 2e3).
• complex data type represents complex numbers (e.g., 3+1j, 6j).
• str data type represents string. A string may consist of a sequence of
characters (e.g., “Hello”, “12”, “Good Morning”).
• bool data type represents Boolean vales – True and False.
The data type provides a meaning to the data and defines operations by which
the value of a data type can be stored and manipulated. Let us take the number
5; it is an integer and belongs to data type int in Python; whereas, string
“Good” is of data type str. When we perform addition operation, the
addition of integers returns an integer, 5 + 6 = 11; but, addition of two strings
“Good” and “Morning” concatenates the two strings to give the output “Good
Morning”.
Python provides the above-defined basic built-in data type as part of the
language. Thus, when you write a program, use the data type and perform
operations on them, the Python language handles the operations; you, as a
user, need not worry about how the operations are performed. Python also
provides additional data types that are discussed in later chapters.
In Python, everything is an object. The built-in types like, int, float, bool,
string, and complex are objects.
In addition to the built-in data types, Python also allows users to create
their own data type. These are called user-defined data types. A user-defined
data type is created by defining classes. They are used to create objects, which is
an instance of the class. Chapter 13 of the book discusses the classes and
objects in detail.

4.5 Literal or Constant


In Python, literal is a value. A value is a fundamental entity that a program
manipulates. A literal is called so because its value is used literally. The value 8
is an integer and 1.1 is float and they represent themselves and nothing else,
i.e., its value cannot be changed. So, they are referred to as literal or constant.
The literals of different data types are – integer, float, complex, boolean and
string.

4.5.1 Integer Literal


• int literal is a sequence of digits 0 to 9. It may also have a positive (+) or
negative (–­­) sign. A literal without any sign is considered positive.
• Some examples of int literals are: 3, 89, 29999999, –45, –1.
• In Python, the range of values of type int is limited by the amount of
memory on the computer system.

4.5.2 Float Literal


• Float literal is a sequence of digits with a decimal point.
• It may have a positive (+) or negative (–) sign with it. A literal without any
sign is considered positive.
• Some examples of float literals are: 3.14, 89.0, 2.002, 45.34215.
• A float literal can also be represented in scientific notation. For
example, 2.3e12 is the scientific notation of the number 2.3 ´ 1012.

4.5.3 Complex Literal


• Complex numbers are written with a “j” as the imaginary part.
• Some examples of complex literals are: 3 + 4j, 2 + 5j, 5j.

4.5.4 Boolean Literal


• A bool literal is two values – True and False.
• True and False are both reserved words.
• A non-zero value is considered as True.
• A zero value is considered as False.

4.5.5 String Literal


• str literal is a sequence of characters enclosed in quotes.
• The quotes can be single quotes (‘), double quotes (“) or triple quotes (‘‘‘).
However, the same type of quote must start and end a string.
• The triple quotes are used to span the string across multiple lines.
• The characters in a string can be digits, alphabets, symbols and whitespace
characters. Some examples of whitespace characters are: newline (‘\n’) and,
tab (‘\t’) including null.
• Two operations can be performed on strings:
• Concatenation: The operator (+) is used to concatenate two or more
strings. It appends one string at the end of another string. For example,
“Good” + “Morning” will result in output “GoodMorning”.
• Repetition: The operator (*) is used for repetition. It repeats a string for
a number of times. For example, “Good” * 4 will give
“GoodGoodGoodGood”.

4.6 Variable, Operator, Expression


In Python, a variable is a name or identifier associated with a value. A variable
is like a name tag that gets attached to a value. The value of a variable can
change during computation. For example, a variable x can be assigned value 5,
and then the same variable x can be assigned value 6. Programmers can choose
the variable name. It is suggested to follow the Python Style Guide naming
convention for variable names. Some examples of variables are: x, y, sum_total,
subj_grade.
In Python, the operator defines an operation on a data type. For example,
the operator + is used for addition. The data type int defines the addition
operation to add integers, and data type float defines the addition operation
to add float numbers. Likewise, for performing different operations, different
operators are defined for different data types. The operators are discussed in
detail in Chapter 5.
The literals, variables and operators combine to form an expression. For
example, z = x – y is an expression. The expression is evaluated to get a value.
The evaluation of the expression is done in accordance with the operator
precedence rules. The expressions are discussed in detail in Chapter 5.

4.7 Assignment Statement


In Python, assignment statement is used for assigning value to a variable. An
assignment statement defines an identifier as a variable and a value of a data
type is associated to the variable. The syntax of simple assignment statement is:

variable = expression
The sign “equal to” (=) is an assignment operator. This is not equality but
assignment operator. To the left of = sign is the variable and to the right of =
sign is the value stored in the variable.
An example of assignment statement is as follows:

x=5
In the above statement,
• 5 is a value of int data type
• = is the assignment operator
• x is a variable assigned a value 5
Some key properties of assignment statement are:
• An assignment creates a reference to value instead of copying the value. So,
variables are like pointers.

• In Python, variables do not have to be declared explicitly. The declaration


happens automatically during assignment. During the assignment, Python
creates the variable name. There is no need to pre-define the variable.

• The variable names must be assigned a value before they are used.
Otherwise, an exception is raised. For example, y = x + 5 will result in an
exception since x does not have a value.
• In an assignment statement, the left side must be a single variable. The
right side is an expression (discussed in Chapter 5). The expression on the
right side is first evaluated and the value generated is associated to the left-
side variable.

Examples of correct assignment statement are:


a = 12
x=y+5
Examples of incorrect assignment statement are:
12 = a
x+y=5
• Python allows assigning single value to multiple variables in a single
statement. For example,
x = y = z = 5.
Here, value 5 is assigned to variables x, y and z.
• Python allows assigning multiple values to multiple variables in a single
statement. For example,
x, y, a = 5, 10.2, “Hello”.
Here, values 5 and 10.2 are assigned to variables x and y, respectively, and
string “Hello” is assigned to variable a.

4.8 Object
Python is an object-oriented programming language. Object is the basic
building block in object-oriented language. An object has an identity, type and
value.
• Identity is unique for an object. It is the memory address where the object
is stored.
• Type defines behavior of the object. It defines values that an object of a type
represents and the set of operations that can be performed on the object.
• Value of an object is the value it represents.
In Python programs, all data values are represented by objects. Since value is of
a data type, an object is representation of value from a data type. Some
properties of objects are as follows:
• An object stores one value. 12, 234 and 33333 are three different objects of
type int.
• Different objects can store same value. One object can store 12 and
another object can also store 12.
• What all can be done with an object depends on the type of object. For
example, integer operations can be performed on an object of type int,
and string operations are performed on object of type str.
In Python, we can find the identity, type and value of an object as follows:
• id (object) for Identity
• type (object) for Type
• Value is the value it represents.
Example 4.1: (a) Print id, type and value of an object (b) Output

In Python, a variable refers to an object. The steps taken by Python


language when we write a statement
a = 10
are as follows:
• An object is created with literal or value 10.
• The object with value 10 has a unique identifier (unique storage location in
memory).
• The variable named ‘a’ refers to the object 10. The variable gets bound to
the object by the assignment statement. (The left side of assignment gets
bound to the value on right side.)
• The type of object is int, because object 10 is an integer.
• Operations of type integer can be performed on the object, like, add,
subtract.
Figure 4.2 is a diagrammatic representation of object and its reference
variable.

Figure 4.2 Object and reference variable


In Python, the size in bytes occupied by the different data types is much
higher than the size of a data type in C or C++. This is because in Python,
everything is an object. So, it has its overheads of maintaining an object. We
can use the function getsizeof() (discussed in later chapters) to get the size of
any data type. In Python, the data types themselves are considered as objects.
Thus, data type int is also an object.
In Example 4.2 (do not worry about the code, see output values), we see
that for the assigned data, int occupies 12 bytes, float 16 bytes and string 26
bytes, in a 64-bit machine on which Python 3.6 is installed.
Example 4.2: (a) Size of data types (b) Output

4.8.1 Scalar and Non-scalar Objects


Objects can be scalar and non-scalar.
• Scalar object cannot be divided further. Objects of built-in data types – int,
float, bool and None are scalar objects. Some examples of scalar objects are:
o -3, 5, 2001 (objects of type int)
o 3.0, 67.4, -33.4, 8.2E-3 3.4E-5 (objects of type float).
o True, False (objects of type bool)
o None is a single value
• Non-scalar objects can be decomposed further. Objects of built-in data type
str are non-scalar objects. Some examples are: “good”, “Hello Students”
and “Beautiful”. The strings can be further decomposed like, “go”, “o”, “d”,
“Hello”, “Students”, “Beauti”, “ful”.

4.8.2 Mutable and Immutable Objects


Objects can be mutable and immutable. To determine an object’s mutability,
we have to check its data type.
Mutable objects are the ones whose value can change.
Immutable objects are the ones whose value cannot change. From among
the basic data types, int, float and str are immutable. This means that
once objects of data types int, float and str type are created, the value of
the object cannot be changed. As a result, when an operation is performed
using integer, float or string, a new integer, float or string object is created.
Example 4.3 (a) shows the code. We see that integer value 10 is assigned to x
and then integer value 30 is assigned to x. In Example 4.3 (b) we see that the
id of x is different for both assignments. So, when a value assigned to a variable
is changed, it results in a new variable, and the value of existing variable does
not change. Thus, we see that data type int is immutable.
Example 4.3: (a) Show immutable objects (b) Output
4.9 Simple Input Output
When writing a Python program, there is a need to show the result of the
program to the user. Also, there may be a need to get input from the user.
Python has built-in functions to support the input and output functionality
(Functions are discussed in detail in later chapters).
We discuss two functions here:
• Print function – shows output on the screen, and
• Input function – accepts input from the user keyboard.

4.9.1 Output Statement


For output, print function is used. A simple print statement has name of the
function “print”, followed by parameters to be printed in parenthesis. The
syntax of print() function is as follows:

print (“objects, sep=’’, end=’\n’,


file=[Link], flush=False)
where,
objects are values to be printed.
sep is separator between objects. By default, it is space character ‘’.
‘\n’ is newline. After printing all values, end the statement. By default, it is
newline.
[Link] is default standard output device, i.e., screen.
(Flush will be explained in later chapters)
The print() statement prints an empty line in the output. It is used for
showing blank lines in the output. Example 4.4 shows Python code with print
statement: (1) Print with string object,
(2) Print with string and variable, (3) Print with string, variable and string, (4)
Print a blank line, and (5) Print integer objects, string and separator. Figure 4.6
(b) shows output after execution of the code.
Example 4.4: (a) Show using the Print statement (b) Output
4.9.2 Input Statement
For taking input from the user, input function is used. A simple input
statement has the name of the function “input”, followed by parenthesis. The
syntax of input() function is as follows:

input([prompt])
where, prompt is a string to be displayed on the screen. It is optional to
specify a prompt.
When input statement is executed, the prompt is displayed on the screen,
and it waits for the user action. For example, an input statement a= input
(‘Enter your age’), when executed, will display the prompt ‘Enter your age’ and
wait for the user to enter the data. Example 4.5 (a) shows a Python code with
input statement and (b) shows the output after execution of the code.
Example 4.5: (a) Using input statement (b) Output
It must be noted that Python accepts all inputs as strings. To get the
integer value or float value, the user must convert the string into int or
float. For example, to convert the input to integer, the type conversion int
is used, i.e., int(input(“Enter ”)). So, whenever you input a number as a string,
int converts the string into an integer.
Example 4.6. (a) Input Integer conversion (b) Output

4.10 Writing a Program (Python Syntax)


A program written in Python is easy to read. When writing a program, a set of
rules defined for the programming language, also called the syntax, have to be
followed. The syntax of Python language is discussed in the following
subsections.
4.10.1 Python Lines – Logical, Physical, Blank
On Python IDLE, each new line is a physical line. Physical line is a sequence
of characters that is terminated by an end-of-line sequence. The end-of-line
can be carriage return (CR), line feed (LF) or return/enter. Implicitly, Python
assumes that a physical line corresponds to a logical line.
• One Physical line, One Logical line: One statement of Python (logical) is
written in one physical line. Python code (1) in Example 4.7 shows that
each physical line has one logical statement.
• Multiline – One Logical line, Many Physical lines – Use backslash (\):
When writing a program, a single Python statement may be spread across
multiple physical lines. The complete statement in different physical lines
forms a logical line of Python. A logical line is created from one or more
physical lines. Every logical line terminates with a newline character. The
Python code (2) shown in Example 4.7 shows one logical statement spread
across multiple physical lines by using the backslash at the end of the
physical line.
• One Physical line, Many Logical lines – Use semicolon (;): When writing a
program, more than one Python statement (logical line) may be on one
physical line. To specify more than one logical statement on a single
physical line, use semicolon (;) at the end of a logical statement. The
Python code (3) in Example 4.7 shows that in one physical line there are
two logical statements separated by semicolon.
Implicitly, it is suggested to use a single statement per line, as it makes the
codes more readable.
Example 4.7: (a) Logical and Physical Lines (b) Output
Blank line is a line having only whitespaces, tabs, form feeds, or a
comment. Python interpreter ignores the blank line. When writing a Python
code, if you press <Enter> key without writing on the line, a blank line is
inserted in the code.

4.10.2 Comment
Comment is a text written in English with a purpose of describing the task
that the code will perform. Comments are important while writing a program.
The comments in a code make it easy for other programmers to understand the
code. The comments help the author to understand the code months later,
when they might forget the details of the program.
During execution of Python program, the interpreter ignores the
comments. The comments do not affect working of the program. A comment
can also be after a statement. There can be multiple comments in a single
program.
In Python, there are two ways to write a comment:
1. Single-line comment
2. Multi-line comment
Single-line comment
• Single-line comment starts with hash (#) symbol.
• It is used for writing short comments.
• Everything after the hash is considered as a comment up to end of the
physical line or the newline character.
• For example,
# This is a factorial program.
Multi-line comment
• Multi-line comment starts with three single quotes (‘‘‘) and ends with three
single quotes (’’’), or, start with three double quotes (“““) and end with
three double quotes (”””).
• It is used for writing detailed description in the code, spread across
multiple lines.
• For example,
‘‘‘ This is a program
For computing the factorial of a number.
3! Is 3*2*1’’’
Example 4.8 shows comments in a Python code.
Example 4.8: (a) Comments in Python code (b) Output

4.10.3 Indentation
Most programming languages like C, C++, Java use braces { } to define a block
of code for class, function definitions and control flow statements. Python does
not use braces for defining a block of code. Python uses indentation.
Indentation is enforced rigidly.
• A block of code starts with indentation and ends with the first un-indented
statement.
• The number of spaces in indentation is not fixed. The programmer can
choose the number of spaces.
• Statements that are together must have same indentation.
• Within a block, all statements must be indented to the same extent.
Alternatively, all statements on consecutive lines indented with the same
number of spaces form a block.
• Generally, four whitespaces are used for indentation and is preferred over
tab.
Let us see some examples of indentation.
Example 4.9 shows that a program with wrong indentation, when run,
gives syntax error. From this error, it is noted that in the program, a block
cannot be started arbitrarily. Blocks should follow some rules, which will be
discussed in later chapters.
Example 4.9: Incorrect indentation and syntax error
4.11 Solved Questions with Explanation
1) Find the output:

2)

Explanation: Self-explanatory
3)
Explanation: Self-explanatory
4)

Explanation: Here, 5123 is not a string, so integer 5123 is multiplied by


integer 2.
5)

Explanation: Here, the input is not converted into type int. So, the input
is of type string. A string cannot be replicated by a string. So it shows error.
6)

Explanation: Here, string 456 is replicated 4 times. Then it is represented


as float.
7)

Explanation: Here, string 456 is replicated 4 times. Then it is represented


as string.
8)

Explanation: Here, the user has entered a string “a”. A string cannot be
replicated by a string. So it shows error. The error is in the input value.
9)

Explanation: Here, the input is a string 4. It is not converted into int. So,
the string 4 is replicated 2 times.
10)

Explanation: Here, the input is a string 2. It is not converted into int. So,
the string 2 is replicated 456 times.
11)

Explanation: Here, only b is reapeated 4 times and a only once.


12)

Explanation: Here, both a and b are concatenated and then repeated 4


times.
13) Find the output (for the codes in the left column).

Code Output and explanation


>>> “3” + 9 Error. Cannot add string and integer
>>> “23” * 2 2323
>>> “78” + “56” 7856
>>> “23” * “2” Error. Cannot replicate a string with a non-int
>>> “23” + “abc” 23abc
>>> “23” * “abc” Error. Cannot replicate a string with a non-int
>>> 3 + 4.5 7.5
>>> 4.3 * “abc” Error. Cannot replicate a string with a non-int
of type float
>>> 4.3 + 4e1 44.3
>>> 22 * 2.0 44.0

14) Identify the type of literals.

Literal Type
>>> 33 <int>
>>> 23.1 <float>
>>> True <bool>
>>> 2e3 <float>
>>> “Good” <str>
>>> ‘Good’ <str>
>>> Good Not a literal
>>> 234.123 <float>

4.12 Programming Examples


In this section, a few sample programs are given with their output.
Program 4.1: Program to print “Hello!” on the screen.

Output

Program 4.2: Accept the name of the user and print “Hello” with the user
name.

Output

Program 4.3: Accept the name of the user, and print 5 sentences for the user.
Output

Program 4.4: Accept the details of the user and print his/her details.

Output
Program 4.5: Print all vowels in the output.

Output

Program 4.6: Accept four integers from the user. Print them in separate lines
using (1) 4-print statements (2) single-print statement.

Output

Program 4.7: Accept two strings from the user and print it as a single string
with a space.
Output

Program 4.8: Accept an integer from the user. Print its id, type and value.

Output

Program 4.9: Accept a string from the user. Print its id, type and value.

Output
Program 4.10: Accept a float value from the user. Print its id, type and value.

Output

Program 4.11: Accept two strings from the user. Concatenate the two strings.

Output

Program 4.12: Accept a string from the user and repeat it five times.
Output

Program 4.13: Accept words from the user that describe him/her positively.
Take the words from the user and print it with “I AM” followed by the word.
(E.g., I AM strong.)

Output
Program 4.14: Accept the name of the user. Accept five things that they like to
eat. Display output in five lines as- “XYZ likes to eat PQR”.

Output
Program 4.15: Show a menu that allows a user to select the operations
performed using calculator.

Output

Program 4.16: Define values of different data types and assign variables to
them.
Output

Program 17: Define string literals and perform operations on them.

Output

Summary
• A data type defines the set of values, and the operations that can be
performed on the values.
• int, float, str, bool and None are basic built-in data types in
Python.
• The value of a data type is a literal.
• Operators are used for performing operations on a data type.
• An identifier defines a name. There are rules and naming conventions for
defining identifiers.
• Python has 33 keywords.
• Variable is a name associated with a value. It is not predefined or declared
explicitly.
• Expression is a combination of literals, variables and operators.
• Assignment statement assigns value to a variable.
• Object is the basic building block in Python. Object has identity, type and
value.
• A variable refers to an object.
• Objects can be scalar or non-scalar objects.
• Objects whose value can change are mutable objects; others are immutable
objects.
• The int data type represents integers, float represents floating-point
numbers and str represents string.
• String concatenation can be performed using (+) operator.
• String repetition can be performed using (*) operator.
• A bool literal is True and False.
• None is an object that represents absence of value.
• Print function is used for showing output on the screen.
• Input function is used for taking input from the user.
• Python syntax defines rules that have to be followed while writing a
program.
• Python defines a new line as a physical line.
• A Python statement spread across different physical lines forms a logical
line.
• Python allows writing multiple logical lines in a single physical line using
semicolon (;) and one logical line in multiple physical lines using backslash
(\).
• Blank line is ignored by the Python interpreter.
• Comments in Python program describe the program. They are ignored by
the interpreter.
• Comments can be in a single line or in multiple lines.
• Python uses indentation for defining a block of code.
Keywords
Reserved word
Naming convention
Variable
Expression
Assignment statement
Object
Scalar objects
Non-scalar objects
Mutable objects
Immutable objects
Integers
String
Boolean
Python syntax
Physical line
Logical line
Multiline
Blank line
Comments
Single-line comment
Multi-line comment
Indentation
Data type
Literal
Value
Operator
Identifier

Programming Language Keywords


int
float
str
bool
None
True
False
id (object)
print()
input()
type (object)
String concatenation (+)
String repetition (*)

Assessment
A.1 Bloom Level: Knowledge/Remember
Review Questions
1. Define the following:
a) Data type
b) Literal
c) Identifier
d) Variable
e) Expression
f) Assignment
g) Object
h) Physical line
i) Logical line
j) Comment
2. Name the basic built-in data types in Python.
3. Give three examples each, of valid values of data type
int, float, string.
4. What is the value of type None?
5. What is the value of type bool?
6. What is the value of 2.3e6?
7. State the rules for defining identifiers.
8. What is the meaning of Python syntax?
9. Match the operator with their use:

Operator Used for


1 = a String concatenation
2 singe quote (') b Multi-line comment
3 Triple quote (''') c Assignment
4 + d Multiple logical lines in single
physical line
5 * e one logical line in multiple
physical lines
6 Semicolon (;) f String literal
7 # g String repetition
8 \ h Single-line comment

Fill in the blanks


1. _________ and __________ are the two values of bool data
type.
2. There are _______ keywords in Python.
3. _______, _________ and __________ combine to form an
expression.
4. The set of operations that can be performed on an
object is defined using _______ of object.
5. <class ‘int’> is ______ of object.
6. Based on decomposition, objects are identified as ______
objects and _______ objects.
7. _______ objects are the ones whose value can change.
8. The ______ data type represents integers.
9. The ______ data type represents floating-point numbers.
10. The ______ data type represents strings.
11. The __________ quotes are used to span string across
multiple lines.
12. ________ is the newline character.
13. The truth value of None is ________.
14. _______ function is used for showing output to the user.
15. ________ function is used to accept input from the user.
16. _________ is the default separator between objects in a
print function.
17. _______ character is used to display one logical line in
many physical lines.
18. _____ symbol is used for writing one Python statement in
many logical lines.
19. ____ line and ______ line are the two ways of writing
comments.
20. ____ symbol is used for writing single-line comment.
21. _______ single quotes or double quotes are used for
writing multi-line comment.
22. _____________ is used for defining a block of code.
State True/False
1. Bool data type is for a sequence of characters called
strings.
2. 45 is a floating-point number.
3. 2, 2.0 and −2 are valid integers.
4. The value of a literal cannot be changed.
5. Reserved words are case-sensitive
6. 3sum is a valid identifier.
7. A variable is a name tag attached to a value.
8. An assignment statement creates a copy of the value
instead of referencing to the value.
9. In Python, variables are pre-defined.
10. Different objects can store the same value.
11. None is a scalar object.
12. Objects of int, float and str are immutable.
13. “*” is a string concatenation operator.
14. A zero means True.
15. None represents absence of value.
16. A single Python statement cannot be written on multiple
physical lines.
17. i=5; y=3 is a valid Python syntax.
18. Comments affect the working of a Python program.
19. The number of spaces in indentation is fixed.

A.2 Bloom Level: Comprehend/Understand


Review Questions
1. Describe the naming convention for identifiers.
2. Describe syntax of: (a) Print function
(b) Input function.
3. Explain how a literal is different from a variable.
4. What is the difference between 5 and x=5?
5. Identify the identifier names that are correct:
a) A1
b) a1
c) _a
d) @a1
e) %a1
f) )a1
g) A1@
h) A1%
i) A1)
j) Aa11
k) _aaa
6. Segregate reserved words from the keywords:
a) def
b) defn
c) for
d) formula
e) lambda
f) lamb
g) while
h) wiley
i) None
j) none
k) Def
l) fore
7. Identify the scalar and non-scalar objects:
a) 10.2
b) 10
c) “10.2”
d) ‘10’

Multiple Choice Questions (MCQ)


1. Identify the odd one out:
(i) 2.0
(ii) -3.14
(iii) 2
(iv) 13e3
2. End of line cannot be _____.
(i) CR (Carriage return)
(ii) LF (Line Feed)
(iii) Return/Enter
(iv) Tab

A.3 Bloom Level: Application/Apply


Review Questions
1. Identify the literals, type of literals and variables used in
the following statements. Name the type of expression
used in the third statement, the operators used in each
statement and binding of objects in the following
statements.

2. For the statement: S = “Good Morning”, identify the


object and type of object. Also identify some operations
that can be performed on object, variable name and
operator name
3. If a = 10.6, what is the (1) type of object, and (2) value
it represents?
4. What will be the output when the following assignment
statements are executed?
a) x = 5
b) 5 = x
c) x = “this is green”
d) x, y = 2
e) x, y = 2, 4
f) x, y = “2”, 2
g) x = a + 5
h) x = y = z = 5
i) x, y, a, b = 2, 4
j) x=2=y=2

Multiple Choice Questions (MCQ)

1. Select the character not allowed in an identifier:


(i) a
(ii) 9
(iii) @
(iv) _ (underscore)
2. Find the incorrect identifier:
(i) SUM
(ii) Sum
(iii) sum2
(iv) 2sum
3. Identify the correct assignment:
(i) 6 = a
(ii) a + b =5
(iii) 6 – x = a
(iv) x = y + 5
4. Find the non-scalar object:
(i) −10
(ii) 5.67
(iii) “Hello”
(iv) True
5. Find the invalid integer:
(i) 5
(ii) −5
(iii) +5
(iv) 5.0
6. Find the invalid float:
(i) 5.0
(ii) −5.0
(iii) −5e3
(iv) 5
7. The output of “Bless You” * 2 is:
(i) Bless YouBless You
(ii) BlessBless YouYou
(iii) Bless You*2
(iv) Error

A.4 Bloom Level: Analyze


1. Consider the following statements:
a) x = 5 ------(1)
y = 10
x = 2 -------(2)
b) y = “Apple”
x = “Banana” ------(1)
x = “Carrot” -------(2)
Is the variable x in statement (1) and (2) the same variable? Justify your
answer.
2. What is the similarity or difference between the three
variables – Add, ADD and add?
3. What is the difference between the following variables:
a) _sum
b) _ _sum
c) _ _sum_ _
4. Differentiate between the following:
(a) Scalar objects and non-scalar objects
(b) Mutable objects and non-mutable objects

A.5 Bloom Level: Evaluate


1. Evaluate the following code critically in terms of Python
syntax.
a)

b)

c)

d)

2. Determine whether the code satisfies the requirements.


If not, state the reason and correct it.
a) Print the following:
1
12
123
Code
Print(“1”)
Print(“1”, “2”)
Print(“1”, “2”, “3”)
b) Print the following statement in a single line using
multi-line print statement.
“Mother Earth supports [Link] must take care of it;otherwise we
will suffer”
Code
print(“Mother Earth supports life.\
We must take care of it;\
otherwise we will suffer”)
c) Print the following statement as follows:
I am very beautiful.
Beauty lies within.
I am a pure soul.
Pure souls are always happy.
-----My strength is my inner beauty-----
Code
print(“I am very beautiful.”)
print(\t”Beauty lies within.”)
print(“I am a pure soul.”)
print(\t”Pure souls are always happy.”)
print(“-----My strength is my inner beauty----- “)

A.6 Bloom Level: Create/Synthesize


Programming Assignment

1. The value 70 is to be assigned to variables p, q, r. Write


an assignment statement to assign a single value to
multiple variables
2. The value 10 is to be assigned to variable x, and “Good
Morning” to variable s. Assign these values in a single
assignment statement.
3. Write a Python statement to print the id, type and value
of object 100.
4. Write a Python statement to:
a. Concatenate “You”, “are”, “beautiful” in a single
string.
b. Repeat string “Beautiful World” three times.
5. Write the command for printing a blank line.
6. Write a Python statement for printing “Hello World”.
7. Assign “Beautiful Sun” to a variable and print the value
of the variable.
8. Accept your name as input in a variable x. Print the
output as follows – “Your name” is a lovable person.
(Here, “Your name” should show your name).
9. Accept your name and age as input. Display output as
“Name” is “age” years old (Here, name and age should
show the input you have taken)
10. WAP to create the following pattern
a. 1
1 2
1 2 3
b.
1 2 3 4
2 3
1
c. 1
2
3
4

Answers
A.1 Bloom Level: Knowledge/Remember
Review Questions
9.
(1) c
(2) f
(3) b
(4) a
(5) g
(6) d
(7) h
(8) e

Fill in the Blanks


1. True, False
2. 33
3. Literals, Variables, Operators
4. Type
5. Type
6. Scalar. Non-scalar
7. Mutable
8. Int
9. Float
10. Str
11. Triple
12. \n
13. False
14. Print
15. Input
16. Space (“ “)
17. \
18. ;
19. Single, Multi
20. #
21. Three
22. Indentation

True/False
1. False
2. False
3. False
4. True
5. True
6. False
7. True
8. False
9. False
10. True
11. True
12. True
13. False
14. False
15. True
16. False
17. True
18. False
19. False

A.2. Bloom Level: Comprehend/Understand


Review Questions
5. Correct – (a), (b), (c), (j), (k)
6. Reserved – (a), (c), (e), (g), (i)
7. Scalar (a), (b)

Multiple Choice Questions (MCQ)


1. iii
2. iv

A.3. Bloom Level: Application/Apply


Review Questions
1.
o Literals – 55, 2
o Type of literals – int
o Variables – x, y, z
o Type of expression in third statement – Integer (Because both x and y
are integers)
o Operators used – Assignment operator (“=”)
o Binding of objects - binds RHS to LHS
• Object 55 is bind to x
• Object 2 is bind to y
• Object x-y is bind to z
2.
o Object “Good Morning”
o Type of object – string
o Some operation on object – String concatenation, string repetition
o Variable name – S
o Operator name – Assignment
3. Type is <float>
Value is 10.6
4.
(a) x is assigned value 5.
(b) Error. A literal cannot be assigned a value.
(c) x is assigned the string, “this is green”.
(d) Error. Cannot assign same integer value to two
literals.
(e) Assign 2 to x and 4 to y.
(f) Assign “2” to x and 2 to y.
(g) Error. Variable a does not have a value.
(h) x, y, z are assigned value 5.
(i) Error. Cannot assign same integer value to two
literals.
(j) Error. Cannot assign value to literal.

Multiple Choice Questions (MCQ)


1. iii
2. iv
3. iv
4. iii
5. iv
6. iv
7. i

A.5. Bloom Level: Evaluate


1. (a) Indentation error
(b) Invalid Identifier
(c) Correct. Uses single line and multiline comments.
(d) Correct. Continues a sentence on multiple lines.
2. (a) Required spacing will not be generated. A tab
should be used in print statement.
(b) Correct
(c) In statements 2 and 4, the “\t” should be within
quotes. There is error in the code.

You might also like