Problem Solving Concepts in Python
Problem Solving Concepts in Python
UNIT 1
2 MARKS
1
1. What is Computer Science?
➢ Computer Science is the study of computers and computational systems.
➢ Computer science is the study of processes hat interact with data and that can be
represented as data in the form of programs.
➢ It enables the use of algorithms to manipulate, store, and communicate digital
information.
➢ Basically, computer Science is computational problem solving —that is, solving
problems by the use of computation.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. What are the things are needed to solve problem computationally?
In order to solve a problem computationally, two things are needed:
1. a representation that captures all the relevant aspects of the problem, and
2. an algorithm that solves the problem by use of the representation.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
3. Define: Brute force approach. Given an
➢ Trying all possible solutions to a given problem is referred to as a brute force approach.
➢ Example problem is Man, Cabbage, Goat, Wolf problem.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. Define: Abstraction
➢ Collection of all possibilities solution of any problem omit the irrelevant details is being
represented in a form of abstraction.
➢ An abstraction means, only showing the relevant features of the problem.
➢ Example, In Man, Cabbage, Goat, Wolf problem, the color of the boat the width of the
river, the name of the man is irrelevant information.
➢ We can omit these details before solving a problem.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5. What Is an Algorithm?
➢ An algorithm is a well-defined procedure that allows a computer to solve a problem.
➢ Another way to describe an algorithm is a sequence of unambiguous instructions.
➢ An algorithm is a finite number of clearly described, unambiguous “doable” steps that
can be systematically followed to produce a desired result for given input in a finite
amount of time.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2
6. What is computer hardware?
➢ Computer hardware comprises the physical part of a computer system.
➢ It includes the all-important components of the central processing unit (CPU) and main
memory.
➢ It also includes peripheral components such as a keyboard, monitor, mouse, and printer.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
7. What is binary representation?
➢ All information within a computer system is represented using only two digits, 0 and
1, called binary representation.
➢ Base 2 has digits 0 and 1, with place values that are powers of two.
➢
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
8. Define bit and byte.
➢ The term bit stands for binary digit. Therefore, every bit has the value 0 or 1.
➢ A byte is a group of binary digits or bits (usually eight bits) operated on as a unit.
➢ The algorithm for the conversion from base 10 to base 2 is to successively divide a
number by two until the remainder becomes 0.
(18)10 → ( ? )2
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
3
9. Define CPU
The central processing unit (CPU) is the “brain” of a computer, containing digital logic
circuitry able to interpret and execute instructions.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
➢ In Main memory currently executing programs are reside, in which the CPU can
directly and very quickly access.
➢ Main memory is volatile; that is, the contents are lost when the power is turned off.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. What is Secondary Memory?
➢ Secondary memory is nonvolatile, and it provides long-term storage of programs and
data.
➢ This kind of storage, for example, can be magnetic (hard drive), optical (CD or DVD),
or nonvolatile flash memory (such as in a USB drive).
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
12. Write the examples of input/output devices.
➢ Input/output devices include anything that allows for input (such as the mouse and
keyboard) or output (such as a monitor or printer).
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
13. What is Operating System.
➢ An operating system is software that has the job of managing and interacting with the
hardware resources of a given computer and providing a particular user interface.
➢ Because an operating system is intrinsic to the operation a computer, it is referred to
as system software.
➢ An operating system acts as the “middle man” between the hardware and executing
application programs.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
14. What is computer software?
➢ Computer software is a set of program instructions, including related data and
documentation, that can be executed by computer.
➢ This can be in the form of instructions on paper, or in digital form.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4
15. What Are Syntax and Semantics?
➢ The syntax of a language is a set of characters and the acceptable sequences of those
characters.
➢ The semantics of a language is the meaning associated with each syntactically correct
sequence of characters.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
16. What is machine code?
➢ A central processing unit (CPU) is designed to interpret and execute a specific set of
instructions represented in binary form (i.e., 1s and 0s) called machine code.
➢ Only programs in machine code can be executed by a CPU, depicted in Figure 1-19.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
17. Define Translator and types of translator.
➢ A program written in high-level language is called as source code.
➢ To convert the source code into machine code, translators are needed.
➢ A translator takes a program written in source language as input and converts it into a
program in target language as output.
➢ It also detects and reports the error during translation.
➢ Two types of translator. They are: 1. Compiler 2: Interpreter.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
18. What is compiler?
➢ A compiler is a translator program that translates programs directly into machine code
to be executed by the CPU.
➢ Compiler is a translator which is used to convert programs in high-level language to
low-level language.
➢ It translates the entire program and also reports the errors in source program
encountered during the translation.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5
19. What is Interpreter?
➢ Interpreter is a translator which is used to convert programs in high-level language to
low-level language.
➢ Interpreter translates line by line and reports the error once it encountered during the
translation process.
➢ Thus, an interpreter can immediately execute instructions as they are entered. This is
referred to as interactive mode.
➢ Python is executed by an interpreter.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
20. What is program debugging?
Program debugging is the process of finding and correcting errors (“bugs”) in a
computer program.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
21. What is Syntax Error and Semantic error?
➢ Syntax errors are caused by invalid syntax.
➢ Semantic (logic) errors are caused by errors in program logic.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
22. What is IDE?
An Integrated Development Environment (IDE) is a bundled set of software tools for
program development.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
23. Define Variable.
➢ A variable is a name that is assigned to a value.
Examples:
➢ n = 5 variable n is assigned the value 5.
➢ n=10
➢ n + 20 (10 + 20)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
24. What are the arithmetic operators?
➢ The common arithmetic operators in Python are + (addition), - (subtraction),
* (multiplication), / (division), and ** (exponentiation).
6
Examples:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
25. Define input function in python.
➢ In Python, input is used to request and get information from the user.
name = input('What is your name?: ')
➢ Characters within quotes are called strings.
➢ This particular use of a string, for requesting input from the user, is called a prompt.
➢ The input function displays the string on the screen to prompt the user for input,
What is your name?: Charles
➢ The underline is used here to indicate the user’s input.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
26. Define Print function in python.
➢ In Python, print function is used to display information on the screen.
➢ This may be used to display a message,
>>> print('Welcome to My First Program!')
Welcome to My First Program!
➢ or used to output the value of a variable,
>>> n = 10
>>> print(n)
10
➢ or to display a combination of both strings and variables,
>>> name 5 input('What is your name?: ')
What is your name?: Charles
>>> print('Hello', name)
Hello Charles
➢ Note that a comma is used to separate the individual items being printed, causing a
space to appear between each when displayed.
7
Thus, the output of the print function in this case is Hello Charles, and not HelloCharles.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
27. What is comment statement in Python?
➢ Comment statement contains information for persons reading the program.
➢ Comment statements are ignored during program execution—they have no effect on
the program results.
➢ The program lines beginning with the hash sign, #.
➢ In Python, # symbol is used to denote a comment statement.
Example,
# Sample program in python
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
28. Convert (1010)2 to Decimal
(1010)2 = (1×23) + (0×22) + (1×21) + (0×20)
=8+0+2+0
(1010)2 = (10)10 or (10)d
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
29. What Is a Literal? What are the types of Literal?
➢ A literal is a sequence of one or more characters that stands for itself. There are 2
types of Literal. They are:
1. Numeric Literal
2. String Literal
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
30. What is numeric Literal?
➢ A numeric literal is a literal containing only the digits 0–9, a sign character (+ or -)
and a possible decimal point.
➢ Commas are never used in numeric literals.
➢ If a numeric literal contains a decimal point, then it denotes a floating-point value, or
“float” (e.g., 10.24); otherwise, it denotes an integer value (e.g., 10).
8
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
31. What is Built-in Format function in Python?
➢ The built-in format function can be used to produce a numeric string of a given
floating-point value rounded to a specific number of decimal places.
➢ Examples,
>>>12/5 >>> 5/7
2.4 0.7142857142857143
>>> format (12/5, '.2f') >>>format (5/7, '.2f')
'2.40' '0.71'
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
32. What is String Literal?
➢ A string literal, or string, is a sequence of characters denoted by a pair of matching
single or double (and sometimes triple) quotes in Python.
➢ A string consisting of only a pair of matching quotes (with nothing in between) is called
the empty string, which is different from a string containing only blank characters.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
33. What is control character in python?
➢ Control characters are nonprinting characters used to control the display of output .
➢ Control characters are special characters that are not displayed on the screen.
➢ Control characters do not have a corresponding keyboard character.
➢ Therefore, they are represented by a combination of characters called an escape
sequence.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
34. What is escape sequence in Python?
➢ An escape sequence begins with an escape character that causes the sequence of
characters following it to “escape” their normal meaning.
➢ The backslash (\) serves as the escape character in Python.
9
➢ For example, the escape sequence '\n', represents the newline control character , used
to begin a new screen line.
➢ An example of its use is given below,
print('Hello\nJennifer Smith') which is displayed as follows,
Hello
Jennifer Smith
➢ An escape sequence is a string of one or more characters used to denote control
characters.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
35. What is String Formatting?
➢ The format function can be used to control how strings are displayed.
➢ Syntax is,
format (value, format_specifier)
Where,
value is the value to be displayed,
format_specifier can contain a combination of formatting options.
For example,
1. To produce the string 'Hello' left-justified in a field width of 20 characters would be done
as follows,
format('Hello', ' < 20') ➝ 'Hello '
2. To right-justify the string, the following would be used,
format('Hello', ' > 20') ➝ ' Hello'
Formatted strings are left-justified by default.
3. To center the string the '^' character is used:
format('Hello', '^20').
➢ Another use of the format function is to create strings of blank characters, which is
sometimes useful,
format(' ', '30') ➝ '
➢ Finally blanks, by default, are the fill character for formatted strings. However, a
specific fill character can be specified as shown below,
>>>print('Hello World', format('.', '. < 30'), 'Have a Nice Day!')
Hello World .............................. Have a Nice Day!
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
10
36. What is implicit line joining?
➢ There are certain delimiting characters that allow a logical program line to span more
than one physical line.
➢ This includes matching parentheses, square brackets, curly braces, and triple quotes.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
37. What is explicit line joining?
➢ program lines may be explicitly joined by use of the backslash (\) character.
➢ Program lines that end with a backslash that are not part of a literal string (that is,
within quotes) continue on the following line.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
38. What is a Variable?
➢ A variable is a name (identifier) that is associated with a value.
➢ Variables are assigned values by use of the assignment operator =,
Ex: num = 10 ; num = num + 1
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
39. What is an identifier?
➢ An identifier is a sequence of one or more characters used to name a given program
element.
➢ In Python, an identifier may contain letters and digits, but cannot begin with a digit.
➢ The special underscore character can also be used.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
40. What is keyword?
➢ A keyword is an identifier that has predefined meaning in a programming language.
➢ Therefore, keywords cannot be used as “regular” identifiers.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11
41. What Is an Operator?
➢ An operator is a symbol that represents an operation that may be performed on one or
more operands.
➢ Operators that take one operand are called unary operators. Operators that take two
operands are called binary operators.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
42. What are arithmetic operators?
The + ,- , * (multiplication) and / (division) arithmetic operators perform the usual operations.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
43. What is division operator?
➢ The division operator, /, produces “true division” regardless of its operand types.
➢ The truncating division operator, //, produces either an integer or float truncated
result based on the type of operands applied to.
➢ The modulus operator (%) gives the remainder of the division of its operands.
Ex:
1) 25 /10 = 2.5
2) 25 // 10 = 2
3) 29 % 12=5
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
44. What Is an Expression?
➢ An expression is a combination of symbols that evaluates to a value.
➢ Expressions, most commonly, consist of a combination of operators and operands,
Ex: 4 + (3 * k)
➢ An expression can also consist of a single literal or variable.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
45. What is operator precedence?
Operator precedence is the relative order that operators are applied in the evaluation of expressions.
12
Fig: Operator Precedence of Arithmetic Operators in Python
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
46. What is operator associativity?
Operator associativity is the order that operators are applied when having the same level of
precedence, specific to each operator.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
47. What is data type? What are the types of data types?
➢ A data type is a set of values, and a set of operators that may be applied to those values.
➢ There are two approaches to data typing in programming languages.
1. Static Type
2. Dynamic Type
Static type:
➢ It is a variable is declared as a certain type before it is used, and can only be assigned
values of that type.
Dynamic type:
➢ The variable may be assigned values of different type during the execution of a
program.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
13
PROBLEM SOLVING USING PYTHON
UNIT 1
5 MARKS
14
1. Explain about computer algorithm?
15
Fundamental Hardware Components.
= = = = = == = = == == == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = =
3. Discuss about operating system.
➢ An operating system is a program that acts as an interface between the user and the
computer hardware and controls the execution of all kinds of programs.
➢ An operating system is intrinsic to the operation a computer; it is referred to as system
software.
➢ An operating system acts as the “middle man” between the hardware and executing
application programs as shown in the following figure.
16
➢ For example, it controls the allocation of memory for the various programs that may be
executing on a computer.
➢ Operating systems also provide a particular user interface.
➢ Thus, it is the operating system installed on a given computer that determines the “look
and feel” of the user interface and how the user interacts with the system.
= = = = = == = = == == == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = =
4. What Are Syntax, Semantics and translation?
➢ The syntax of a language is a set of characters and the acceptable sequences of those
characters.
➢ The semantics of a language is the meaning associated with each syntactically correct
sequence of characters.
➢ In English, for example, includes the letters of the alphabet, punctuation, and
properly spelled words and properly punctuated sentences.
➢ The following is a syntactically correct sentence in English,
“Hello there, how are you?”
➢ The following, however, is not syntactically correct,
“Hello there, hao are you?”
➢ In this sentence, the sequence of letters “hao” is not a word in the English language.
Now consider the following sentence,
“Colorless green ideas sleep furiously.”
➢ This sentence is syntactically correct, but is semantically incorrect, and thus has no
meaning.
Program Translation
➢ A central processing unit (CPU) is designed to interpret and execute a specific set of
instructions represented in binary form (i.e., 1s and 0s) called machine code.
➢ Only programs in machine code can be executed by a CPU, depicted in the following
Figure.
17
➢ A translator takes a program written in source language as input and converts it into a
program in target language as output.
➢ It also detects and reports the error during translation.
➢ Two types of translator. They are: 1. Compiler 2: Interpreter.
Compiler
➢ A compiler is a translator program that translates programs directly into machine code
to be executed by the CPU.
➢ Compiler is a translator which is used to convert programs in high-level language to
low-level language.
➢ It translates the entire program and also reports the errors in source program
encountered during the translation.
Interpreter
➢ Interpreter is a translator which is used to convert programs in high-level language to
low-level language.
➢ Interpreter translates line by line and reports the error once it encountered during the
translation process.
➢ Thus, an interpreter can immediately execute instructions as they are entered. This is
referred to as interactive mode.
➢ Python is executed by an interpreter.
= = = = = == = = == == == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = =
5. Explain about Python programming language?
➢ Python is a widely used high-level programming language general purpose
programming language created by Guido Van Rossum from CWI (Centrum Wiskunde
& Informatica) which is a National Research Institute for Mathematics and Computer
Science in Netherlands.
➢ The language was first released in I990.
➢ Its name comes from a 1970s British comedy sketch television show called Monty
Python’s Flying Circus.
➢ Python supports both Procedural and Object-Oriented programming approaches.
➢ Python has a simple syntax.
➢ Python programs are clear and easy to read.
➢ At the same time, Python provides powerful programming features, and is widely used.
18
➢ Companies and organizations that use Python include YouTube, Google, Yahoo, and
NASA.
The IDLE Python Development Environment
➢ IDLE is an integrated development environment (IDE).
➢ An IDE is a bundled set of software tools for program development.
➢ This typically includes an editor for creating and modifying programs, a translator for
executing programs, and a program debugger.
➢ A debugger provides a means of taking control of the execution of a program to aid in
finding program errors.
➢ Python is most commonly translated by use of an interpreter.
➢ Thus, Python provides the very useful ability to execute in interactive mode.
➢ The window that provides this interaction is referred to as the Python shell.
Python Shell
= = = = = == = = == == == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = =
6. What is Literal? Explain its types.
➢ A literal is a sequence of one or more characters that stands for itself. There are 2
types of Literal. They are:
3. Numeric Literal
4. String Literal
Numeric Literal
➢ A numeric literal is a literal containing only the digits 0–9, a sign character (+ or -)
and a possible decimal point.
➢ Commas are never used in numeric literals.
➢ If a numeric literal contains a decimal point, then it denotes a floating-point value, or
“float” (e.g., 10.24); otherwise, it denotes an integer value (e.g., 10).
19
String Literal
➢ A string literal, or string, is a sequence of characters denoted by a pair of matching
single or double (and sometimes triple) quotes in Python.
➢ A string consisting of only a pair of matching quotes (with nothing in between) is called
the empty string, which is different from a string containing only blank characters.
= = = = = = = = = == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = =
7. Explain program Debugging.
➢ Program debugging is the process of finding and correcting errors (“bugs”) in a
computer program.
➢ There are two types of errors:
1. Syntax Errors
2. Semantic Errors
Syntax errors:
➢ Syntax errors are caused by invalid syntax (for example, entering prnt instead of print).
➢ Since a translator cannot understand instructions containing syntax errors, translators
terminate when encountering such errors indicating where in the program the problem
occurred.
Semantic Errors:
➢ In contrast, semantic errors (generally called logic errors ) are errors in program logic.
➢ Such errors cannot be automatically detected, since translators cannot understand the
intent of a given computation.
➢ For example, if a program computed the average of three numbers as follows,
➢ (num1 + num2 + num3) / 2.0
20
➢ translator would have no means of determining that the divisor should be 3 and not 2.
= = = = = = = = = == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = =
8. Explain input and output functions in python?
Input Function
➢ In Python, input is used to request and get information from the user.
name = input('What is your name?: ')
➢ Characters within quotes are called strings.
➢ This particular use of a string, for requesting input from the user, is called a prompt.
➢ The input function displays the string on the screen to prompt the user for input,
What is your name?: Charles
➢ The underline is used here to indicate the user’s input.
Output Function
➢ In Python, print function is used to display information on the screen.
➢ This may be used to display a message,
>>> print('Welcome to My First Program!')
Welcome to My First Program!
➢ or used to output the value of a variable,
>>> n = 10
>>> print(n)
10
➢ or to display a combination of both strings and variables,
>>> name 5 input('What is your name?: ')
What is your name?: Charles
>>> print('Hello', name)
Hello Charles
➢ Note that a comma is used to separate the individual items being printed, causing a
space to appear between each when displayed.
Thus, the output of the print function in this case is Hello Charles, and not HelloCharles.
= = = = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
9. What are the arithmetic operators in python? Explain.
➢ An operator is a symbol that represents an operation that may be performed on one
or more operands.
➢ Operators that take one operand are called unary operators.
➢ Operators that take two operands are called binary operators.
21
➢ The common arithmetic operators in Python are + (addition), - (subtraction),
* (multiplication), / (division), and ** (exponentiation).
22
print(mod)
print(p)
Output:
13
5
36
2.25
2
1
6561
= = = = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
10. Explain Operator Precedence and Operator Associativity.
➢ This is used in an expression with more than one operator to determine which operation
is to perform first.
➢ This order of execution of operators in the expression is called as operator Precedence.
Example 1:
Example 2:
Here multiplication is performed before addition when no parentheses are included,
4+3*5
= 4 + 15
23
= 19
In our example, therefore, if the addition is to be performed first, parentheses would be
needed,
(4 + 3) * 5
= 7*5
= 35
Operator Associativity:
➢ If an expression contains two or more operators with the same precedence then Operator
Associativity is used to determine.
➢ It can either be Left to Right or from Right to Left.
Example:
100 / 10 * 10
Here / and * both have same precedence but Left to Right associativity is applied.
Therefore,
100 / 10 * 10
= 10 * 10 = 100
= = = = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. Explain Coercion and Type Conversion.
Coercion:
➢ Coercion is the automatic or implicit conversion of values from one data type to another
(such as strings to numbers).
➢ Coercion is automatically performed on mixed-type expressions only if the operands
can be safely converted, that is, if no loss of information will result.
➢ The conversion of integer 2 to floating-point 2.0 is a safe conversion.
➢ The conversion of 4.5 to integer 4 is not safe, since the decimal digit would be lost.
Type Conversion
➢ Type conversion is the explicit conversion of operands to a specific type.
➢ Type conversion can be applied even if loss of information results.
➢ Python provides built-in type conversion functions int() and float(), with the int()
function truncating results as given in following figure.
24
Conversion Functions int() and float() in Python
= = = = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
12. What is data type? Explain its types?
➢ A data type is a set of values, and a set of operators that may be applied to those values.
➢ For example, the integer data type consists of the set of integers.
➢ Integers, floats, and strings are part of a set of predefined data types in Python called
the built-in types.
➢ There are two approaches to data typing in programming languages.
1. Static typing
2. Dynamic typing
Static Typing
➢ Static typed programming languages are those in which variables need not be defined
before they’re used.
Dynamic Typing
➢ Dynamic typed programming languages are those languages in which variables must
necessarily be defined before they are used.
➢ Thus, the same variable may be assigned values of different type during the execution
of a program.
➢ Python is an example of a dynamic typed programming language.
= = = = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
25
PROBLEM SOLVING USING PYTHON
UNIT 1
10 MARKS
26
1. Explain Brute Force approach with example.
OR
Explain about Essence of Computational Problem Solving.
➢ Trying all possible solutions to a given problem is referred to as a brute force
approach.
➢ Example problem is Man, Cabbage, Goat, Wolf problem.
➢ In order to solve a problem computationally, two things are needed:
1) Representation that captures all the relevant aspects of the problem
2) An algorithm that solves the problem by use of the representation.
➢ Consider a problem known as the Man, Cabbage, Goat, Wolf problem.
➢ A man has to take a wolf, a goat, and some cabbage across a river. His rowboat has
enough room for the man plus either the wolf or the goat or the cabbage. If he takes the
cabbage with him, the wolf will eat the goat. If he takes the wolf, the goat will eat the
cabbage. Only when the man is present are the goat and the cabbage safe from their
enemies. All the same, the man carries wolf, goat, and cabbage across the river. How?
➢ There is a simple algorithmic approach for solving this problem by simply trying all
possible combinations of items that may be rowed back and forth across the river.
Trying all possibilities until the solution to a problem is found is referred to as a brute
force approach.
➢ From all possibilities collection omit the irrelevant details is being represented in a form
of abstraction. An abstraction means, only showing the relevant features of the
problem. In this problem, the color of the boat the width of the river, the name of the
man are irrelevant information. We can omit these details before solving a problem. In
the table below I have listed a set of moves for the Farmer-Wolf-Goat-Cabbage riddle.
We are using the symbols F, W, G, and C to stand for the Farmer, Wolf, Goat, and
Cabbage respectively.
27
move left river bank right river bank
Farmer takes the Goat to the right river bank _W_C F_G_
Farmer takes the Wolf to the right river bank ___C FWG_
Farmer takes the goat across. Exit state reached! ____ FWGC
= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =
28
1. Problem Analysis
1.1 Understanding the Problem
➢ Once a problem is clearly understood, the fundamental computational issues for solving
it can be determined.
➢ For example,
➢ For the Man, Cabbage, Goat, Wolf (MCGW) problem, a brute-force algorithmic
approach of trying all possible solutions works very well, since there are a small number
of actions that can be taken at each step, and reaching a solution.
➢ For both the Traveling Salesman problem and the game of chess, the brute-force
approach is infeasible.
➢ Thus, the computational issue for these problems is to find other, more efficient
algorithmic approaches.
1.2 Knowing What Constitutes a Solution
➢ Besides clearly understanding a computational problem, one must know what
constitutes a solution.
➢ For some problems, there is only one solution. For others, there may be a number (or
infinite number) of solutions.
➢ Thus, a program may be stated as finding,
A solution
An approximate solution
A best solution
All solutions
➢ For the Man, Cabbage, Goat, Wolf problem, there are an infinite number of solutions
since the man could pointlessly row back and forth across the river an arbitrary number
of times. A best solution here is one with the shortest number of steps. (There may be
more than one “best” solution for any given problem.)
➢ In the Traveling Salesman problem there is only one solution (unless there exists more
than one shortest route).
➢ Finally, for the game of chess, the goal (solution) is to win the game. Thus, since the
➢ number of chess games that can be played is on the order of 10 120 (with each game
ending in a win, a loss, or a stalemate), there are a comparable number of possible
solutions to this problem.
29
2. Program Design
2.1 Describing the Data Needed
➢ For the Man, Cabbage, Goat, Wolf problem, a list can be used to represent the correct
location (east and west) of the man, cabbage, goat, and wolf , which is reproduced
below,
Man Cabbage Goat wolf
W E W E
2.2 Describing the Needed Algorithms
➢ When solving a computational problem, either suitable existing algorithms may be
found or new algorithms must be developed.
➢ For the Man, Cabbage, Goat, Wolf problem, there are standard search algorithms that
➢ can be used.
➢ For the Traveling Salesman problem, there are various (nontrivial) algorithms that can
be utilized, as mentioned, for solving problems with tens of thousands of cities.
➢ Finally, for the game of chess, since it is infeasible to look ahead at the final outcomes
of every possible move, there are algorithms that make a best guess at which moves to
make.
➢ Algorithms that work well in general but are not guaranteed to give the correct result
for each specific problem are called heuristic algorithms.
3. Program Implementation
➢ In the implementation state, we have to specify which programming language to use,
or how to implement the program.
➢ Since we are programming in Python, the implementation needs to be expressed in a
syntactically correct and appropriate way, using the instructions and features available
in Python.
4. Program Testing
➢ Programming errors are pervasive, persistent and inevitable.
➢ Software testing is a crucial part of software development.
➢ Testing is done incrementally as a program is being developed, when the program is
complete, and when the program needs to be updated.
➢ For now, we provide the following general truisms of software development in the
following Figure
30
= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Operator
➢ The common arithmetic operators in Python are + (addition), - (subtraction),
* (multiplication), / (division), and ** (exponentiation).
➢ Assume variable a = 10 and variable b = 20,
Operator Description Example
+ Addition adds two values a + b = 30
- Subtraction Subtracts the two values a – b = -10
*
Multiplies the two values a * b = 200
Multiplication
/ Division Divides the first value by the second b/a=2
returns the remainder when first
% Modulus b%a=0
value is divided by the second
** Exponent Returns first raised to power second a**b =10 to the power 20
Floor Division Divides the first value
by the second , where the result is the
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4,
// quotient in which the digits after the
-11.0//3 = -4.0
decimal point are removed. But if
one of the operands is negative, the
31
result is floored, i.e., rounded away
from zero (towards negative infinity)
−
Assignment Operators
Assignment operators are used to assign values to variables:
➢ Assume variable a = 10 and variable b = 20,
Comparison Operators
➢ Comparison operators are used to compare two values. They are also called Relational
operators.
➢ Assume variable a = 10 and variable b = 20,
32
If the value of left operand is greater
> than the value of right operand, then (a > b) is not true.
condition becomes true.
If the value of left operand is less than
< the value of right operand, then (a < b) is true.
condition becomes true.
If the value of left operand is greater
>= than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
If the value of left operand is less than
<= or equal to the value of right operand, (a <= b) is true.
then condition becomes true.
Logical Operators
➢ Logical operators are used to combine conditional statements
➢ Assume variable a = 10 and variable b = 20,
Operator Description Example
and Logical If both the operands are true then
(a and b) is true.
AND condition becomes true.
or Logical If any of the two operands are non-
(a or b) is true.
OR zero then condition becomes true.
not Logical Used to reverse the logical state of
Not(a and b) is false.
NOT its operand.
Identity Operators
➢ Identity operators compare the memory locations of two objects, not if they are equal,
but if they are actually the same object, with the same memory location.
Membership Operators
➢ Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples.
33
Returns True if a sequence with the
x not in y, here not in results in a 1 if x is
not in specified value is not present in the
not a member of sequence y.
object
Bitwise Operators
➢ Bitwise operators are used to compare (binary) numbers.
➢ Bitwise operator works on bits and performs bit by bit operation.
➢ Assume if a = 60; and b = 13;
➢ Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
a = 0 0 1 1 1 1 0 0
b = 0 0 0 0 1 1 0 1
- - - - - - - - - - - -
a & b = 0 0 0 0 1 1 0 0
a | b = 0 0 1 1 1 1 0 1
a ^ b = 0 0 1 1 0 0 0 1
~ a = 1 1 0 0 0 0 1 1
Operator Description Example
& Binary AND Sets each bit to 1 if both bits are 1 (a & b) (means 0000 1100)
Sets each bit to 1 if one of two bits
| Binary OR (a | b) = 61 (means 0011 1101)
is 1
Sets each bit to 1 if only one of
^ Binary XOR (a ^ b) = 49 (means 0011 0001)
two bits is 1
~ Binary Ones (~a ) = -61 (means 1100 0011 in 2's
Complement Inverts all the bits complement form due to a signed binary
NOT number.
Shift left by pushing zeros in from
<< Binary Left
the right and let the leftmost bits a << 2 = 240 (means 1111 0000)
Shift
fall off
Shift right by pushing copies of the
>> Binary
leftmost bit in from the left, and let a >> 2 = 15 (means 0000 1111)
Right Shift
the rightmost bits fall off
= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =
34
Boolean Type bool
Binary Types bytes, bytearray, memoryview
Python Numbers
➢ Integers, floating point numbers and complex numbers
➢ They are defined as int, float and complex classes in Python.
➢ We can use the type() function to know which class a variable or a value belongs to.
➢ Similarly, the isinstance() function is used to check if an object belongs to a
particular class.
➢ Example 1:
a=5
print(a, "is of type", type(a))
Output
5 is of type <class 'int'>
➢ Example 2:
a = 2.0
print(a, "is of type", type(a))
Output
2.0 is of type <class 'float'>
➢ Example 3:
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output
(1+2j) is complex number? True
Example:
>>> float(5)
5.0
>>> int(10.6)
10
>>> int(-10.6)
-10
Python List
➢ List is an ordered sequence of items.
➢ All the items in a list do not need to be of the same type.
➢ Declaring a list , Items separated by commas are enclosed within brackets [ ].
35
➢ a = [1, 2.2, 'python']
➢ We can use the slicing operator [ ] to extract an item or a range of items from a list.
➢ The index starts from 0 in Python.
Example 1:
➢ a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
Output
a[2] = 15
Example 2:
➢ a = [5,10,15,20,25,30,35,40]
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
Output
a[0:3] = [5, 10, 15]
Example 3:
➢ a = [5,10,15,20,25,30,35,40]
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
Output
➢ a[5:] = [30, 35, 40]
➢ Lists are mutable, meaning, the value of elements of a list can be altered.
Python Tuple
➢ Tuple is an ordered sequence of items same as a list.
➢ The only difference is that tuples are immutable. Tuples once created cannot be
modified.
➢ It is defined within parentheses () where items are separated by commas.
➢ We can use the slicing operator [] to extract items but we cannot change its value.
Example:
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
Output
36
t[1] = program
Example:
t = (5,'program', 1+3j)
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
Output
➢ Just like a list and tuple, the slicing operator [ ] can be used with strings.
➢ Strings, however, are immutable.
Example 1:
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
Output:
s[4] = o
Example 2:
s = 'Hello world!'
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
Output:
s[6:11] = world
37
Python Set
Example:
a = {5,2,3,1,4}
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
➢ Since, set are unordered collection, indexing has no meaning.
➢ Hence, the slicing operator [] does not work.
Python Dictionary
➢ Dictionary is an unordered collection of key-value pairs.
➢ In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value.
➢ Key and value can be of any type.
Example:
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
Example 2:
d = {1:'value','key':2}
print("d[1] = ", d[1]);
Output:
d[1] = value
= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =
38
39
PROBLEM SOLVING USING PYTHON
UNIT 2
2 MARKS
1
1. What is Control Structure?
➢ Control flow is the order that instructions are executed in a program.
➢ A control statement is a statement that determines the control flow of a set of
instructions.
➢ Collectively a set of instructions and the control statements controlling their execution
is called a control structure.
➢ There are three fundamental forms of control that programming languages:
1. Sequential control,
2. Selection control
3. Iterative control.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. What is Sequential Control?
➢ In Sequential control instructions are executed in the order that they are written.
➢ A program consisting of only sequential control is referred to as a “straight-line
program.”
= = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = =
3. What is Selection Control?
➢ Selection Control is provided by a control statement that selectively executes
instructions.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. What is Iterative Control?
➢ Iterative control is provided by an iterative control statement that repeatedly executes
instructions.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5. What is Boolean Expression?
➢ The Boolean data type contains two Boolean values, denoted as True and False in
Python.
➢ A Boolean expression is an expression that evaluates to a Boolean value.
2
➢ Boolean expressions are used to denote the conditions for selection and iterative
control statements.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. What is Relational operator?
➢ Relational expressions are a type of Boolean expression, since they evaluate to a
Boolean result.
➢ The relational operators in Python perform the usual comparison operations, shown in
the following figure.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
7. What is Membership Operators?
➢ These operators can be used to easily determine if a particular value occurs within a
specified list of values.
➢ The membership operators are given in following.
3
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
9. Write about operator precedence of arithmetic, relational and Boolean operators.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
10. Explain IF statement with example.
➢ IF statement is a selection control statement based on the value of a given Boolean
expression.
➢ The IF statement in Python is depicted below.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. What is Indentation in Python?
➢ It is used to align program lines to aid readability.
➢ In Python, however, indentation is used to associate and group statements, as shown
following.
4
➢ A header in Python starts with a keyword and ends with a colon.
➢ The group of statements following a header is called a suite.
➢ A header and its associated suite are together referred to as a clause.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
12. What are Multi-Way Selection?
1. multiple nested if statements
2. single if statement
3. elif headers.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
13. What is Nested if Statement?
➢ Any number of IF statements can be nested inside one another with ELSE statement is
called Nested IF statement.
➢ IF statements can be nested, resulting in multi-way selection.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
14. What is elif Header in Python?
➢ The elif is short for ELSE IF.
➢ It allows us to check for multiple expressions.
5
➢ If the condition for IF is False, it checks the condition of the next elif block and so on.
➢ If all the conditions are False, the body of else is executed.
➢ The IF block can have only one else block. But it can have multiple elif blocks.
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Example:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
15. Explain IF statement?
Syntax:
if test expression:
statement(s)
➢ The program evaluates the test expression and will execute statement(s) only if the test
expression is True.
➢ If the test expression is False, the statement(s) is not executed.
Example:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
16. What is IF….ELSE statement?
Syntax:
IF test expression:
Body of if
else:
Body of else
6
➢ The IF..ELSE statement evaluates test expression and will execute the body of if only
when the test condition is True.
➢ If the condition is False, the body of else is executed.
➢ Indentation is used to separate the blocks.
Example:
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
17. What is iterative control statement?
➢ The iterative statements are used to execute a part of the program repeatedly as long as
a given condition is True.
➢ Iterative control structures are also known as looping statements or repetitive
statements.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
18. What is WHILE statement?
➢ A WHILE statement is an iterative control statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition).
Syntax:
while condition:
Suite/ Statement1
Statement 2
………..
Example:
i=1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
7
5
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
25. What is a List?
➢ A list is a linear data structure, that its elements have a linear ordering. That is, there
is a first element, a second element, and so on.
➢ Example:
➢ The above example is list storing the average temperature for each day of a given week,
in which each item in the list is identified by its index value.
➢ The location at index 0 stores the temperature for Sunday, the location at index 1 stores
the temperature for Monday, and so on.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
26. What are List operations?
Operations commonly performed on lists include retrieve, update, insert, remove, and append.
9
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
27. Write note on: List Traversal.
➢ A list traversal is accessing of one-by-one elements from a list.
➢ For example, to add up all the elements in a list of integers, each element can be
accessed one-by-one, starting with the first, and ending with the last element.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
10
28. Write a note on List type in Python.
➢ A list in Python is a mutable, linear data structure of variable length, allowing mixed-
type elements.
➢ Mutable means that the contents of the list may be altered.
➢ Lists in Python use zero-based indexing. Thus, all lists have index values 0 ... n-1,
where n is the number of elements in the list.
➢ Lists are denoted by a comma-separated list of elements within square brackets as
shown below:
[1, 2, 3] ['one', 'two', 'three'] ['apples', 50, True]
➢ An empty list is denoted by an empty pair of square brackets, [].
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
[Link]: Tuples.
➢ A tuple in Python is an immutable linear data structure, denoted by a comma-
separated list of elements within parentheses, allowing mixed-type elements.
Example:
1. nums =(10, 20, 30)
2. student = ('John Smith', 48, 'Computer Science', 3.42)
➢ Tuples of one element must include a comma following the element.
CORRECT WRONG
>>> (1,) >>> (1)
OUTPUT:
(1) 1
➢ An empty tuple is represented by a set of empty parentheses, ().
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
30. Write a note on Sequences.
➢ A sequence in Python is a linearly ordered set of elements accessed by an index
number.
➢ Lists, tuples, and strings are all sequences.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
31. What is Nested Lists?
➢ Lists and tuples can contain elements of any type, including other sequences.
➢ Thus, lists and tuples can be nested to create arbitrarily complex data structures.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11
32. What is index variable?
An index variable is a variable whose changing value is used to access elements of an indexed
data structure.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
33. What is assigning list in Python?
➢ when a variable is assigned to another variable holding a list, list2 =list1, each variable
ends up referring to the same instance of the list in memory.
Assignment of List
Example:
>>>list1 = [10, 20, 30, 40]
>>>list2 = list1
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
34. What is copying of list in Python?
➢ Copy of a list can be made as given below,
list2 = list(list1)
➢ In this case, we get the following results,
>>>list1 = [10, 20, 30, 40]
>>> list2 = list(list1)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
35. Define: List comprehensions in Python.
➢ List comprehensions in Python provide a concise means of generating a more varied
set of sequences than those that can be generated by the range function.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
12
PROBLEM SOLVING USING PYTHON
UNIT 2
5 &10 MARKS
13
1. Discuss about Control Structure?
➢ Control flow is the order that instructions are executed in a program.
➢ A control statement is a statement that determines the control flow of a set of
instructions.
➢ Collectively a set of instructions and the control statements controlling their execution
is called a control structure.
➢ There are three fundamental forms of control that programming languages:
1. Sequential control,
2. Selection control
3. Iterative control.
Sequential Control:
➢ In Sequential control instructions are executed in the order that they are written.
➢ A program consisting of only sequential control is referred to as a “straight-line
program.”
Selection Control
➢ Selection Control is provided by a control statement that selectively executes
instructions.
Iterative Control
➢ Iterative control is provided by an iterative control statement that repeatedly executes
instructions.
14
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Explain Selection Control.
➢ In Python, the selection statements are also known as decision making statements or
branching statements.
➢ The selection statements are used to select a part of the program to be executed based
on a condition.
➢ Python provides the following selection statements.
1. if statement
2. if-else statement
3. if-elif statement
if Statement
➢ An if statement is a selection control statement based on the value of a given Boolean
expression.
➢ The if statement checks, the given condition then decides the execution of a block of
statements.
➢ If it is True, then the block of statements is executed and if it is False, then the block of
statements is ignored.
➢ The execution flow of if statement is as follows.
15
SYNTAX:
if condition:
Statement_1
Statement_2
Statement_3
...
EXAMPLE
num = int(input('Enter any number: '))
if (num % 5 == 0):
print(f'Given number {num} is divisible by 5')
if-else statement in Python
➢ The if-else statement checks the given condition then decides which block of statements
to be executed based on the condition result.
➢ If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed.
➢ The execution flow of if-else statement is as follows.
16
if-elif statement
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Example:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
3. Discuss about Iterative control.
➢ The iterative statements are used to execute a part of the program repeatedly as long as
a given condition is True.
➢ Iterative control structures are also known as looping statements or repetitive
statements.
• while statement
• for statement
while statement
➢ In Python, the while statement is used to execute a set of statements repeatedly.
➢ The while statement is also known as entry control loop statement because in the case
of the while statement, first, the given condition is verified then the execution of
statements is determined based on the condition result.
17
➢ The general syntax of while statement in Python is as follows.
Syntax:
➢
while condition:
➢
Suite/ Statement1
➢
Statement 2
………..
Example:
i = 1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
while statement with 'else' clause
➢ The else clause can be used with a while statement.
18
➢ The else block is gets executed whenever the condition of the while statement is
evaluated to false.
➢ But, if the while loop is terminated with break statement then else doesn't execute.
Example:
i = 1
while i < 6:
print(i)
i += 1
else:
print('This is else block of while!!!')
for statement in Python
➢ In Python, the for statement is used to iterate through a sequence like a list, a tuple, a
set, a dictionary, or a string.
➢ The for statement is used to repeat the execution of a set of statements for every element
of a sequence.
➢ The general syntax of for statement in Python is as follows.
Examples:
1. for statement with List
# Python code to illustrate for statement with List
my_list = [1, 2, 3, 4, 5]
for value in my_list:
print(value)
print('Job is done!')
Output:
1
2
3
4
19
5
Job is done!
20
for item in 'Python':
print(item)
print('Job is done!')
Output:
P
y
t
h
o
n
Job is done!
5. for statement with Range function
# Python code to illustrate for statement with Range function
for value in range(1, 6):
print(value)
print('Job is done!')
Output
1
2
3
4
5
Job is done!
for statement with 'else' clause
➢ In Python, the else clause can be used with a for a statement.
➢ The else block is gets executed whenever the for statement is does not terminated with
a break statement.
➢ But, if the for loop is terminated with break statement then else block doesn't execute.
Example
# Here, else block is gets executed because break statement
does not executed
for item in 'Python':
if item == 'x':
break
21
print(item)
else:
print('else block says for is successfully completed!')
print('Job is done!!')
Output
P
y
t
h
o
n
else block says for is successfully completed!
Job is done!!
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. Explain briefly about List concept.
➢ A list is a linear data structure, that its elements have a linear ordering. That is, there
is a first element, a second element, and so on.
➢ Example:
➢ The above example is list storing the average temperature for each day of a given week,
in which each item in the list is identified by its index value.
➢ The location at index 0 stores the temperature for Sunday, the location at index 1 stores
the temperature for Monday, and so on.
List operations
Operations commonly performed on lists include retrieve, update, insert, remove, and append.
22
List Traversal
➢ A list traversal is accessing of one-by-one elements from a list.
➢ For example, to add up all the elements in a list of integers, each element can be
accessed one-by-one, starting with the first, and ending with the last element.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
23
5. Discuss about List data type in Python.
➢ In Python, a list is a collection of ordered and indexed elements of different data types.
➢ The list and its elements are mutable. That means, the list and its elements can be
modified at any time in the program.
➢ The list data type (data structure) has implemented with a class known as a list.
➢ All the elements of a list must be enclosed in square brackets, and each element must
be separated with a comma symbol.
➢ All the elements of a list are ordered and they are indexed.
➢ Here, the index starts from '0' (zero) and ends with 'number of elements - 1'.
Creating a list in Python
Syntax:
list_name = [element_1, element_2, element_3, ...]
Example
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(student_data)
list() constructor:
➢ In Python, a list can also be created using list() constructor. The list() constructor
takes only one argument.
Syntax
list_name = list([element_1, element_2, element_3, ...])
For example, consider the following code for creating a list using list() constructor which
stores the details of a student.
24
Syntax
list_name[index]
Example:
student_data = list([1, 'Ram', '2nd Year', 'CSE', 45.90])
print(f'Roll Number: {student_data[0]}\n'
f'Name of the Student: {student_data[1]}\n'
f'Branch: {student_data[3]}\n'
f'Year: {student_data[2]}\n'
f'Percentage: {student_data[4]}')
Example:
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(student_data[2:4])# Accessing elements from index 2 to 3
print(student_data[:4]) # Accessing elements from index 0 to 3
print(student_data[2:]) # Accessing elements from index 2 to
last element
Output:
['2nd Year', 'CSE']
[1, 'Rama', '2nd Year', 'CSE']
['2nd Year', 'CSE', 85.8]
Looping through a list in Python
➢ Looping through a list using for statement with membership operator in.
Example:
25
Output:
Element from the List is - 1
Element from the List is - Rama
Element from the List is - 2nd Year
Element from the List is - CSE
Element from the List is - 85.8
Existence of an element in a list in Python
➢ Test whether an element is present in a list or not using membership operator 'in'.
Example:
Output:
CSE is found in the list!!!
Finding the length of a list in Python
Example:
Output:
Length of the list is 5
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
26
6. Explain about List operations in Python.
The operations of List in Python is given below:
1. Changing an Element of a list in Python
2. Adding an element to the list in Python
3. Removing elements from a list in Python
4. Counting the number of times a value appears in the list
5. Extending a list
6. Finding the index of a value in a list
7. Finding Maximum and Minimum value in a list
8. The reverse of a list
9. Sorting the elements of a list
1. Changing an Element of a list in Python
➢ In Python, an element of a list can be changed at any time using index value.
➢ Syntax is:
list_name[index] = new_value
Example:
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
student_data[1] = 'Seetha'
print(student_data)
Output:
[1, 'Seetha', '2nd Year', 'CSE', 85.8]
2. Adding an element to the list in Python
➢ Adding an element to the existing list can be performed using the following built-in
methods.
• append(value)
• insert(index, value)
append(value) - This method adds a new element at the end of the list.
Example:
Output:
27
The list after append is
[1, 'Rama', '2nd Year', 'CSE', 85.8, 'promoted']
insert(index, value) - This method inserts a new element at the specified index of the list.
Example:
Output:
The list after insertion at index 2 is
[1, 'Rama', 'promoted', '2nd Year', 'CSE', 85.8]
3. Removing elements from a list in Python
The Python provides the following built-in methods to remove elements from a list.
• remove(value)
• pop()
• clear()
• del
remove(value)
➢ This method removes the specified element from the list.
➢ If the specified element is not found in the list, then the execution terminates with an
error message.
pop( ) or pop(index)
➢ This method removes the last element from the list.
➢ But, when it is used with an index value, it removes the value at the specified index
from the list.
del Keyword
➢ This keyword removes the complete list from the memory.
➢ After del keyword used with a list, we cannot use it again.
Example:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f'The list is - {my_list}')
28
my_list.remove(6)
print(f'The list after removing 6 is - {my_list}')
my_list.pop()
print(f'The list after pop is - {my_list}')
my_list.pop(2)
print(f'The list after pop with index 2 is - {my_list}')
my_list.clear()
print(f'The list after clear is - {my_list}')
del my_list
Output:
The list is - [1, 2, 3, 4, 5, 6, 7, 8, 9]
The list after removing 6 is - [1, 2, 3, 4, 5, 7, 8, 9]
The list after pop is - [1, 2, 3, 4, 5, 7, 8]
The list after pop with index 2 is - [1, 2, 4, 5, 7, 8]
The list after clear is - []
4. Counting the number of times a value appears in the list
➢ The Python provides a built-in method called count(value) to count the number of
times the given value appears in the list.
Example:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 5, 2]
print(f'The list is - {my_list}')
print(f'The value 2 appears {my_list.count(2)} times in the
list.')
Output:
The list is - [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 5, 2]
The value 2 appears 3 times in the list.
5. Extending a list
➢ The Python provides a built-in method called extend( ) to append elements of a list to
another list.
Example:
my_list_1 = [1, 2, 3, 4, 5]
my_list_2 = [10, 20, 30]
my_list_1.extend(my_list_2)
29
print(f'The list_1 after extend is - {my_list_1}')
Output:
The list_1 after extend is - [1, 2, 3, 4, 5, 10, 20, 30]
Output
The maximum value in the list is - 90
The minimum value in the list is - 2
8. The reverse of a list
➢ The Python provides a built-in method reverse( ) to produce the reverse of a list.
➢ The method reverse( ) returns None.
Example:
my_list = [12, 2, 5, 90, 30, 40, 3]
print(f'The list is - {my_list}')
my_list.reverse()
print(f'Reverse of the list is - {my_list}')
30
Output:
The list is - [12, 2, 5, 90, 30, 40, 3]
Reverse of the list is - [3, 40, 30, 90, 5, 2, 12]
9. Sorting the elements of a list
➢ Python provides a built-in method sort( ) to sort all the elements of a list.
➢ The method sort( ) returns None.
➢ The sort( ) method arranges the list elements in increasing order by default.
➢ To sort the elements in decreasing order, we need to pass an argument reverse = True
to sort( ) method.
Example:
my_list = [12, 2, 5, 90, 30, 40, 3]
print(f'The list is - {my_list}')
my_list.sort()
print(f'Increasing order of the list is - {my_list}')
my_list.sort(reverse=True)
print(f'Decreasing order of the list is - {my_list}')
Output:
The list is - [12, 2, 5, 90, 30, 40, 3]
Increasing order of the list is - [2, 3, 5, 12, 30, 40, 90]
Decreasing order of the list is - [90, 40, 30, 12, 5, 3, 2]
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
7. Explain the concept of Tuples.
➢ In Python, a tuple is a collection of ordered and indexed elements of different data types.
➢ The elements of a tuple are immutable, that means the elements of a tuple cannot be
modified.
➢ In Python, the tuple data type (data structure) has implemented with a class known as a
tuple.
➢ All the elements of a tuple must be enclosed in parenthesis, and each element must be
separated with a comma symbol.
➢ All the elements of a tuple are ordered and they are indexed. Here, the index starts from
'0' (zero) and ends with 'number of elements - 1'.
Creating a tuple in Python
1. Syntax is:
Example:
31
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
print(type(student_data))
print(student_data)
Output:
<class 'tuple'>
(1, 'Rama', '2nd Year', 'CSE', 85.8)
2) By using tuple() constructor
➢ In Python, a tuple can also be created using tuple( ) constructor.
➢ The tuple() constructor takes only one argument.
Syntax is:
Output:
<class 'tuple'>
('JNTUH', 'MRIT', 'MLTM')
Accessing Elements of a tuple in Python
➢ In Python, the tuple elements are organized using index values that start with '0' (zero)
at first element and ends with 'length of the tuple - 1' at last element.
➢ The individual elements of a tuple are accessed using the index values.
Syntax is:
tuple_name[index]
➢
Example:
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
print(type(student_data))
print(f'Roll Number: {student_data[0]}\n'
f'Name of the Student: {student_data[1]}\n'
f'Branch: {student_data[3]}\n'
f'Year: {student_data[2]}\n'
f'Percentage: {student_data[4]}')
OutPut:
<class 'tuple'>
Roll Number: 1
32
Name of the Student: Rama
Branch: CSE
Year: 2nd Year
Percentage: 85.8
Accessing Elements of a tuple in Python using slicing:
➢ In Python, we can also access a subset of elements from a tuple using slicing.
➢ We can access any subset of elements from the specified starting index to ending index.
➢ In tuple slicing, the default starting index is '0' and the default ending index is 'length
of the tuple - 1'.
Syntax is:
tuple_name[starting_index : ending_index]
➢
Example:
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
print(student_data[2:4])# Accessing elements from index 2 to 3
print(student_data[:4]) # Accessing elements from index 0 to 3
print(student_data[2:]) # Accessing elements from index 2 to
the last element
Output:
('2nd Year', 'CSE')
(1, 'Rama', '2nd Year', 'CSE')
('2nd Year', 'CSE', 85.8)
Changing an Element of a tuple in Python
➢ In Python, the elements of a tuple are immutable.
➢ So, modification of individual elements in a tuple is not allowed.
Looping through a tuple in Python
➢ In Python, we can loop through a tuple using for statement with membership
operator in.
Example:
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
for element in student_data:
print(f'Element from the tuple is - {element}')
Output:
Element from the tuple is - 1
Element from the tuple is - Rama
Element from the tuple is - 2nd Year
33
Element from the tuple is - CSE
Element from the tuple is - 85.8
Existence of an element in a tuple in Python
➢ In Python, we can test whether an element is present in a tuple or not using
membership operator 'in'.
Example:
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
if 'CSE' in student_data:
print(f'CSE is found in the tuple {student_data}!!!')
else:
print(f'CSE is not found in the tuple {student_data}!!!')
Output:
CSE is found in the tuple (1, 'Rama', '2nd Year', 'CSE', 85.8)!!!
Finding the length of a tuple in Python
➢ Python provides a built-in function len( ) to find the length of a tuple.
➢ The length of a tuple is the total number of elements in that tuple.
Example:
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
tuple_length = len(student_data)
print(f'Length of the tuple {student_data} is {tuple_length}')
Output:
Length of the tuple (1, 'Rama', '2nd Year', 'CSE', 85.8) is 5
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
8. Distinguish the difference between Tuples and List.
[Link]. LIST TUPLE
1
Lists are mutable Tuple are immutable
The list is better for performing operations, Tuple data type is appropriate for
2
such as insertion and deletion. accessing the elements
Tuple consume less memory as
3 Lists consume more memory
compared to the list
Lists are surrounded by square brackets []
Tuples are surrounded by parenthesis ()
Ex:
4. list_num = [1,2,3,4] Ex:
tup_num = (1,2,3,4)
34
[Link]. LIST TUPLE
Example: Example:
7. list_colors = ['red', 'blue', 'green'] tup_colors = ('red', 'blue',
print(list_colors.__sizeof__()) 'green')
Output:64 print(tup_colors.__sizeof__())
Output:48
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
9. Explain the operations of Tuple in Python.
The operations of Tuple in Python is given below:
1. Adding an element to the tuple in Python
2. Removing elements from a tuple in Python
3. Counting the number of times a value appears in the tuple
4. Finding the index of a value in a tuple
5. Finding the Maximum and Minimum value in a tuple
6. Sorting the elements of a tuple in Python
1. Adding an element to the tuple in Python
➢ Adding an element to the existing tuple in Python is not allowed.
2. Removing elements from a tuple in Python
➢ In Python, removing an individual element from the existing tuple is not allowed.
➢ However, the entire tuple can be deleted using del keyword.
Example:
35
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(f'The tuple is - {my_tuple}')
del my_tuple
print(f'The tuple after del keyword is used - {my_tuple}')
# GENERATES ERROR
3. Counting the number of times a value appears in the tuple
➢ The Python provides a built-in method called count(value) to count the number of times
the given value appears in the tuple.
Example:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 5, 2)
print(f'The tuple is - {my_tuple}')
print(f'The value 2 appears {my_tuple.count(2)} times in the
tuple.')
Output:
The tuple is - (1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 5, 2)
The value 2 appears 3 times in the tuple.
4. Finding the index of a value in a tuple
➢ Python provides a built-in method called index( value ) to find the index of that value
in the tuple.
➢ If the given value not found in the tuple, then the execution terminates with an error
message ValueError: <<value>> is not in a tuple.
Example:
my_tuple = (1, 2, 3, 4, 5)
print(f'The index of the value 4 is {my_tuple.index(4)}')
Output:
The index of the value 4 is 3
5. Finding the Maximum and Minimum value in a tuple
➢ The Python programming language provides built-in methods max( ) and min( ) to find
the maximum and minimum elements in a tuple.
Example:
my_tuple = (12, 2, 5, 90, 30, 40, 3)
print(f'The maximum value in the tuple is - {max(my_tuple)}')
print(f'The minimum value in the tuple is - {min(my_tuple)}')
Output:
The maximum value in the tuple is - 90
The minimum value in the tuple is - 2
6. Sorting the elements of a tuple in Python
36
➢ The Python provides a built-in method sorted( ) to sort all the elements of a tuple.
➢ The method sorted( ) returns None.
➢ The sorted( ) method arranges the tuple elements in increasing order by default.
➢ To sort the elements in decreasing order, we need to pass an argument reverse = True
to sorted( ) method.
Example:
my_tuple = (12, 2, 5, 90, 30, 40, 3)
print(f'The tuple is - {my_tuple}')
result_tuple = sorted(my_tuple)
print(f'Increasing order of the tuple is - {result_tuple}')
result_tuple = sorted(my_tuple, reverse=True)
print(f'Decreasing order of the tuple is - {result_tuple}')
Output:
The tuple is - (12, 2, 5, 90, 30, 40, 3)
Increasing order of the tuple is - [2, 3, 5, 12, 30, 40, 90]
Decreasing order of the tuple is - [90, 40, 30, 12, 5, 3, 2]
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
10. Explain about Sequences in Python?
➢ A sequence in Python is a linearly ordered set of elements accessed by an index
number.
➢ The order in which we put them in is the order in which we get an item out from
them.
➢ The most popular sequences are:
1. String
2. List
3. Tuples
1. String
➢ A string is a group of characters.
➢ Since Python has no provision for arrays, we simply use strings.
➢ We can use a pair of single or double quotes.
➢ Every string object is of the type ‘str’.
>>> type(name)
OutPut:
<class ‘str’>
37
➢ To declare an empty string, we may use the function str():
>>> name=str()
>>> name
OutPut:
”
Example:
>>> name=str('Ayushi')
>>> name
OutPut:
‘Ayushi’
Example:
>>> name[3]
OutPut:
‘s’
2. List
➢ Python does not have arrays, it has lists.
➢ A list is an ordered group of items.
➢ To declare it, we use square brackets.
>>> groceries=['milk','bread','eggs']
>>> groceries[1]
OutPut:
‘bread’
Example:
>>> groceries[:2]
OutPut:
[‘milk’, ‘bread’]
A Python list can hold all kinds of items; this is what makes it heterogenous.
>>> mylist=[1,'2',3.0,False]
Also, a list is mutable. This means we can change a value.
>>> groceries[0]='cheese'
>>> groceries
Output:
[‘cheese’, ‘bread’, ‘eggs’]
3. Tuples
➢ A tuple, in effect, is an immutable group of items.
38
➢ When we say immutable, we mean we cannot change a single value once we declare
it.
>>> name=('Ayushi','Sharma')
>>> type(name)
Output:
<class ‘tuple’>
We can also use the function tuple().
>>> name=tuple(['Ayushi','Sharma'])
>>> name
(‘Ayushi’, ‘Sharma’)
Like we said, a tuple is immutable. Let’s try changing a value.
>>> name[0]='Avery'
Traceback (most recent call last):
File “<pyshell#594>”, line 1, in <module>
name[0]=’Avery’
TypeError: ‘tuple’ object does not support item assignment
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. Discuss about the operations of Sequences in Python.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == ==
39
PROBLEM SOLVING USING PYTHON
UNIT 3
2 MARKS
1
1. What Is a Function Routine?
➢ Computer program as a single series of instructions.
➢ A routine is a named group of instructions performing some task.
➢ A routine can be invoked (called) as many times as needed in a given program.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Define: Function.
➢ A function is a block of statements under a name that can execute independently.
➢ The functions are used to perform a specific task.
➢ Functions allow us to divide a larger problem into smaller subparts to solve efficiently.
= = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = =
3. How to create/ define a function?
➢ The Python programming language provides the keyword def to create functions.
➢ The general syntax to create functions is as follows.
Syntax:
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. What is calling a function in Python?
➢ In Python, we use the name of the function to make a function call.
➢ If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)
Example:
def sample_function():
2
print('This is a user-defined function')
sample_function()
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
➢ Function avg takes three arguments (n1, n2, and n3) and returns the average of the three.
➢ The function call avg(10, 25, 16), therefore, is an expression that evaluates to the
returned function value.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. What is Non-Value-Returning Functions in Python?
➢ A non-value-returning function is called not for a returned value, but for its side
effects.
➢ A side effect is an action other than returning a function value, such as displaying
output on the screen.
Example:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
7. What is Actual arguments and Formal arguments in Python?
➢ Actual arguments, or simply “arguments,” are the values passed to functions (or
method) when the calling function to be operated on.
3
➢ Formal parameters, or simply “parameters,” are the “placeholder” names
(variables/identifiers) specified in the (header of) function definition.
def addition(x, y): →Formal parameters
addition = x+y
print(f”{addition}”)
addition(2, 3) →Actual Parameters
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
8. What is Local Variable?
➢ A local variable is a variable that is only accessible from within a given function.
➢ In Python, the variable that created inside a function is said to be under the local scope.
Example:
In this example Variable ‘a’ is used within the function named my_function() only.
def my_function():
a = 10
print('Inside my_function a value is: ', a)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
9. What is Global Variable?
➢ A global variable is a variable defi ned outside of any function definition. Such
variables are said to have global scope.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4
10. What is Variable scope in Python?
➢ The scope refers to the accessibility of a variable or object in the program.
➢ The scope of a variable determines the part of the program in which it can be accessed
or used.
➢ In Python programming, there are two different levels of scope and they are as follows.
1. Local Scope
2. Global Scope
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. What is built-in functions in Python?
➢ Built-in functions are defined as the functions whose functionality is pre-defined in
Python.
➢ There are several built-in functions in Python which are listed below:
1. abs()
2. all()
[Link]()
4. bin()
5. bool()
6. sum() and so on.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5
PROBLEM SOLVING USING PYTHON
UNIT 3
5 & 10 MARKS
6
1. Explain about function in Python?
➢ Computer program as a single series of instructions.
➢ A routine is a named group of instructions performing some task.
➢ A routine can be invoked (called) as many times as needed in a given program.
➢ When a routine terminates, execution automatically returns to the point from which it
was called.
➢ A function is Python’s version of a program routine. Some functions are designed to
return a value, while others are designed for other purposes.
➢ Functions allow us to divide a larger problem into smaller subparts to solve efficiently.
Create/ Define a function:
➢ The Python programming language provides the keyword def to create functions.
➢ The general syntax to create functions is as follows.
Syntax:
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
Calling a function:
➢ In Python, we use the name of the function to make a function call.
➢ If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)
Example:
def sample_function():
print('This is a user-defined function')
sample_function()
7
Value-Returning Functions :
➢ A value-returning function in Python is a program routine called for its return value,
and is therefore similar to a mathematical function.
➢ Function avg takes three arguments (n1, n2, and n3) and returns the average of the three.
➢ The function call avg(10, 25, 16), therefore, is an expression that evaluates to the
returned function value.
Non-Value-Returning Functions:
➢ A non-value-returning function is called not for a returned value, but for its side effects.
➢ A side effect is an action other than returning a function value, such as displaying
output on the screen.
Example:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Discuss about: Parameter passing in Python.
➢ Information can be passed into functions as arguments.
➢ Arguments are specified after the function name, inside the parentheses.
➢ You can add as many arguments as you want, just separate them with a comma.
➢ In Python, all the parameters are passed using pass by reference only.
Example1:
def fn1(name):
print(f'Hello! {name}')
name = 'Raja'
8
name = 'Rama'
fn1 (name)
print(f'name outside the function is {name}')
Output:
Hello! Rama
name outside the function is Rama
➢ In the above example program, the changes made in the called function does not affect
the name value outside the function.
➢ Because here the name variable has redefined, so it becomes a local variable for the
function.
➢ So, when we change the 'name' value in the function, it creates a new reference to it,
but it does not change the name outside the function.
Example2:
def myFun(x):
x[0] = 20
Example 3:
def myFun(x):
x = [20, 30, 40]
9
def addition(x, y): →Formal parameters
addition = x+y
print(f”{addition}”)
addition(2, 3) →Actual Parameters
Mutable vs. Immutable Arguments
➢ When a function is called, the current values of the arguments passed become the
initial values of their corresponding formal parameters.
Example:
➢ In this case, literal values are passed as the arguments to function avg.
➢ When variables are passed as actual arguments. Here we can change the value.
➢ It is considered as Mutable.
➢ In this case, function avg doesn’t assign values to its formal parameters, so there is no
possibility of the actual arguments being changed. It is considered as Immutable.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. Explain Python function arguments?
In Python, there are different ways to pass arguments to a function. They are as follows.
10
1. Positional Arguments (or) Required Arguments
➢ The positional arguments are the arguments passed to a function in the same positional
order as they defined in the function definition.
➢ Here, the number of arguments and order of arguments in the function call should
exactly match with the respective function definition.
➢ If any mismatch leads to error.
➢ The positional arguments are also known as required arguments.
Example:
def addition(num1, num2, num3):
return num1 + num2 + num3
2. Default Arguments
➢ The default argument is an argument which is set with a default value in the function
definition.
➢ If the function is called with value then, the function executed with provided value,
otherwise, it executed with the default value given in the function definition.
Example:
def addition(num1, num2, num3=300):
return num1 + num2 + num3
Output:
Sum = 60
Sum = 330
3. Keyword Arguments
➢ The keyword argument is an argument passed as a value along with the parameter name
(parameter_name = value).
➢ When keyword arguments are used, we may ignore the order of arguments.
➢ We may pass the arguments in any order because the Python interpreter uses the
keyword provided to match with the respective parameter.
11
Example:
def student_info(rollNo, name, dept, year):
print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}')
print(f'Department : {dept}')
print(f'Year of Study : {year}')
Output:
Roll Number : 111
Student Name : Rama
Department : CSE
Year of Study : 4
4. Variable-length Arguments
➢ The Python provides variable-length of arguments which enable us to pass an arbitrary
number of arguments.
➢ Here, all the arguments are stored as a tuple of parameters in the function definition.
And they are accessed using the index values (similar to a tuple).
Example:
def largest(*numbers):
return max(numbers)
print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))
Output:
35
5
80
44
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5. Explain about Variable scope in Python.
➢ The scope refers to the accessibility of a variable or object in the program.
➢ The scope of a variable determines the part of the program in which it can be accessed
or used.
1. Local Variable and Local Scope
12
➢ A local variable is a variable that is only accessible within a given function itself.
Such variables are said to have local scope.
Example:
def my_function():
a = 10
print('Inside my_function a value is: ', a)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. Discuss about Built-in function in Python.
➢ The Python built-in functions are defined as the functions whose functionality is pre-
defined. These functions are known as Built-in Functions.
➢ There are several built-in functions in Python which are listed below:
abs()Function:
➢ The python abs() function is used to return the absolute value of a number.
➢ It takes only one argument, a number whose absolute value is to be returned.
➢ The argument can be an integer and floating-point number.
➢ If the argument is a complex number, then, abs() returns its magnitude.
Examples:
1) x = abs(-7.25)
print(x)
Output:
7.25
2) x = abs(3+5j)
13
print(x)
Output:
5.830951894845301
all() Function:
➢ The all() function returns True if all items in an iterable are true, otherwise it returns
False.
➢ If the iterable object is empty, the all() function also returns True.
➢ Ex:
mylist = [0, 1, 1] mylist = [True, True, True]
x = all(mylist) x = all(mylist)
print(x) print(x)
Output:
False True
Any() Function:
➢ The any() function returns True if any item in an iterable are true, otherwise it returns
False.
➢ If the iterable object is empty, the any() function will return False.
Ex 1:
mylist = [False, True, False]
x = any(mylist)
Output:
True
Ex 2:
mytuple = (0, 1, False)
x = any(mytuple)
Output:
True
Ex 3:
myset = {0, 1, 0}
x = any(myset)
Output:
True
complex() Function:
14
➢ The complex() function returns a complex number by specifying a real number and an
imaginary number.
Syntax:
complex(real, imaginary)
Ex:
x = complex(3, 5) x = complex('3+5j’)
print(x) print(x)
Output: (3+5j) Output: (3+5j)
dict() Function:
➢ The dict() function creates a dictionary.
➢ A dictionary is a collection which is unordered, changeable and indexed.
Ex:
x = dict(name = "John", age = 36, country = "Norway")
print(x)
Output:
{'name': 'John', 'age': 36, 'country': 'Norway'}
eval() Function:
➢ The eval() function evaluates the specified expression.
Example:
x=5
print(eval('x + 1’))
Output:
6
exec() Function:
➢ The exec() function executes the specified Python code.
➢ The exec() function accepts large blocks of code, unlike the eval() function which
only accepts a single expression
Ex:
x = 'name = "John
print(name)'
exec(x)
Output: John
len() Function:
➢ The len() function returns the number of items in an object.
15
➢ When the object is a string, the len() function returns the number of characters in the
string.
Ex:
mylist = ["apple", "orange", "cherry"]
x = len(mylist)
print(x)
Output:
3
id() function
➢ The id() function returns a unique id for the specified object.
➢ All objects in Python has its own unique id.
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256)
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
88991544
list() function
➢ The list() function creates a list object.
➢ A list object is a collection which is ordered and changeable.
Example:
print(x)
Output:
16
map() function
➢ The map() function executes a specified function for each item in an iterable.
➢ The item is sent to the function as a parameter.
Example:
def myfunc(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print(x)
#convert the map into a list, for readability:
print(list(x))
Output:
<map object at 0x056D44F0>
['5', '6', '6']
max() function
➢ The max() function returns the item with the highest value, or the item with the highest
value in an iterable.
➢ If the values are strings, an alphabetically comparison is done.
Example:
x = max(5, 10)
print(x)
Output:
10
min() function
➢ The min() function returns the item with the lowest value, or the item with the lowest
value in an iterable.
➢ If the values are strings, an alphabetically comparison is done.
Example:
x = min(5, 10)
print(x)
Output:
5
range() function
17
➢ The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Example:
x = range(6)
for n in x:
print(n)
Output:
0
1
2
3
4
5
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
18
PROBLEM SOLVING USING PYTHON
UNIT 4
2 MARKS
1
1. What is an Object?
➢ All objects have certain attributes and behavior.
➢ An object contains a set of attributes, stored in a set of instance variables, and a set of
functions called methods that provide its behavior.
➢ The attributes of a car, for example, include its color, number of miles driven, current
location, and so on.
➢ Its behaviors include driving the car (changing the number of miles driven attribute)
and painting the car (changing its color attribute).
➢ The sort rmethod would be part of the object containing the list.
Ex:
names_list.sort().
➢ The period is referred to as the dot operator , used to select a member of a given object
in this case, the sort method.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2. What is Object References?
➢ In Python, objects are represented as a reference to an object in memory.
➢ A reference is a value that references, or “points to,” the location of another entity.
➢ Thus, when a new object in Python is created, two entities are stored—the object, and
a variable holding a reference to the object.
➢ All access to the object is through the reference value.
➢ The value that a reference points to is called the dereferenced value. This is the value
that the variable represents, as shown in the following Figure.
2
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
3. What is built-in function id?
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256).
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
88991544
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4. What is assignment of references?
when variable n is assigned to variable k, depicted in the following Figure.
When variable n is assigned to k, it is the reference value of k that is assigned, not the
dereferenced value 20.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5. What is Garbage Collection?
Garbage collection is a method of determining which locations in memory are no longer in use,
and deallocating them.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
6. What is Turtle Graphics?
➢ Turtle graphics refers to a means of controlling a graphical entity (a “turtle”) in a
graphics window with x,y coordinates.
3
➢ Python provides the capability of turtle graphics in the turtle Python standard library
module.
➢ There may be more than one turtle on the screen at once. Each turtle is represented by
a distinct object.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7. How can you create Turtle in Python?
➢ The first step in the use of turtle graphics is to create a turtle graphics window of a
specific size with an appropriate title.
➢ The following shows how to create a turtle screen of a certain size with an appropriate
title bar.
4
Absolute Positioning:
➢ A turtle’s position can be changed using absolute positioning by use of method
setposition.
Relative Positioning
➢ A turtle’s position can be changed using relative positioning by use of methods
setheading, left, right, and forward.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
11. What is pen attributes of turtle?
➢ The pen attributes that can be controlled includes:
1. pen is down or up (using methods penup and pendown)
2. pen size (using method pensize)
3. pen color (using method pencolor).
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
12. What are additional attributes of turtle?
1. Turtle Visibility - Methods showturtle() and hideturtle() control a
turtle’s visibility.
2. Turtle Size- The size of a given turtle shape can be controlled with methods
resizemode and turtlesize.
3. Turtle Shape- A turtle’s shape may be set to one of the provided shapes, a described
polygon (or collection of polygons), or an image.
4. Turtle Speed- The speed of a turtle can be controlled by use of the speed method.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
13. What is module?
➢ The term “module” refers to the design and/or implementation of specific functionality
to be incorporated into a program.
➢ Modules generally consist of a collection of functions (or other entities).
➢ The Python turtle module is an example of a software module.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
14. What are advantages of modular programming?
1. Software Design
2. Software Development
3. Software Testing
4. Software Modification and Maintenance
=== == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5
15. What is module specification?
➢ Every module needs to provide a specification of how it is to be used.
➢ This is referred to as the module’s interface.
➢ Any program code making use of a particular module is referred to as a client of the
➢ module.
➢ A module’s specification should be sufficiently clear and complete so that its clients
can effectively utilize it.
➢ The function’s specification is provided by the line immediately following the function
header, called a docstring in Python.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
16. What is docstring?
➢ The function’s specification is provided by the line immediately following the function
header, called a docstring in Python.
➢ A docstring is a string literal denoted by triple quotes used in Python for providing the
specification of certain program elements.
Ex:
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
17. What is Top-Design?
➢ Top-down design is an approach for deriving a modular design in which the overall
design of a system is developed first, deferring the specification of more detailed
aspects of the design until later steps.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
18. What Is a Python Module?
➢ A Python module is a file containing Python definitions and statements.
➢ The Python Standard Library contains a set of predefined standard (built-in) modules.
➢ When a Python file is directly executed, it is considered the main module of a
program.
➢ Main modules are given the special name __main__.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
19. What is namespace?
➢ A namespace provides a context for a set of identifiers.
6
➢ Every module in Python has its own namespace.
➢ A name clash is when two otherwise distinct entities with the same identifier become
part of the same scope.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
20. What is “import module name” Form of Import?
➢ With the import modulename form of import in Python, the namespace of the
imported module becomes available to, but does not become part of, the namespace of
the importing module.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
21. What is “from-import” Form of Import?
➢ Python also provides an alternate import statement of the form
from modulename import something
where something can be a list of identifiers, a single renamed identifier, or an asterisk, as
shown below,
(a) from modulename import func1, func2
(b) from modulename import func1 as new_func1
(c) from modulename import *
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
22. What is module private variable?
In Python, all the variables in a module are “public,” with the convention that variables
beginning with two underscores (__) are intended to be private.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
23. What is Built-in Function dir()?
➢ Built-in function dir() is very useful for monitoring the items in the namespace of
the main module for programs executing in the Python shell.
➢ For example, the following gives the namespace of a newly started shell,
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
The following shows the namespace after importing and defining variables,
>>> import random
>>> n 5 10
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n',
'random']
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7
24. What are the 3 possible namespaces?
There are three possible namespaces referenced (“active”):
1. built-in namespace
2. global namespace
3. local namespace.
Built-in namespace:
➢ The built-in namespace contains the names of all the built-in functions, constants, and
so on, in Python.
Global namespace:
➢ The global namespace contains the identifiers of the currently executing module.
Local Namespace
➢ The local namespace is the namespace of the currently executing function (if any).
When Python looks for an identifier, it first searches the local namespace (if defi ned), then the
global namespace, and finally the built-in namespace.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
25. What is text file?
➢ A text file is a file containing characters, structured as individual lines of text.
➢ In addition to printable characters, text files also contain the nonprinting newline
character, \n, to denote the end of each text line.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
26. What is Binary File?
➢ Binary files can contain various types of data, such as numerical values, and are
therefore not structured as lines of text.
➢ Such files can only be read and written via a computer program.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
27. What are the operations of File?
Fundamental operations of all types of files include opening a file, reading from a file, writing
to a file, and closing a file.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
28. What is Opening Text File?
➢ All files must first be opened before they can be used.
➢ In Python, when a file is opened, a file object is created that provides methods for
accessing the file.
8
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
29. What is Reading Text File?
➢ The readline method returns the next line of a text file, including the end-of-line
character.
➢ If at the end of the file, an empty string is returned.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
30. What is Writing a text File?
➢ Use the write()method to output text to a file.
➢ To ensure that all data has been written, call the close() method to close the file
after all information has been written.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
31. What is String Processing?
String processing refers to the operations performed on strings that allow them to be accessed,
analyzed, and updated.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
32. What is String Traversal?
The characters in a string can be easily traversed, without the use of an explicit index variable,
using the for chr in string form of the for statement.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
33. What is an Exception?
➢ The exception is an abnormal situation during the execution.
➢ An exception is a value (object) that is raised (“thrown”) signalling that an unexpected,
or “exceptional,” situation has occurred.
➢ Python contains a predefined set of exceptions referred to as standard exceptions.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
34. List some standard exceptions.
ImportError Raised when an import(from..import) statement fails
IndexError Raised when a sequence index is out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an object of
inappropriate type
ValueError Raised when a built-in operation or function is applied to an
appropriate value
9
IOError Raised when an input/output operation fails (e.g., ‘file not found’)
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
35. What is propagation of exception?
➢ An exception is either handled by the client code, or automatically propagated back to
the client’s calling code, and so on, until handled.
➢ If an exception is thrown all the way back to the main module (and not handled), the
program terminates displaying the details of the exception.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
36. What is IOError exceptions?
IOError exceptions raised as a result of a fi le open error can be caught and handled.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10
PROBLEM SOLVING USING PYTHON
UNIT 4
5 & 10 MARKS
11
1. Explain the fundamental concept of software object?
➢ Objects are the fundamental component of object-oriented programming.
➢ All objects have certain attributes and behavior.
➢ An object contains a set of attributes, stored in a set of instance variables, and a set of
functions called methods that provide its behavior.
➢ The attributes of a car, for example, include its color, number of miles driven, current
location, and so on.
➢ Its behaviors include driving the car (changing the number of miles driven attribute)
and painting the car (changing its color attribute).
➢ The sort rmethod would be part of the object containing the list (names_list.
Ex:
names_list.sort().
➢ The period is referred to as the dot operator, used to select a member of a given object
in this case, the sort method.
Object References:
➢ In Python, objects are represented as a reference to an object in memory.
➢ A reference is a value that references, or “points to,” the location of another entity.
➢ Thus, when a new object in Python is created, two entities are stored—the object, and
a variable holding a reference to the object.
➢ All access to the object is through the reference value.
➢ The value that a reference points to is called the dereferenced value. This is the value
that the variable represents, as shown in the following Figure.
12
➢ We can get the reference value of a variable (that is, the location in which the
corresponding object is stored) by use of built-in function id.
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256).
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
Assignment of reference:
when variable n is assigned to variable k, depicted in the following Figure.
➢ When variable n is assigned to k, it is the reference value of k that is assigned, not the
dereferenced value 20.
➢ This can be determined by use of the built-in id function, as demonstrated below.
>>> id(k) >>> id(k) == id(n)
505498136 True
>>> id(n) >>> n is k
505498136 True
➢ Thus, to verify that two variables refer to the same object instance, we can either
compare the two id values by use of the comparison operator, or make use of the
provided is operator (which performs id(k) = = id(n)).
➢ when the value of one of the two variables n or k is changed, as depicted in the
following Figure.
13
Reassignment of Reference Value
➢ Here, variable k is assigned a reference value to a new memory location holding the
value 30.
➢ The previous memory location that variable k referenced is retained since variable n is
still referencing it.
➢ As a result, n and k point to different values, and therefore are no longer equal.
Memory Deallocation and Garbage Collection
➢ when variable k being reassigned, variable n is reassigned as well. The result is
depicted in the following Figure.
➢ After n is assigned to 40, the memory location storing integer value 20 is no longer
referenced—thus, it can be deallocated.
➢ To deallocate a memory location means to change its status from “currently in use” to
“available for reuse.”
➢ In Python, memory deallocation is automatically performed by a process called garbage
collection.
➢ Garbage collection is a method of automatically determining which locations in
memory are no longer in use and deallocating them.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2. Explain about List assignment and Copying?
List Assignment:
➢ when a variable is assigned to another variable referencing a list, each variable ends
up referring to the same instance of the list in memory, depicted in the following
figure.
14
List Assignment
➢ Thus, any changes to the elements of list1 results in changes to list2,
>>>list1[0] = 5
>>>list2[0]
5
List Copying
➢ A copy of a list can be made as follows, Copy using = operator.
➢ It only creates a new variable that shares the reference of the original object.
>>> list2 = list(list1)
➢ list() is referred to as a list constructor .
➢ The result of the copying is depicted in the following figure.
15
➢ The list constructor list() makes a copy of the top level of a list, in which the sublist
(lower-level) structures are shared is referred to as a shallow copy.
Top-Level Reassignment of Shallow Copies
➢ Copies were made of the top-level list structures, the elements within each list
were not copied. This is referred to as a shallow copy.
➢ Thus, if a top-level element of one list is reassigned, for example list1[0] = [70, 80],
the other list would remain unchanged, as shown in the following figure.
➢ A shallow copy creates a new object which stores the reference of the original elements.
➢ So, a shallow copy doesn't create a copy of nested objects, instead it just copies the
reference of nested objects.
Sublevel Reassignment of Shallow Copies:
➢ A change to one of the sublists is made, for example, list1[0][0] = 70, the corresponding
change would be made in the other list.
➢ That is, list2[0][0] would be equal to 70 also, as depicted in the following Figure.
Deep Copy:
➢ A deep copy operation of a list (structure) makes a copy of the complete structure,
including sublists.
16
➢ Since immutable types cannot be altered, immutable parts of the structure may not be
copied. Such an operation can be performed with the deepcopy method of the
copy module,
>>>import copy
>>>list2 = [Link](list1)
➢ The result of this form of copying is given in the following Figure.
17
5 This is similar to the concept of passing This is similar to the concept of passing
by reference in programming languages by value in languages like C++, Java, and
like C++, C#, and Java. C#.
6 This is implemented by using copy() This is implemented using “deepcopy()”
function. function.
7 import copy import copy
result_A = [[90, 85, 82], [72, 88, 90]] result_A = [[90, 85, 82], [72, 88, 90]] #
result_B = [Link](result_A) Student A grades
result_B = [Link](result_A) #
print(result_A) Student B grades (copied from A)
print(result_B)
print(result_A)
print(result_B)
Output: Output:
[[90, 85, 82], [72, 88, 90]] [[90, 85, 82], [72, 88, 90]]
[[90, 85, 82], [72, 88, 90]] [[90, 85, 82], [72, 88, 90]]
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4. How will you create turtle graphics window in Python?
➢ The Python turtle library contains all the methods and functions that you’ll need to
create your images.
➢ To access a Python library, you need to import it into your Python environment, like
this:
>>> import turtle
➢ Turtle graphics refers to a means of controlling a graphical entity (a “turtle”) in a
graphics window with x,y coordinates.
➢ Each of the turtle graphics methods must be called in the form
[Link] .
➢ The first method called, setup, creates a graphics window of the specified size (in
pixels).
➢ The first step in the use of turtle graphics is to create a turtle graphics window of a
specific size with an appropriate title.
18
Creating a Turtle Graphics Window
➢ In this case, a window of size 800 pixels wide by 600 pixels high is created.
➢ The center point of the window is at coordinate (0,0).
➢ Thus, x-coordinate values to the right of the center point are positive values, and those
to the left are negative values.
Similarly, y-coordinate values above the center point are positive values, and those
below are negative values.
The top-left, top-right, bottom-left, and bottom-left coordinates for a window of size
(800, 600) are as shown in the following Figure.
19
➢ The screen is divided into four quadrants.
➢ The point where the turtle is initially positioned at the beginning of your program is
(0,0). This is called Home.
➢ To move the turtle to any other area on the screen, you use .goto() and enter the
coordinates like this:
>>> [Link](100,100)
➢ To bring the turtle back to its home position, you type the following:
>>> [Link]()
➢ This is like a shortcut command that sends the turtle back to the point (0,0).
➢ It’s quicker than typing [Link](0,0).
➢ A turtle graphics window in Python is also an object.
➢ Therefore, to set the title of this window, we need the reference to this object.
➢ This is done by call to method Screen.
➢ The background color of the turtle window can be changed from the default white
background color.
➢ This is done using method bgcolor.
➢ Example:
window = [Link]()
[Link]('blue')
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5. Discuss about “Default Turtle”.
➢ A “turtle” is an entity in a turtle graphics window that can be controlled in various ways.
➢ Like the graphics window, turtles are objects.
20
➢ A “default” turtle is created when the setup method is called.
➢ The reference to this turtle object can be obtained by,
the_turtle = [Link]()
➢ A call to getturtle returns the reference to the default turtle and causes it to appear
on the screen.
➢ The initial position of all turtles is the center of the screen at coordinate (0,0), as shown
in the following Figure.
>>> t = [Link]()
>>> [Link](90)
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)
21
➢ When you run these commands, the turtle will turn right by ninety degrees, go forward
by a hundred units, turn left by ninety degrees, and move backward by a hundred units.
➢ We can use the shortened versions of these commands as well:
• [Link]() instead of [Link]()
• [Link]() instead of [Link]()
• [Link]() instead of [Link]()
• [Link]() instead of [Link]()
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7. Explain about fundamental Turtle attributes and its behaviour?
➢ Turtle objects have three fundamental attributes:
1. Position
2. Heading (orientation)
3. Pen attributes.
1. Position:
There are two types of positioning. They are:
a) Absolute Position
b) Relative Position
a) Absolute Positioning
➢ Method position returns a turtle’s current position.
➢ For newly created turtles, this returns the tuple (0, 0).
➢ A turtle’s position can be changed using absolute positioning by moving the turtle
to a specific x,y coordinate location by use of method setposition.
Example:
22
➢ Since newly created turtles are positioned at coordinates (0, 0), the square will be
displayed near the middle of the turtle window.
2 & b) Turtle Heading and Relative Positioning
➢ A turtle’s position can also be changed through relative positioning.
➢ In this case, the location that a turtle moves to is determined by its second
fundamental attribute, its heading.
➢ A newly created turtle’s heading is to the right, at 0 degrees.
➢ A turtle with heading 90 degrees moves up; with a heading 180 degrees moves left;
and with a heading 270 degrees moves down.
➢ A turtle’s heading can be changed by turning the turtle a given number of degrees left,
left(90), or right, right(90).
➢ The forward method moves a turtle in the direction that it is currently heading.
Example:
➢ In the above example, since turtles are initially positioned at coordinates (0, 0) with
an initial heading of 0 degrees, the first step is to move the turtle forward 100 pixels.
➢ That draws the bottom line of the square.
➢ The turtle is then turned left 90 degrees and again moved forward 100 pixels.
➢ This draws the line of the right side of the square.
➢ These steps continue until the turtle arrives back at the original coordinates (0, 0),
completing the square.
➢ Methods left and right change a turtle’s heading relative to its current heading.
➢ A turtle’s heading can also be set to a specific heading by use of method
setheading: the_turtle.setheading(90).
➢ In addition, method heading can be used to determine a turtle’s current heading.
23
➢ A turtle’s position can be changed using relative positioning by use of methods
setheading, left, right, and forward.
3. Pen attributes
➢ The pen attribute of a turtle object is related to its drawing capabilities.
➢ The most fundamental of these attributes is whether the pen is currently “up” or
“down,” controlled by methods penup() and pendown().
➢ When the pen attribute value is “up,” the turtle can be moved to another location without
lines being drawn.
➢ This is especially needed when drawing graphical images with disconnected segments.
Example:
➢ In this example, the turtle is hidden so that only the needed lines appear.
➢ Since the initial location of the turtle is at coordinate (0, 0), the pen is set to “up” so
that the position of the turtle can be set to (2100, 0) without a line being drawn as it
moves.
➢ This puts the turtle at the bottom of the left side of the letter.
➢ The pen is then set to “down” and the turtle is moved to coordinate (0, 250), drawing
as it moves.
➢ Therefore, draws a line from the bottom of the left side to the top of the “A.”
➢ The turtle is then moved (with its pen still down) to the location of the bottom of the
right side of the letter, coordinate (100, 0).
➢ To cross the “A,” the pen is again set to “up” and the turtle is moved to the location of
the left end of the crossing line, coordinate (264, 90).
➢ The pen is then set to “down” and moved to the end of the crossing line, at coordinate
(64, 90), to finish the letter.
24
Pen Size:
➢ The pen size of a turtle determines the width of the lines drawn when the pen attribute
is “down.”
➢ The pensize method is used to control this: the_turtle.pensize(5).
➢ The width is given in pixels, and is limited only by the size of the turtle screen.
Example:
Pen Color:
➢ The pen color can also be selected by use of the pencolor method:
the_turtle.pencolor('blue').
➢ The name of any common color can be used, for example 'white','red',
'blue', 'green', 'yellow', 'gray', and 'black'.
➢ Colors can also be specified in RGB (red/green/blue) component values.
➢ These values can be specifi ed in the range 0–255 if the color mode attribute of the
turtle window is set as given below,
[Link](255)
the_turtle.pencolor(238, 130, 238) # violet
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
8. Explain about additional attributes of turtle?
The additional attributes include:
1. Turtle Visibility
2. Turtle Size
3. Turtle Shape
4. Fill color of the turtle,
5. Turtle Speed,
6. Turtle Tilt
25
Turtle Visibility
➢ A turtle’s visibility can be controlled by use of methods hideturtle()and
showturtle().
Turtle Size
➢ The size of a turtle shape can be controlled with methods resizemode and
turtlesize as shown in the following figure.
➢ The shape and fill colors are set by use of the shape and fillcolor methods,
the_turtle.shape('circle')
the_turtle.fillcolor('white')
➢ New shapes may be created and registered with (added to) the turtle screen’s shape
dictionary.
26
Example:
➢ One way of creating a new is shape by providing a set of coordinates denoting a
polygon is shown in the following figure.
➢ In the figure, method register_shape is used to register the new turtle shape with
the name mypolygon.
➢ Once the new shape is defined, a turtle can be set to that shape by calling the shape
method with the desired shape’s name.
➢ The fillcolor method is then called to make the fill color of the polygon white
(with the edges remaining black).
➢ It is also possible to create turtle shapes composed of various individual polygons called
compound shapes.
Turtle Speed
➢ We may control the speed at which a turtle moves. The speed of a turtle can be
controlled by use of the speed method.
➢ A turtle’s speed can be set to a range of speed values from 0 to 10, with a “normal”
speed being around 6.
➢ To set the speed of the turtle, the speed method is used, the_turtle.speed(6).
➢ The following speed values can be set using a descriptive rather than a numeric value,
➢ 10: 'fast' 6: 'normal' 3: 'slow' 1: 'slowest' 0:
'fastest'
➢ Thus, a normal speed can also be set by the_turtle.speed('normal').
Turtle Tilt
➢ Turtle tilt is used to rotate the turtle shape by the angle from its current tilt-angle, but
do NOT change the turtle’s heading (direction of movement).
➢ Tilt is used by the method of [Link](angle)
27
Example:
# tilt turtleshape by 45
[Link](45)
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
9. How will you create multiple turtle?
➢ Any number of turtle objects can be created by use of method Turtle().
turtle1 = [Link]()
turtle2 = [Link]()
etc.
➢ By storing turtle objects in a list, any number of turtles may be maintained,
turtles = []
[Link]([Link]())
[Link]([Link]())
etc.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10. Write about advantages of Modular Programming?
1. Software Design:
➢ Provides a means for the development of wee-designed programs.
2. Software Development:
➢ Provides a natural means of dividing up programming tasks
➢ Provides a means for the reuse of program code
3. Software Testing:
➢ Provides a means of separately testing parts of a program
➢ Provides a means of integrating parts of a program during testing
4. Software Modification and Maintenance:
➢ Facilitates the modification of specific program functionalities.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
11. Discuss briefly about fundamentals concepts of modules.
➢ Software is that programs that are designed as a collection of modules.
➢ The term “module,” refers to the design and/or implementation of specific functionality
of a program.
➢ Modules generally consists of a collection of functions or entities.
➢ Modular design allows large programs to be broken down into parts, in which each part
(module) provides a specified capability.
28
➢ It allows modules to be individually developed and tested, and eventually integrated as
a part of a complete system.
Module specification:
➢ Every module needs to provide a specification of how it is to be used.
➢ This is referred to as the module’s interface.
➢ Any program code making use of a particular module is referred to as a client of the
➢ module.
➢ A module’s specification should be sufficiently clear and complete so that its clients
can effectively utilize it.
➢ The function’s specification is provided by the line immediately following the function
header, called a docstring in Python.
➢ A docstring is a string literal denoted by triple quotes used in Python for providing the
specification of certain program elements.
Ex:
➢ The docstring of a particular program element can be displayed by use of the __doc__
extension,
>>> print(numPrimes.__doc__)
Returns the number of primes between start and end.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
12. Explain about Python Modules.
➢ A Python module is a file containing Python definitions and statements.
➢ The Python Standard Library contains a set of predefined standard (built-in) modules.
➢ When a Python file is directly executed, it is considered the main module of a
program.
➢ Main modules are given the special name __main__.
➢ As with the main module, imported modules may contain a set of statements.
➢ The statements of imported modules are executed only once, the first time that the
module is imported.
29
➢ By convention, modules are named using all lower case letters and optional underscore
characters.
Modules and Namespaces
➢ A namespace is a container that provides a set of identifiers
➢ Every module in Python has its own namespace.
➢ A name clash is when two distinct entities with the same identifier become
part of the same scope.
➢ Name clashes can occur, for example, if two or more Python modules contain identifiers
with the same name and are imported into the same program, as shown in the following
figure.
➢ In above example, module1 and module2 are imported into the same program.
➢ Each module contains an identifier named double, which return very different results.
➢ When the function call double(num_list) is executed in main, there is a name
clash.
➢ Thus, it cannot be determined which of these two functions should be called.
➢ Namespaces provide a means for resolving such problems.
➢ Two instances of identifier double, each defined in their own module, are distinguished
by being fully qualified with the name of the module in which each is defined:
[Link] and [Link]
30
Example Use of Fully Qualified Function Names
Importing Modules:
➢ With the import modulename form of import in Python, the namespace of the
imported module becomes available to, but does not become part of, the namespace of
the importing module.
➢ Python also provides an alternate import statement of the form
from modulename import something
where something can be a list of identifiers, a single renamed identifier, or an asterisk, as
shown below,
(a) from modulename import func1, func2
(b) from modulename import func1 as new_func1
(c) from modulename import *
➢ In example (a), only identifiers func1 and func2 are imported.
➢ In example (b), only identifier func1 is imported, renamed as new_func1 in the
importing module.
➢ Finally, in example (c), all of the identifiers are imported, except for those that begin
with two underscore characters, which are meant to be private in the module.
➢ In Python, all the variables in a module are “public,” with the convention that variables
beginning with two underscores (__) are intended to be private.
Built-in function dir():
➢ Built-in function dir() is very useful for monitoring the items in the namespace of
the main module for programs executing in the Python shell.
➢ For example, the following gives the namespace of a newly started shell,
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
The following shows the namespace after importing and defining variables,
>>> import random
>>> n 5 10
>>> dir()
31
['__builtins__', '__doc__', '__name__', '__package__', 'n',
'random']
Local, Global, and Built-in Namespaces in Python
There are three possible namespaces referenced (“active”):
1. Built-in namespace
2. Global namespace
3. Local namespace.
Built-in namespace:
➢ The built-in namespace contains the names of all the built-in functions, constants, and
so on, in Python.
Global namespace:
➢ The global namespace contains the identifiers of the currently executing module.
Local Namespace
➢ The local namespace is the namespace of the currently executing function (if any).
When Python looks for an identifier, it first searches the local namespace (if defined), then the
global namespace, and finally the built-in namespace.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
13. Explain the fundamental operations of file in python?
➢ Fundamental operations of all types of files include:
1. Opening a file
2. Reading from a file
3. Writing to a file
4. Closing a file
Opening Text Files
➢ All files must first be opened before they can be read from or written to.
32
➢ In Python, when a file is opened, a file object is created that provides methods for
accessing the file.
Opening for Reading
➢ To open a file for reading, the built-in open function is used.
input_file = open('[Link]','r')
➢ The first argument is the file name to be opened, '[Link]'.
➢ The second argument, 'r', indicates that the file is to be opened for reading.
➢ If the file is successfully opened, a file object is created and assigned to the provided
identifier, in this case identifier input_file.
Opening for Writing
➢ To open a file for writing, the open function is used as shown below,
output_file = open('[Link]','w')
➢ The first argument is the file name to be opened, '[Link]'.
➢ The second argument, 'w' is used to indicate that the file is to be opened for writing.
If the file already exists, it will be overwritten (starting with the first line of the file).
➢ When using a second argument of 'a', the output will be appended to an existing file
instead.
➢ It is important to close a file that is written to, otherwise the tail end of the file may not
be written to the file.
output_file.close()
Reading Text Files
➢ The readline method returns as a string the next line of a text file, including the
end-of-line character, \n.
➢ When the end-of-file is reached, it returns an empty string.
Example: Using WHILE Statement
33
input_fi le = \
open('[Link]','r')
for line in input_file:
➢ Using a FOR statement, all lines of the file will be read one by one.
➢ Using a WHILE loop, however, lines can be read until a given value is found.
Writing Text Files
➢ The write method is used to write strings to a file, is shown in the following figure.
➢ This code copies the contents of the input file, '[Link]', line by line to the
output file, 'myfile_copy.txt'.
➢ In contrast to print when writing to the screen, the write method does not add a
newline character to the output string.
➢ Thus, a newline character will be output only if it is part of the string being written.
➢ In this case, each line read contains a newline character.
➢ Finally, when writing to a file, data is first placed in an area of memory called a buffer.
Only when the buffer becomes full is the data actually written to the file.
➢ The close () method flushes the buffer to force the buffer to be written to the file.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
14. What is String Processing. Explain string Traversal.
String processing refers to the operations performed on strings that allow them to be accessed,
analyzed, and updated.
String Traversal:
➢ The characters in a string can be easily traversed, without the use of an explicit index
variable, using the for chr in string form of the FOR statement.
➢ This is usually done by the use of a FOR loop.
➢ For example, if we want to read a line of a text file and determine the number of blank
characters it contains, we could do the following,
space =' '
34
num_spaces = 0
line = input_fi [Link]()
for k in range(0,len(line)):
if line[k] == space:
num_spaces = num_spaces + 1
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
15. Discuss about String-Applicable Sequence Operations.
➢ Because strings (unlike lists) are immutable, sequence-modifying operations are not
applicable to strings.
➢ For example, one cannot add, delete, or replace characters of a string.
➢ Therefore, all string operations that “modify” a string return a new string that is a
modified version of the original string.
a) Length of String
b) Select Operation
c) Slice
d) Count
e) Index
f) Membership
g) Concatenation
h) Minimum Value
i) Maximum Value
j) Comparison
a) Length of String
The len() function is used to find the length of the string.
Example:
s = 'Hello Goodbye!'
print(len(s))
Output:
14
b) Select Operation
➢ It returns the substring of String (if found).
➢ If the substring is not found, it raises an exception.
➢ By using s[index value]method we can select particular string.
Example:
s = 'Hello Goodbye!'
35
s[6]
Output: 'G'
c) Slice:
➢ It can return a range of characters by using the slice syntax.
➢ Specify the start index and the end index, separated by a colon, to return a part of the
string. s[start:end]
Example:
s = 'Hello Goodbye!'
s[6:10]
Output: 'Good'
Slice from the Start
➢ By leaving out the start index, the range will start at the first character:
Example:
s = 'Hello Goodbye!'
print(s[:5])
Output: 'Hello'
Get the characters from the start to position 5 (not included) and starting index value is 0.
Slice To the End
➢ By leaving out the end index, the range will go to the end:
Example:
s = 'Hello Goodbye!'
print(s[2:])
Output: llo Goodbye!
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example:
s = 'Hello Goodbye!'
print(s[-5:-2])
Output:
dby
Get the characters:
36
From: "d" in " Goodbye!" (position -5)
To, but not included: "e" in " Goodbye!" (position -2):
d) Count
The string count () method returns the number of occurrences of a substring in the given
string.
[Link](substring)
Example:
s = 'Hello Goodbye!'
[Link]('o')
Output: 3
e) index
➢ The index() method finds the first occurrence of the specified value.
➢ The index() method raises an exception if the value is not found.
➢ The index() method is almost the same as the find() method, the only difference
is that the find() method returns -1 if the value is not found.
➢ [Link](value, start, end); start & end is optional.
Example:
s = 'Hello Goodbye!'
[Link]('b')
Output: 10
f) membership
Membership operators are used to test if a sequence is presented in an object.
1) in operator : The ‘in’ operator is used to check if a value exists in a sequence or not.
Evaluates to true if it finds a variable in the specified sequence and false otherwise.
2) ‘not in’ operator- Evaluates to true if it does not find a variable in the specified sequence
and false otherwise.
Example:
>>>s = 'Hello Goodbye!'
>>>'a' in s
Output: False
>>>'a' not in s
Output: True
37
g) Concatenation
➢ String concatenation means add strings together.
➢ Use the + character to add a variable to another variable:
Example:
>>>s = 'Hello Goodbye!'
>>> s + '!!'
Output:
'Hello Goodbye!!!'
h) Minimum Value
➢ The min() function returns the item with the lowest value.
➢ If the values are strings, an alphabetically comparison is done.
➢ min(n1, n2, n3, ...) OR min(iterable)
Example:
>>>s = 'Hello Goodbye!'
>>>min(s)
Output: ' '
i) Maximum Value
➢ The max() function returns the item with the lowest value.
➢ If the values are strings, an alphabetically comparison is done.
➢ max(n1, n2, n3, ...) OR max(iterable)
Example:
>>>s = 'Hello Goodbye!'
>>>max(s)
Output: 'y'
j) comparison
➢ Comparison operators are used to compare two values.
Operator Meaning Example
== Is equal to x==y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
38
16. Explain the concept of Strings in python?
➢ A string is a sequence of characters which is enclosed in quotes.
➢ In Python, a string value can be enclosed either in single quotes or double quotes or
triple quotes.
➢ The Python treats both single quote and double quote as same.
➢ For example, the strings ‘Welcome Python' and " Welcome Python " both are same.
➢ We can display a string literal with the print() function.
Example:
Print("Hi Python")
print('Hi Python')
Output:
Hi Python
Hi Python
Assign String to a Variable
➢ Assigning a string to a variable is done with the variable name followed by an equal
sign and the string.
Example
a = "Hi python"
print(a)
Output:
Hi Python
Multiline Strings
➢ We can assign a multiline string to a variable by using three quotes.
Example:
a=””” More things are wrought by prayer than this world dreams
off. An honest man is the noblest work of God. Get place and
wealth, if possible, with grace; if not, by any means get
wealth and place.”””
Print(a)
Output:
More things are wrought by prayer than this world dreams off.
An honest man is the noblest work of God. Get place and wealth,
if possible, with grace; if not, by any means get wealth and
place.
39
Accessing String Values
➢ In Python, a string data value has assigned to a variable and it is organized as an array
of characters.
➢ The Python provides a variety of ways to access the string values.
Example:
0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1
Accessing whole string
➢ To access the entire string which is stored in a variable, we use the variable name
directly.
Example:
a = "Hi python"
print(a)
Output:
Hi Python
Accessing a character from a String Values [Strings are Arrays]
To access a single character from a string variable, we can use the index value in square
brackets of the respective character.
Example:
a=’PYTHON’
print(a[1])
Output:
Y
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "python":
for x in "PYTHON":
print(x)
Output:
P
Y
T
40
H
O
N
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
17. Discuss about string methods in python.
➢ Python has a set of built-in methods that you can use on strings.
➢ All string methods returns new values.
➢ They do not change the original string.
1. Checking the Contents of a String with in and not in operator.
isalpha() Method, isdigit() Method, islower() Method, isupper() Method, lower()
Method, upper() Method.
2. Searching the contents of a string
find() Method
3. Replacing the contents of a string
replace() Method
4. Removing the contents of a string
strip() Method
5. Splitting a string
split() Method
Checking the Contents of a String
➢ To check if a certain phrase or character is present in a string, we can use the keyword
in.
Example 1: Check if "world" is present in the following text.
txt = "Welcome to python world!"
print("world" in txt)
Output:
True
Example 2: Using IF statement
txt = "Welcome to python world!"
if "world" in txt:
print("Yes, 'World' is present.")
Output:
Yes, 'World' is present.
41
Check if NOT
➢ To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example: Check if "universal" is present in the following text.
txt = "Welcome to python world!"
if "world" not in txt:
print("Yes, 'World' is present.")
Output:
True
isalpha() Method
➢ Check if all the characters in the text are letters.
➢ It returns true, if string contains only letters.
➢ Example of characters that are not alphabet letters: (space)!#%&? etc.
➢ Syntax is: [Link]()
Example 1:
S=’hello’
X=[Link]()
Print(X)
Output:
True
Example 2:
S=’hello!!’
X=[Link]()
Print(X)
Output:
False
isdigit() Method
➢ Check if all the characters in the text are digits.
➢ It returns True if all the characters are digits, otherwise False.
➢ Exponents, like ², are also considered as a digit.
Syntax is: [Link]()
Example 1:
S=’123’
42
X=[Link]()
Print(X)
Output:
True
Example 2:
S=’123aa’
X=[Link]()
Print(X)
Output:
False
islower() Method
➢ Check if all the characters in the text are in lower case.
➢ The islower() method returns True if all the characters are in lower case,
otherwise False.
➢ Numbers, symbols and spaces are not checked, only alphabet characters.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
welcome python world!
isupper() Method
➢ Check if all the characters in the text are in upper case.
➢ The isupper() method returns True if all the characters are in upper case,
otherwise False.
➢ Numbers, symbols and spaces are not checked, only alphabet characters.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
WELCOME PYTHON WORLD!
lower() Method
➢ The lower() method returns a string where all characters are lower case.
43
➢ Symbols and Numbers are ignored.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
welcome python world!
upper() Method
➢ Check if all the characters in the text are in upper case.
➢ The upper() method returns True if all the characters are in upper case, otherwise
False.
➢ Numbers, symbols and spaces are not checked, only alphabet characters.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
WELCOME PYTHON WORLD!
Searching the contents of a string
find() Method
➢ The find() method finds the first occurrence of the specified character and returns
its index value.
➢ If the character is not found, it returns the -1.
Example 1:
a = "Welcome Python World!"
print([Link]("e"))
Output:
1
Example 2:
a = "Welcome Python World!"
print([Link](“y”))
Output:
-1
Replacing the contents of a string
44
replace() Method
➢ Returns a string where a specified value is replaced with a specified value.
Example:
a = "Welcome Python World!"
print([Link]("Welcome", "hi"))
Output:
hi Python World!
Removing the contents of a string
strip() Method
➢ The strip() method removes any leading (spaces at the beginning) and trailing
(spaces at the end) characters.
➢ Space is also considered as default leading character to remove.
Example:
S = ' Hello!'
[Link](' !')
print(S)
Output:
Hello!
Splitting a string
split() Method
Splits the string at the specified separator, and returns a list. The default separator is any
whitespace.
Example:
txt = "welcome to the python world"
x = [Link]()
print(x)
Output:
['welcome', 'to', 'the', 'python', 'world']
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
18. Explain about Exception handling in python?
➢ Various error messages can occur when executing Python programs. Such errors are
called exceptions.
➢ An exception can be defined as an unusual condition of a program resulting in the
interruption in the flow of the program.
45
➢ Whenever an exception occurs, it stops the execution of current program, and it cannot
proceed further to execute. An exception is a Python object that represents an error.
➢ An exception is a value (object) that is raised (“thrown”) signalling that an unexpected,
or “exceptional,” situation has occurred.
➢ Python contains a predefined set of exceptions referred to as standard exceptions.
➢ Some standard exceptions are given below:
ImportError Raised when an import(from..import) statement fails
IndexError Raised when a sequence index is out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an object of
inappropriate type
ValueError Raised when a built-in operation or function is applied to an
appropriate value
IOError Raised when an input/output operation fails (e.g., ‘file not found’)
Example 1:
lst = [1, 2, 3]
lsst[0]
Traceback (most recent call last):
File "<ipython-input-2-f6df29656ae2>", line 2, in
<module> lsst[0]
NameError: name 'lsst' is not defined
Example 2:
lst = [1, 2, 3]
lst[3]
Traceback (most recent call last):
File "<ipython-input-4-ecca8424f755>", line 2,in<module>
lst[3]
IndexError: list index out of range
Example 3:
2 + '3'
Traceback (most recent call last):
File "<ipython-input-5-8fd9dcfa4f42>", line 1, in <module>
2 + '3'
46
TypeError: unsupported operand type(s) for +: 'int' and
'str'
Example 4:
int('12.04')
Traceback (most recent call last):
File "<ipython-input-7-6210505837df>", line 1, in <module>
int('12.04')
ValueError: invalid literal for int() with base 10: '12.04'
➢
The Propagation of Raised Exceptions
➢ When an exception is raised and not handled by the client code, it is automatically
propagated back to the client’s calling code (and its calling code, etc.) until handled.
Try
{this code}
Except
{Run this code if exception occurs}
Else
{Run this code if no exception occurs}
➢ Exceptions are caught and handled in Python by use of a try block and exception
handler.
Exception Handling and User Input
➢ Exceptions raised by built-in functions, programmer-defined functions may raise
exceptions as well.
➢ Suppose we prompted the user to enter the current month as a number,
month = input('Enter current month (1–12): ')
➢ The input function will return whatever is entered as a string. We can do integer type
conversion on this value to make it an integer type,
month =int(input('Enter current month (1–12): '))
➢ If the input string contained non-digit characters (except for 1 and 2), the int function
would raise a ValueError exception.
➢ IOError exceptions raised as a result of a file open error can be caught and handled.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
47
PROBLEM SOLVING USING PYTHON
UNIT 5
2 MARKS
1
1. What is associative data structure?
➢ The elements of an associative data structure are unordered, instead accessed by an
associated key value.
➢ In Python, an associative data structure is provided by the dictionary type.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2. What is Dictionary?
➢ A dictionary is a mutable, associative data structure of variable length.
➢ In Python, a dictionary is a collection of elements/ items where each element is a pair
of key and value.
➢ The syntax for declaring dictionaries in Python is given below.
Example:
student_dictionary ={'rollNo':1,'name':'Rani','dept':’CS'}
print(type(student_dictionary))
Output:
<class 'dict'>
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
3. What is Indexed data structure?
➢ Elements of indexed linear data structures, such as lists, are ordered—the first element
(at index 0), second element (at index 1), and so forth.
➢ Index means position or location of data.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4. What is Set data type in python?
➢ A set is a mutable data type with nonduplicate, unordered values, providing the usual
mathematical set operations.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2
5. What is frozen set?
➢ Frozen set is an immutable set type.
➢ Elements of the frozen set remain the same after creation.
➢ Syntax: frozenset([iterable])
Where, Iterable can be set, dictionary, tuple, etc.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
6. List out the Set Operators.
Set Operator Set A={1,2,3} Set B={3,4,5,6}
Membership 1 in A True True if 1 is a member of set
Add [Link](4) {1,2,3,4} Add new member to set
Remove [Link](2) {1,3} Remove member from set
Union A|B {1,2,3,4,5,6} Set of elements in either set
A or set B
Intersection A&B {3} Set of elements in both set A
and set B
Difference A-B {1,2} Set of elements in set A, but
not set B
Symmetric difference A^B {1,2,4,5,6} Set of elements in set A or
set B, but not both.
Size len(a) 3 Number of elements in set
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7. What is Object Oriented programming?
➢ Object oriented programming (OOP) is a structure of program with properties and
methods of individual objects.
➢ An object is a data of a program.
➢ Every object has its properties and methods.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
8. What is a class?
➢ A class specifies the set of instance variables and methods that are “bundled together”
for defining a type of object.
➢ A class is a "blueprint” to define an object.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
9. What are the three fundamental features of Object-Oriented Programming?
The three fundamental features of object-oriented programming:
1. Encapsulation
3
2. Inheritance
3. Polymorphism
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10. What is Encapsulation?
Encapsulation is a means of bundling together instance variables and methods to form a given
type, as well as a way of restricting access to certain class members.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
11. What is Inheritance?
➢ The inheritance is the process of acquiring (inherit) the properties of one class to
another class.
➢ The inheriting class is called a subclass (also “derived class” or “child class”), and the
class inherited from is called the superclass (also “base class” or “parent class”).
Parent Class
Child Class
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
12. What is subtype?
A subtype is something that can be substituted for and behave as its parent type (and its parent
type, etc.).
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
13. What is Polymorphism?
In object-oriented programming, polymorphism allows objects of different types, each with
their own specific behaviors, to be treated as the same general type.
Example:
Shape
Circle Square
Triangle
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4
14. What is Recursive function?
➢ A recursive function is a function that calls itself.
➢ Example for recursive function is finding factorial of a given number.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
15. Write about three important characteristics of recursive function.
1. There must be at least one base case (a problem instances whose solution is known
without further recursive breakdown).
2. Problems that are not a base case are broken down into subproblems that are a similar
kind of problem as the original problem and work towards a base case.
3. There is a way to derive the solution of the original problem from the solutions of the
recursively solved subproblems.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
16. List out the difference between Set and Frozen set.
Set Frozen Set
A Set can be defined as an unordered list of Frozen set is an immutable (unchangeable)
data types that are iterable, changeable set type.
(mutable), and doesn’t have copy items.
In Python sets, you can change the items Items of the frozen set remain the same once
when you required, created. Because of this, frozen sets are used
as a key in Dictionary.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =