You are on page 1of 39

PROBLEM SOLVING USING 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

From here, (18)10 = (10010)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.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =

10. What is Main Memory?

➢ 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?

➢ 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.
➢ The word “algorithm” is derived from the ninth-century Arab mathematician, Al-
Khwarizmi, who worked on “written processes to achieve some goal.” (The term
“algebra” also derives from the term “al-jabr,” which he introduced.)
= = = = = == = = == == == = = = = = = = = = = = = = = = = = = = = = = == = = = = = = =
2. Write about fundamental hardware component?
➢ The central processing unit (CPU) is the “brain” of a computer system, containing
digital logic circuitry able to interpret and execute instructions.
➢ Main memory in a computer is called Random Access Memory. It is also known as
RAM.
➢ In main memory currently executing programs reside, when programs and data become
active, they are copied from secondary memory into main memory where the processor
can interact with them.
➢ A copy remains in secondary memory.
➢ Main memory is intimately connected to the processor, so moving instructions and data
into and out of the processor is very fast.
➢ Main memory is volatile; that is, the contents are lost when the power is turned off.
➢ In contrast, secondary memory is nonvolatile, and therefore provides long-term
storage of programs and data.
➢ For example, can be magnetic (hard drive), optical (CD or DVD), or nonvolatile flash
memory (such as in a USB drive).
➢ Input/output devices include anything that allows for input (such as the mouse and
keyboard) or output (such as a monitor or printer).
➢ Finally, buses transfer data between components within a computer system, such as
between the CPU and main memory.
➢ The relationship of these devices is depicted in Figure below.

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.

Execution of machine code


➢ A program written in high-level language is called as source code.
➢ To convert the source code into machine code, translators are needed.

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).

Operator Description Syntax


+ Addition: adds two operands x+y
- Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
Modulus: returns the remainder when first operand is divided by the
% x%y
second
** Power : Returns first raised to power second x ** y

# Examples of Arithmetic Operator


a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a – b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)

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

Start state FWGC ____

Farmer takes the Goat to the right river bank _W_C F_G_

Farmer returns alone with the boat back FW_C __G_

Farmer takes the Wolf to the right river bank ___C FWG_

Farmer returns back with the Goat F_GC _W__

Farmer takes the Cabbage across the river __G_ FW_C

Farmer returns back alone F_G_ _W_C

Farmer takes the goat across. Exit state reached! ____ FWGC

= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =

2. Explain the Process of Computational Problem Solving.


➢ Computational problem solving is a process with programming and followed by the
steps of : analysis, design, implementation and testing. This is shown in the following
figure.

Process of Computational Problem Solving

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
= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =

3. Discuss briefly about operators of python?


➢ 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.

Python divides the operators in the following groups:

• 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,

Operator Description Example


Assigns values from right side
= c = a + b assigns value of a + b into c
operands to left side operand
+= Add It adds right operand to the left operand
c += a is equivalent to c = c + a
AND and assign the result to left operand
-= It subtracts right operand from the left
Subtract operand and assign the result to left c -= a is equivalent to c = c - a
AND operand
*= It multiplies right operand with the left
Multiply operand and assign the result to left c *= a is equivalent to c = c * a
AND operand
It divides left operand with the right
/= Divide
operand and assign the result to left c /= a is equivalent to c = c / a
AND
operand
%=
It takes modulus using two operands
Modulus c %= a is equivalent to c = c % a
and assign the result to left operand
AND
**= Performs exponential (power)
Exponent calculation on operators and assign c **= a is equivalent to c = c ** a
AND value to the left operand
//= Floor It performs floor division on operators
c //= a is equivalent to c = c // a
Division and assign value to the left operand

Comparison Operators
➢ Comparison operators are used to compare two values. They are also called Relational
operators.
➢ Assume variable a = 10 and variable b = 20,

Operator Description Example


If the values of two operands are equal,
== (a == b) is not true.
then the condition becomes true.
If values of two operands are not equal,
!= (a != b) is true.
then condition becomes true.
If values of two operands are not equal, (a <> b) is true. This is similar to !=
<>
then condition becomes true. operator.

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.

Operator Description Example


Returns True if both variables are the x is y, here is results in 1 if id(x) equals
is
same object id(y).
Returns True if both variables are not x is not y, here is not results in 1 if id(x)
is not
the same object is not equal to id(y).

Membership Operators
➢ Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples.

Operator Description Example


Returns True if a sequence with the x in y, here in results in a 1 if x is a
in
specified value is present in the object member of sequence y.

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
= = = = = = = = = = == = = = = == = = = = = = = = = = = = = = = = = = == = = = = == = = = = = = = == = = =

4. Explain data type in Python.


➢ A variable is a name that is assigned to a value.
➢ Python has the following data types built-in by default, in these categories:

Text Type str


Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset

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

t[0:3] = (5, 'program', (1+3j))


Python Strings:
➢ String is sequence of Unicode characters.
➢ We can use single quotes or double quotes to represent strings.
➢ Multi-line strings can be denoted using triple quotes, ''' or """.
Example:
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output
This is a string
A multiline
String

➢ 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

➢ Set is an unordered collection of unique items.


➢ Set is defined by values separated by comma inside braces { }.
➢ Items in a set are not ordered.

Example:

a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

# data type of variable a


print(type(a))

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

You might also like