0% found this document useful (0 votes)
2 views

Python final qb

The document outlines various features of Python, including its ease of use, interactive mode, and extensive libraries. It explains fundamental concepts such as classes, objects, data abstraction, and file handling modes, along with control structures and decision-making statements. Additionally, it covers operators, loop control statements, and command line arguments with examples for clarity.

Uploaded by

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

Python final qb

The document outlines various features of Python, including its ease of use, interactive mode, and extensive libraries. It explains fundamental concepts such as classes, objects, data abstraction, and file handling modes, along with control structures and decision-making statements. Additionally, it covers operators, loop control statements, and command line arguments with examples for clarity.

Uploaded by

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

List Python features.

(Any four)
Easy to Learn and Use
Interactive Mode
Expressive Language
Interpreted Language
Cross-platform Language
Portable
Free and Open Source
Object-Oriented Language
Extensible
Large Standard Library
GUI Programming Support

Define class and object


Class: A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together.
Object: An object is an instance of a class that has some attributes and behavior. Objects can
be used to access the attributes of the class.

List different modes of opening file in Python Modes for opening file:
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some data then it
will be overridden.
• a: open an existing file for append operation. It won‟t override existing data.
• r+: To read and write data into the file. The previous data in the file will be overridden.
• w+: To write and read data. It will override existing data.
• a+: To append and read data from the file. It won‟t override existing data.

Write syntax for a method to sort a list


Syntax of sort method for a list: list.sort(reverse=True|False, key=myFunc)
What is data abstruction and data hiding.
Data abstraction: Data Abstraction is used to hide the internal functionality of the function
from the users. The users only interact with the basic implementation of the function, but
inner working is hidden. User is familiar with that "what function does" but they don't know
"how it does."
Data hiding: Data hiding is a concept which underlines the hiding of data or information from
the user. Data hiding is a software development technique specifically used in Object-
Oriented Programming (OOP) to hide internal object details (data members). Data hiding
includes a process of combining the data and functions into a single unit to conceal data
within a class by restricting direct access to the data from outside the class.

Explain building blocks


1) Python Identifiers: Variable name is known as identifier. To name an identifier
following are the rules:
• The first character of the variable must be an alphabet or underscore ( _ ).
• All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore or digit (0-9).
• Identifier name must not contain any white-space, or special character (!, @, #, %,
^, &, *). • Identifier name must not be similar to any keyword defined in the
language.
Identifier names are case sensitive for example my name, and MyName is not the
same. Eg: a,b,c=5,10,15
2) Reserved Words The following list shows the Python keywords. These are reserved words
and cannot use them as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only.
3) Indentation: Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is
compulsory.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the same amount.
For example – if True: print "True" else: print "False" Thus, in Python all the continuous lines
indented with same number of spaces would form a block.
4) Python Types: The basic types in Python are String (str), Integer (int), Float (float), and
Boolean (bool). There are also built in data structures to know when you learn Python. These
data structures are made up of the basic types, you can think of them like Legos, the data
structures are made out of these basic types. The core data structures to learn in Python are
List (list), Dictionary (dict), Tuple (tuple), and Set (set).
Strings Strings in Python are assigned with single or double quotations. As in many other
programming languages, characters in strings may be accessed as if accessing an array. In the
example below we’ll assign a string to a variable, access the first element, check for a
substring, and check the length of the string. x = 'abcd'
Numbers: Integers and Floats in Python are both Number types. They can interact with each
other, they can be used in all four operations. In the example code we’ll explore how these
numbers can interact. x = 2.5 y = 2
Boolean: Boolean variables in Python are either True or False. They will also return True for
1 and False for 0. The example shows how to assign either True or False to a variable in
Python x = True y = False
Lists: Lists in Python are represented with brackets. Like characters in a string, the elements
in a list can be accessed with brackets. Lists can also be enumerate‘d on to return both the
index and the element. We’ll go over enumerate when we cover for loops in Python. The
example code shows how to declare lists, print elements in them, add to them, and remove
from them. x = [10, 25, 63, 104] y = ['a', 'q', 'blah']
Dictionaries: Dictionaries in Python are a group of key-value pairs. Dictionaries are declared
with curly braces and their entries can be accessed in two ways,
a) with brackets, and
b) with .get.
The example code shows how we can access items in a dictionary. _dict = { 'a': 'Sally sells
sea shells', 'b': 'down by the seashore' }
Tuples: Tuples is an immutable sequence in Python. Unlike lists, you can’t move objects out
of order in a Tuple. Tuples are declared with parenthesis and must contain a comma (even if it
is a tuple of 1). The example below shows how to add tuples, get a tuple from a list, and
return information about it.
Sets: Sets in Python are the non-duplicative data structure. That means they can only store
one of an element. Sets are declared with curly braces like dictionaries, but do not contain ‘:’
in them. The example code shows how to turn a list into a set, access set elements by index,
add to a set, and remove from a set. # we can turn a list into a set x = ['a', 'a', 'b', 'c', 'c'] x =
set(x)
5) Control structures: Control structures are used to determine the flow of execution of a
Python program. Examples of control structures in Python include if-else statements, for and
while loops, and try-except blocks.
6) Functions: Functions are reusable blocks of code that perform specific tasks. In Python,
functions are defined using the def keyword.
7) Modules: Python modules are files that contain Python code and can be imported into
other Python programs to reuse code and simplify development.
8) Packages: Packages are collections of related Python modules that can be installed and
imported together. Packages are commonly used in Python for organizing and distributing
libraries and tools.
Explain decision making statements if-else, if-elif-else with example.
Decision-making statements in Python allow the execution of specific blocks of code based
on conditions. Python provides several constructs for decision-making if-else Statement
The if-else statement is used to test a condition. If the condition is True, the code inside the if
block is executed. If the condition is False, the code inside the else block is executed.
Syntax: if condition:
# Code block to execute if the condition is True
else:
# Code block to execute if the condition is False
Example: age = 16 if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
if-elif-else Statement
The if-elif-else statement is used when there are multiple conditions to check. Python
evaluates each if or elif condition in sequence. If one of the conditions evaluates to True, the
corresponding block of code is executed, and the rest are skipped. If none of the if or elif
conditions are True, the code inside the else block is executed.
Syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition1 is False and condition2 is True
else:
# Code block to execute if both condition1 and condition2 are False
Example:
age = 25
if age < 13:
print("You are a child.")
elif 13 <= age <= 19:
print("You are a teenager.")
elif 20 <= age <= 59:
print("You are an adult.")
else:
print("You are a senior.")

Explain identity and assignment operators with example


Identity operators in Python are used to compare the memory addresses of two objects,
determining whether two variables or objects reference the same memory location. There are
two primary identity operators in Python.
1) is operator: Returns True if two variables refer to the same memory location.
2) is not operator: Returns True if two variables do not refer to the same memory location.
• Example 1: Using the "is" Operator
x =[1,2,3]
y=x
result = x is y
print(result) # Output: True
Example 2: Using the "is not" Operator
a ="hello"
b ="world"
result = a is not b print(result) # Output: True
Assignment Operators (Augmented Assignment Operators):
Assignment operators are used in Python programming to assign values to variables. The
assignment operator is used to store the value on the right-hand side of the expression on the
left-hand side variable in the expression.
For example, a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left. There are various compound operators in Python like a += 5 that adds
to the variable and later assigns the same. It is equivalent toa = a + 5.
Membership Operators:
The membership operators in Python are used to find the existence of a particular element in
the sequence, and used only with sequences like string, tuple, list, dictionary etc. Membership
operators are used to check an item or an element that is part of a string, a list or a tuple. A
membership operator reduces the effort of searching an element in the list. Python provides
‘in’ and ‘not in’ operators which are called membership operators and used to test whether a
value or variable is in a sequence.
Bitwise operators available in Python:
1) Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits of two
numbers. Each bit of the output is 1 if the corresponding bits of both operands are 1;
otherwise, it is 0. Example:
a = 10 # binary: 1010
b = 6 # binary:
result = a & b
print(result) # Output: 2 (binary: 0010)
2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two
numbers. Each bit of the output is 0 if the corresponding bits of both operands are 0;
otherwise, it is 1.
Example: a = 10 # binary: 1010
b = 6 # binary: 0110
result = a | b
print(result) # Output: 14 (binary: 1110)
3) Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the corresponding
bits of two numbers. Each bit of the output is 1 if the corresponding bits of the operands are
different; otherwise, it is 0.
Example:
a = 10 # binary: 1010
b = 6 # binary: 0110
result = a ^ b
print(result) # Output: 12 (binary: 1100)
4) Bitwise NOT (~): Performs a bitwise NOT operation on a single operand, which inverts all
the bits. It returns the complement of the given number.
Example: a = 10 # binary: 1010
result = ~a
print(result) # Output: -11 (binary: -1011)
5) Bitwise left shift (<<< 2 print(result) # Output: 40 (binary: 101000) 6) Bitwise right shift
(>>): Shifts the bits of the left operand to the right by a specified number of positions. Zeros
are shifted in from the left side.
Example:
a = 10 # binary: 1010
result = a >> 2
print(result) # Output: 2 (binary: 10)
Explain loop control statement in python.
Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted when
execution is completed. Python provides the following control statements.
1) Break statement This command terminates the loop's execution and transfers the program's
control to the statement next to the loop.
Example
for letter in 'python programming':
if letter == 'y' or letter == 'm':
break
print('Current Letter :', letter)
output : Current Letter : y
2) Continue statement This command skips the current iteration of the loop. The statements
following the continue statement are not executed once the Python interpreter reaches the
continue statement.
Example :
for letter in 'python program':
if letter == 'y' or letter == 'm':
continue
print('Current Letter :', letter)
3) Pass statement The pass statement is used when a statement is syntactically necessary, but
no code is to be executed.
Example :
for letter in 'python':
pass
print('Last Letter :', letter)
What is command line argument ? Write python code to add b) two numbers given as input from
command line arguments and print its sum.

You might also like