21cs15it Problem Solving and Python Revision Questions and Answers (2)
21cs15it Problem Solving and Python Revision Questions and Answers (2)
PART B
1. Explain in detail about the Operators in Python.
4. Write algorithm, pseudo code and flowchart to find the eligibility for
voting?
Start
Input the age of the person.
Check if the age is 18 or above.
If true, the person is eligible to vote.
If false, the person is not eligible to vote.
Display the result.
End
5. Write algorithm, pseudo code and flowchart to check whether the number is
palindrome or not.
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
11. Write a function that takes a string as a parameter and replaces the first
letter of every word with the corresponding uppercase letter.
19. Evaluate the different values (data types) and types of values that can be
used in Python.
20. Explain pseudocode and its rules also give examples for sequence,
selection and repetition type problems
21. Develop a flowchart to check whether the given number is a prime number or
not.
PART C
1. Write algorithm, pseudo code and flowchart to find Prime number or not.
Algorithm to Check if a Number is Prime:
Step-1:Start.
Step-2:Input the number n to be checked.
Step-3:If n <= 1, output that n is not prime and exit.
Step-4:for i from 2 to sqrt(n):
Step-5:If n % i == 0, then output that n is not prime and exit.
Step-6:If no divisors were found, output that n is prime.
Step-7:End.
2. Write algorithm, pseudo code and flowchart to check whether the number is
Armstrong or not.
Algorithm to Check if a Number is Armstrong:
Step-1:Start.
Step-2:Input the number n to check.
Step-3:Find the number of digits in n and store it in num_digits.
Step-4:Initialize sum to 0 and temp to n.
Step-5:while temp > 0:
Step-6:Extract the last digit of temp (digit = temp % 10).
Step-7:Raise the digit to the power num_digits and add the result to sum.
Step-8:Remove the last digit from temp (temp = temp // 10).
Step-9:If sum is equal to n, output that n is an Armstrong number.
Step-10:Otherwise, output that n is not an Armstrong number.
Step-11:End.
2.(i). Write a python program to find the greatest among three numbers.
# greatest of three numbers
a=eval(input("enter the value of a:"))
b=eval(input("enter the value of b:"))
c=eval(input("enter the value of c:"))
if (a>b and a>c):
print("the greatest no is",a)
elif(b>a and b>c):
print("the greatest no is",b)
else:
print("the greatest no is",c)
Example Output:
Enter the first number: 12
Enter the second number: 45
Enter the third number: 30
The greatest number among 12.0, 45.0, and 30.0 is: 45.0
This program works for both integers and floating-point numbers.
(ii). Write a program to check the given number is Armstrong number or not.
# Write a program to check the given number is Armstrong number or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
Output:
enter a number:153
153 is an Armstrong number.
Write a function that takes a number as an input parameter and returns the
corresponding
text in words, for example, on input 452, the function should return ‘Four
Five Two’.
Use a dictionary for mapping digits to their string representation.
def number_to_words(number):
# Dictionary to map digits to their corresponding words
digit_map = {
'0': 'Zero',
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
'5': 'Five',
'6': 'Six',
'7': 'Seven',
'8': 'Eight',
'9': 'Nine'
}
# Convert the number to a string so we can iterate over each digit
number_str = str(number)
# Create a list of words corresponding to each digit
words = [digit_map[digit] for digit in number_str]
# Join the words with a space and return
return ' '.join(words)
# Example usage:
result = number_to_words(452)
print(result) # Output: "Four Five Two"
Example Output:
Input: 452 → Output: "Four Five Two"
Input: 908 → Output: "Nine Zero Eight"
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Important questions
UNIT-III-MODULES,PACKAGES,STRINGS
1. Explain how module allows to logically organize Python code.
MODULES:
• A module allows to logically organize Python code.
• Grouping related code into a module makes the code easier to understand
and use.
• A module is a Python object with arbitrarily named attributes that can
bind and reference.
• Simply, a module is a file consisting of Python code.
• A module can define functions, classes and variables.
• A module can also include runnable code.
EXAMPLE:
• The Python code for a module named aname normally resides in a file
named aname.py.
• Example of a simple module, support.py
The import Statement:
• Python source file as a module by executing an import statement in some
other Python source file. The import has the following
syntax −import module1[, module2[,... moduleN]]
• When the interpreter encounters an import statement, it imports the
module if the module is present in the search path.
• A search path is a list of directories that the interpreter searches
before importing a module.
• A module is loaded only once, regardless of the number of times it is
imported.
• This prevents the module execution from happening over and over again if
multiple imports occur.
The from...import Statement:
• The from ...import statement in python imoprts a specified attributes
from a module into the current namespace
• The from...import statement imports all the attributes of a
module into the current namespace.
The from...import has the following syntax − from modname import name1[,
name2[, ... nameN]]
Locating Modules:
• The current directory.
• If the module isn't found, Python then searches each directory in the
shell variable PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
• The module search path is stored in the system module sys as the
sys.path variable.
• The sys.path variable contains the current directory, PYTHONPATH, and
the installation-dependent default.
The PYTHONPATH Variable:
• The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.PYTHONPATH from a Windows system
Namespaces and Scoping:
• Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects (values).
• Access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable shadows the
global variable.
• Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.
• Python makes educated guesses on whether variables are local or
global.It assumes that any variable assigned a value in a function is local.
• Therefore, in order to assign a value to a global variable within a
function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
For example, a variable number in the global namespace.
• Within the function addnumber, assign number a value, therefore Python
assumes number as a local variable.
• However, we accessed the value of the local variable number before
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.
The dir() Function:
• The dir() built-in function returns a sorted list of strings containing
the names defined by a module.
• The list contains the names of all the modules, variables and functions
that are defined in a module. Following is a simple example
globals() and locals() Functions:
• The globals() and locals() functions can be used to return the names in
the global and local namespaces depending on the location from where they are
called.
• If locals() is called from within a function, it will return all the
names that can be accessed locally from that function.
• If globals() is called from within a function, it will return all the
names that can be accessed globally from that function.
• The return type of both these functions is dictionary. Therefore, names
can be extracted using the keys() function.
The reload() Function:
• When the module is imported into a script, the code in the top-level portion
of a module is executed only once.
• Therefore, if you want to reexecute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously imported
module again. The syntax of the reload() function is this −
• Syntax:reload(module_name)
• Example:Here, module_name is the name of the module you want to reload and
not the string containing the module name. For example, to reload hello
module, do the following −
• reload(hello)
4. Describe the use of try block and except block in Python with syntax.
1. Try –Except Statements
• The try and except statements are used to handle runtime errors
Syntax:
try :
statements
except :
statements
The try statement works as follows:-
First, the try clause (the statement(s) between the try and except keywords)
is
executed.
If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the
clause is
skipped. Then if its type matches the exception named after the except
keyword,
the except clause is executed, and then execution continues after the try
statement.
2. Try – Multiple except Statements
o Exception type must be different for except statements
Syntax:
try:
statements
except:
statements
except:
statements
3. Try –Except-Else
o The else part will be executed only if the try block does not raise the
exception.
o Python will try to process all the statements inside try block. If value
error occur,
the flow of control will immediately pass to the except block and remaining
statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
4. Raise statement
• The raise statement allows the programmer to force a specified exception to
occur.
5. Try –Except-Finally
A finally clause is always executed before leaving the try statement,
whether an
exception has occurred or not.
The finally clause is also executed “on the way out” when any other clause
of the
try statement is left via a break, continue or return statement.
Syntax
try:
statements
except:
statements
finally:
statements
from * add import add
from * sub import sub
from * mul import mul
from * div import div
import calculator
importsys
sys.path.append(“C:/Python34”)
print ( calculator.add(10,5))
print ( calculator.sub(10,5))
print ( calculator.mul(10,5))
print ( calculator.div(10,5))
1. Why do we go for file?
File can a persistent object in a computer. When an object or state is created
and needs to be persistent, it is saved in a non-volatile storage location,
like a hard drive.
7. Write a program to add some content to existing file without effecting the
existing content.
file=open(“newfile.txt”,’a)
file.write(“hello”)
file.close()
8. What is package?
• A package is a collection of python module. Module is a single python file
containing function
definitions
• A package is a directory(folder)of python module containing an additional
init py file, to
differentiate a package from a directory
• Packages can be nested to anydepth, provided that the corresponding
directories contain their
own init py file
9. What is module?
A python module is a file that consists of python definition and statements. A
module can
define functions, classes and variables.
makes the code easier to understand and use.