Uploaded by Bhavana C D

python module1 (QA)

advertisement
Introduction to Python
Module 1:
1.
List the salient features of Python programming Language, Demonstrate
with example print(), input() and len() in python
ANS:
Salient Features of Python:(any 5)
Readable and Simple Syntax: Python's syntax is easy to read and write, making it
accessible for beginners and experienced programmers alike.
High-Level Language: Python abstracts low-level details, providing a high-level
language that simplifies programming.
Interpreted Language: Python code is executed line by line by an interpreter,
which means you can interact with the code in a more dynamic way.
Dynamically Typed: Python is dynamically typed, allowing you to change the
data type of a variable during runtime.
Cross-Platform: Python is available on various platforms, and code can be run on
different operating systems without modification.
Rich Standard Library: Python comes with a comprehensive standard library,
providing ready-to-use modules and packages.
Support for Multiple Programming Paradigms: Python supports
procedural, object-oriented, and functional programming styles.
Community Support: Python has a large and active user community, with
extensive documentation and third-party libraries.
Integration with Other Languages: Python can be integrated with other languages
(e.g., C, C++) for performance-critical tasks.
Open Source: Python is open-source, which means it's free to use and has a large
ecosystem of libraries and tools.
print() Function: The print() function is used to display output to the console.
# Example using print()
name = "Manoj"
age = 21
print("Hello, my name is", name)
print("I am", Age, "years old")
Output:
Hello, my name is
Manoj Age 21
input() Function: The input() function is used to get user input from the console.
#Example using input()
name = input("Enter your name: ")
print("Hello,", name)
Output:
Enter your name: Alice
Hello, Alice
# Example using len()
text = "Python is a versatile language"
length = len(text)
print("Length of the text:", length)
Output:
Length of the text: 30
2.
Explain string concatenation and string replication with one suitable
examples for each
ANS:
String Concatenation in Python involves combining two or more strings to
create a single, longer string. This is achieved using the + operator or by placing
the strings next to each other.
Here's an example:
# String Concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Output:
John Doe
In the above example, two strings, first_name and last_name, are concatenated
using the + operator to create the full_name string. The space " " is used to
separate the first and last names.
String Replication in Python involves creating a new string by repeating an
existing string multiple times. This is done using the * operator.
Here's an example:
# String Replication
message = "Hello, "
repeated_message = message * 3
print(repeated_message)
Output:
Hello, Hello, Hello
3.
Explain basic functions in Python by considering str(), int() and float()
as point of ref
ANS
The str(), int(), and float() functions in Python are essential for type conversion
and data manipulation.
str() Function: The str() function is used to convert a value to a string type. It
takes any valid Python object and returns a string representation of that object
Example:
num = 42
num_str = str(num)
print(num_str)
Output : ‘42’
In this example, the str() function converts the integer 42 into a string, and
num_str holds the string representation of the number
int() Function: The int() function is used to convert a value to an integer type. It
takes a string or a floating-point number as input and returns an integer if the
conversion is possible.
Example:
num_str = "42"
num =
int(num_str)
print(num)
Output :42
In this example, the int() function converts the string "42" to an integer.
float() Function: The float() function is used to convert a value to a floating-point
number. It takes a string or an integer as input and returns a floating-point number if
the conversion is possible.
Example:
num_str = "3.14"
num =
float(num_str)
print(num)
Output:3.14
In this example, the float() function converts the string "3.14" to a floating-point
number.
4.
What are Comparison and Boolean operators? List all the Comparison
and Boolean operators in Python and explain the use of these operators
with suitable
ANS:
Comparison Operators: Comparison operators in Python are used to compare
values, expressions, or variables. They return a Boolean value (True or False)
indicating the result of the comparison. These operators are commonly used in
conditional statements and expressions to control the flow of a program.
1. Equal
(==): Compares if two values are equal.
2. Not Equal (!=): Compares if two values are not equal.
3. Greater Than (>): Compares if the left value is greater than the right value.
4. Less Than (<): Compares if the left value is less than the right value.
5. Greater Than or Equal To (>=): Compares if the left value is greater than or
equal to the right value.
6. Less Than or Equal To (<=): Compares if the left value is less than or equal to
the right value.
Boolean Operators:
Boolean operators are used to combine or manipulate Boolean values. They are
often used to create more complex conditions or expressions by combining
simpler conditions.
List of Boolean Operators in Python:
1. Logical
AND (and): Returns True if both conditions are True.
2. Logical OR (or): Returns True if at least one condition is True.
3. Logical NOT (not): Returns the opposite of the condition; if the condition is
True, it returns False, and vice versa.
Example:
# Comparison Operators
x=5
y = 10
# Equal
result1 = x == y # False
# Not Equal
result2 = x != y # True
# Greater Than result3
=x>y
# False
# Less Than
result4 = x < y # True
# Greater Than or Equal To
result5 = x >= y # False
# Less Than or Equal To
result6 = x <= y # True
# Boolean Operators
a = True
b = False
# Logical AND
result7 = a and b # False
# Logical OR
result8 = a or b # True
# Logical NOT
result9 = not a # False
5.
Explain different ways of importing modules into application in Python
with syntax and suitable programming examples
ANS:
in Python, modules are files containing Python code that can be used to organize,
reuse, and modularize your code. You can import modules in various ways.
1. Importing the Whole Module:
You can import the entire module using the import statement. This allows you to
access all the functions, variables, and classes defined in the module.
Syntax:
import module_name
Example:
Suppose you have a module named math_operations.py:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
You can import the whole module as follows:
import math_operations
result = math_operations.add(5, 3)
2. Importing Specific Functions or Variables:
You can import specific functions or variables from a module, allowing you to use
them directly without specifying the module name.
Syntax:
from module_name import function_name, variable_name
Example:
Using the same math_operations.py module:
from math_operations import add
result = add(5, 3)
3. Using an Alias:
You can provide an alias to the module or specific items you import. This is useful
when you want to avoid naming conflicts or when the module name is lengthy.
Syntax:
import module_name as alias
Example:
Using an alias for the math_operations.py module:
import math_operations as mo
result = mo.add(5, 3)
4. Importing Everything from a Module:
You can import all functions, variables, and classes from a module using the *
wildcard. Be cautious with this approach to avoid naming conflicts.
Syntax:
from module_name import *
Example:
Using the * wildcard for the math_operations.py module:
from math_operations import *
result = add(5, 3)
5. Importing Built-in Modules:
Python includes a variety of built-in modules that you can import and use without
installing external packages.
Syntax:
import module_name
Example:
Importing the math module for mathematical operations:
import math
result = math.sqrt(16)
These different ways of importing modules provide flexibility in organizing and
reusing code, making Python an adaptable language for various programming tasks.
When using external modules, you can install them using tools like pip and then
import them similarly as shown in the examples above.
6.
What is Exception Handling? How are exceptions handled in Python?
Write a Python program with exception handling code to solve an error
situation
ANS:
Exception Handling in programming is the process of dealing with runtime errors,
also known as exceptions, in a controlled and graceful manner. When a program
encounters an exception, it can disrupt the normal flow of execution. Exception
handling helps you catch and manage these errors, preventing program crashes and
improving the user experience.
In Python, exceptions are handled using try, except, else, and finally blocks. Here's
a brief explanation of these components:
try: This block contains the code where an exception may occur.
except: This block contains the code to handle exceptions. You can specify which
exception(s) to catch.
else: This block is executed when no exceptions are raised in the try block.
finally: This block is always executed, whether an exception occurs or not. It is
used for cleanup operations.
Here's a small Python program that demonstrates exception handling:
python
try:
num = int(input("Enter a number:
")) result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
else:
print(f"Result: {result}")
finally:
print("Execution completed.")
In this program:
The try block attempts to get an integer input from the user and performs a
division operation.
If a ZeroDivisionError occurs (dividing by zero) or a ValueError occurs
(non-integer input), the program handles these specific exceptions and prints error
messages.
If no exceptions occur in the try block, the else block is executed, displaying the
result of the division.
Finally, the finally block is always executed, indicating the completion of the
execution, whether an exception occurred or not.
Exception handling in Python is crucial for creating robust and reliable programs, as
it allows you to gracefully handle errors and avoid program crashes.
7.
Explain Local and Global Scope in Python programs. What are local
and global variables? How can you force a variable in a function to refer to
the global variable?
ANS:
Local and Global Scope in Python:
In Python, variables have different scopes, which define where they can be
accessed or modified in a program. The two primary scopes are:
Local Scope: Variables defined within a function have local scope. They are only
accessible within that function and are not visible outside of it.
Global Scope: Variables defined outside of any function have global scope. They
can be accessed and modified from any part of the program.
Local Variables:
Local variables are defined within a function and can only be accessed within
that function. They are temporary and exist as long as the function is executing.
Once the function exits, local variables are destroyed.
Example of local variables:
def my_function():
local_var = 42
print(local_var)
my_function()
# Accessing local_var outside the function will result in an error
In this example, local_var is a local variable defined within my_function. It can only
be accessed within the function.
Global Variables:
Global variables are defined outside of any function and can be accessed from
anywhere in the program. They have a more extended lifetime and persist
throughout the program's execution.
Example of global variables:
global_var = 10
def my_function():
print(global_var)
my_function()
print(global_var)
Here, global_var is a global variable defined outside the function. It can be
accessed both inside and outside the function.
Forcing a Variable in a Function to Refer to the Global Variable:
If you want to modify a global variable from within a function (instead of creating
a local variable with the same name), you can use the global keyword to indicate
that the variable is a global one. This is how you force a variable in a function to
refer to the global variable:
global_var = 10
def
modify_global_variable():
global global_var
global_var = 20
modify_global_variable()
print(global_var)
# This will print 20
In this example, the global keyword inside the function tells Python that global_var
is a global variable, not a local one. As a result, it modifies the global variable's
value.
Download