Python Mini
Python Mini
Python follows the object-oriented paradigm 2. Write a python program to capitalize every 3rd letter of string in
Programming or scripting? Python
Python allows the creation of objects and their manipulation through specific methods
Python is an interpreted language. That means that, unlike languages like C and It supports most of the features of OOPS such as inheritance and polymorphism Ans----
its variants, Python does not need to be compiled before it is run. Other s = "xxxyyyzzz"
interpreted languages include PHP and Ruby. Python follows the functional programming paradigm
Python is
# convert to list
variables when you declare them or anything like that. You can do things Functions may be used as the first-class object
a = list(s)
like x=111 and then x="I'm a string" without error
Python is well suited to object orientated programming in that it allows the Python supports Lambda functions which are characteristic of the functional paradigm
definition of classes along with composition and inheritance. Python does not # change every third letter in place with a list comprehension
public, private).
4. What are string literals? Explain. What is Escape sequences with examples. a[2::3] = [[Link]() for x in a[2::3]]
In Python, functions are first-class objects. This means that they can be assigned
to variables, returned from other functions, and passed into functions. Classes are Ans. In Python, a string literal is a sequence of characters surrounded by quotes. Python # back to a string
also first-class objects. supports single, double and triple quotes for a string. A character literal is a single s = ''.join(a)
Writing Python code is quick but running it is often slower than compiled -quote "' "' is used
languages. Fortunately Python allows the inclusion of C-based extensions so to give multi-line string literal. print(s)
bottlenecks can be optimized away and often are. The numpy package is a good To test String Literals:
-crunching it output: xxXyyYzzZ
# Demo Program to test String Literals
strings = "This is Python" 3. List the comparison operators and their functions.
Python finds use in many spheres web applications, automation, scientific
char = "C"
get other languages and components to play nice. multiline_str = "'This is a multiline string with more than one line code.'" OPERATOR NAME FUNCTION
== EQUAL X==y
Python is capable of scripting, but in general sense, it is considered as a general- print (strings)
!= Not equal X!=y
purpose programming language. print (char) > Greater than x>y
print (multiline_str) < Less than X<y
[Link] are the benefits of using Python? What are Python namespaces?
>= Greater than or equal x>=y
#End of the Program to
Ans: The benefits of using python are-
Output: <= Less than or equal to X<=y
a. Easy to use Python is a high-level programming language that is easy to This is Python C
use, read, write and learn.
b. Interpreted language Since python is interpreted language, it executes This is a multiline string with more than one line code.
the code line by line and stops if an error occurs in any line. (i) ' In Python strings, the backslash "\" is a special character, also called 4. define python standard libraries. Write down 4 library functions
c. Dynamically typed the developer does not assign data types to variables the character.
at the time of coding. It automatically gets assigned during execution.
and their functions( 1+4)
(ii) It is used in representing certain whitespace characters: \ is a tab, \ is a Ans--- The Python Standard Library contains the exact syntax, semantics, and tokens of
d. Free and open-source Python is free to use and distribute. It is open
newline, and \ is a carriage return. Python. It contains built-in modules that provide access to basic system functionality
source.
like I/O and some other core modules. Most of the Python Libraries are written in the C
e. Extensive support for libraries Python has vast libraries that contain (iii) For example to print the message "It's raining", the Python command is programming language. The Python standard library consists of more than 200 core
almost any function needed. It also further provides the facility to import
>>> print ("It\'s raining") modules. All these work together to make Python a high-level programming language.
other packages using Python Package Manager(pip).
f. Portable Python programs can run on any platform without requiring any It's raining
have access to the functionalities of Python. But other than this, there are several other
change.
g. The data structures used in python are user friendly.
h. It provides more functionality with less coding.
A namespace in python refers to the name which is assigned to each object in python. 1. Define python class? Which key word is used to create a class? 1. TensorFlow: This library was developed by Google in collaboration with
The objects are variables and functions. As each object is created, its name along with Write two character of class. 2+1+2 the Brain Team. It is an open-source library used for high-level computations. It is
space(the address of the outer function in which the object is), gets created. The also used in machine learning and deep learning algorithms. It contains a large
namespaces are maintained in python like a dictionary where the key is the namespace Ans-- A class is a user-defined blueprint or prototype from which objects are number of tensor operations. Researchers also use this Python library to solve
and value is the address of the object. There 4 types of namespace in python- complex computations in Mathematics and Physics.
created. Classes provide a means of bundling data and functionality together.
2. Matplotlib:
1. Built-in namespace These namespaces contain all the built-in objects in python Creating a new class creates a new type of object, allowing new instances of that why it is used in data analysis. It is also an open-source library and plots high-
and are available whenever python is running. type to be made. Each class instance can have attributes attached to it for defined figures like pie charts, histograms, scatterplots, graphs, etc.
2. Global namespace These are namespaces for all the objects created at the level maintaining its state. Class instances can also have methods (defined by their 3. Pandas: Pandas are an important library for data scientists. It is an open-source
of the main program. machine learning library that provides flexible high-level data structures and a
3. Enclosing namespaces These namespaces are at the higher level or outer class) for modifying their state.
variety of analysis tools. It eases data analysis, data manipulation, and cleaning of
function. data. Pandas support operations like Sorting, Re-indexing, Iteration,
To create a class, use the keyword class.
4. Local namespaces These namespaces are at the local or inner function. Concatenation, Conversion of data, Visualizations, Aggregations, etc.
Classes are created by keyword class. 4. Numpy:
3. What are the common built-in data types in Python? What is the Attributes are the variables that belong to a class. used library. It is a popular machine learning library that supports large matrices
difference between .py and .pyc files? and multi-dimensional data. It consists of in-built mathematical functions for
2. Define objects in python . What are the components of an object. easy computations. Even libraries like TensorFlow use Numpy internally to
Ans: The common built-in data types in python are- perform several operations on tensors. Array Interface is one of the key features
Ans-- An Object is an instance of a Class. A class is like a blueprint while an of this library.
Numbers They include integers, floating-point numbers, and complex numbers. eg. 1,
7.9,3+4i instance is a copy of the class with actual values
List An ordered sequence of items is called a list. The elements of a list may belong to
1. What is file handling in python? What is the need of this.(2+3)
dogs to create many different instances, but without the class as a guide, you
different data types. Eg. Ans-- File handling is an integral part of programming. File handling in Python is
would be lost, not knowing what information is required.
Tuple It is also an ordered sequence of elements. Unlike lists , tuples are immutable, simplified with built-in methods, which include creating, opening, and closing
An object consists of : [Link] files are open, Python additionally allows performing various file
State: It is represented by the attributes of an object. It also reflects the operations, such as reading, writing, and appending information.
String A sequence of characters is called a string. They are declared within single or properties of an object.
double-quotes. Eg. , , etc. Often the output screen of a laptop or monitor is not enough to display all
Behaviour: It is represented by the methods of an object. It also reflects the
Set Sets are a collection of unique items that are not in order. Eg. {7,6,8} response of an object to other objects. the data. This usually happens when the data is large and only a limited amount
Identity: It gives a unique name to an object and enables one object to can be displayed on the screen and stored in the memory. Computer memory is
Dictionary A dictionary stores values in key and value pairs where each value can be interact with other objects. volatile, so even if a user tries to store the data in the memory, its contents would
accessed through its key. The order of items is not important. Eg.
be lost once a program is terminated. If the user needs the same data again, either
Boolean There are 2 boolean values- True and False. 3. What is polymorphism in python. Give an example with its output. it has to be entered through a keyboard or regenerated programmatically.
Obviously, both these operations are tedious. Therefore, to permanently store the
Ans: The .py files are the python source code files. While the .pyc files contain the Ans-- A child class inherits all the methods from the parent class. However, in data created in a program, a user needs to save it in a File on a disk or some other
bytecode of the python files. .pyc files are created when the code is imported from some
other source. The interpreter converts the source .py files to .pyc files which helps by
saving time. the child class. In such cases, you will have to re-implement method in the child part or whole
class.
4. What are Keywords in Python? Python an interpreted language. Explain. 2. List the in built file functions and their functions? (Any 5)
There are different methods to use polymorphism in Python. You can use
Ans: Keywords in python are reserved words that have special meaning. They are different function, class methods close() Closes the file
generally used to define type of variables. Keywords cannot be used for variable move ahead and have a look at each of these methods in detail.
or function names. There are following 33 keywords in python- And, Or, Not, If
For, Else, While, Break, As, Is, In, None, true, False, Pass, Return, Try, With etc Code: detach() Returns the separated raw stream from the buffer
An interpreted language is any programming language which is not in machine-level # Python program to demonstrate in-built poly-
code before runtime. Therefore, Python is an interpreted language. fileno() Returns a number that represents the stream, from the operating system's
# morphic functions perspective
[Link] is a literal? Explain the types of literals? What are the different modes
that can be used to test Python Program ? # len() being used for a string
flush() Flushes the internal buffer
print(len("geeks"))
Ans. Literal is a raw data given in a variable or constant.
# len() being used for a list isatty() Returns whether the file stream is interactive or not
In Python, there are various types of literals.
(i) Numeric, (ii) String, & (iii) Boolean print(len([10, 20, 30]))
read() Returns the file content
The modes that can be used to test Python program are output: 5 & 3
(i) Interactive mode readable() Returns whether the file stream can be read or not
4. What is meant by inheritance? List different types of inheritance
(ii) Script mode
Ans---- Inheritance is a process of obtaining properties and
2. Write short notes on Tokens. What are the different operators that can be characteristics(variables and methods) of another class. In this hierarchical readline() Returns one line from the file
used in Python ? order, the class which inherits another class is called subclass or child class, and
Ans. Python breaks each logical line into a sequence of elementary lexical components the other class is the parent class. readlines() Returns a list of lines from the file
known as Tokens. The normal token types are Inheritance is categorized based on the hierarchy followed and the number of
parent classes and subclasses involved.
(i) Identifiers, (ii) Keywords, (iii) Operators, (iv) Delimiters and (v) Literals. seek() Change the file position
There are five types of inheritances:
The operators that can be used in Python 1. Single Inheritance
(i) Arithmetic operators 2. Multiple Inheritance seekable() Returns whether the file allows us to change the file position
3. Multilevel Inheritance
(ii) Relational or Comparative operator
4. Hierarchical Inheritance
tell() Returns the current file position
(iii) Logical operators 5. Hybrid Inheritance
(iv) Assignment operators
1. What is a string in python? What are the different ways to construct a truncate() Resizes the file to a specified size
(v) Conditional operator
strings . Compare single quoted and double quoted python strings.
Ans--- In Python, string is an immutable sequence data type. It is the sequence of writable() Returns whether the file can be written to or not
3. Explain Ternary operator with examples. Is Python Object-oriented or Unicode characters wrapped inside single, double, or triple quotes.
Functional Programming? Strings literals can be constructed in multiple ways using:
Single quotes write() Writes the specified string to the file
Ans. Ternary operator is also known as conditional operator that evaluate something Double quotes
based on a condition being true or false. It simply allows testing a condition in a single Triple quotes writelines() Writes a list of strings to the file
line replacing the multiline if-else making the code compact. Constructor
Variable Name = [on_true] if [Test expression] else [on_false] 3. How to open and close a file in python. ?
Single Quoted Python Strings Vs Double Quoted Python Strings:
Example: min = 50 if 49 < 50 else 70 // min = 50 In Python, there is no difference between strings constructed using single quotes Ans--- Opening: To open a file in Python, we use the open() function. The syntax of
min = 50 if 49 > 50 else 70 // min = 70 and double quotes. It is good if the developer could stick to one convention.
open() is as follows: file_object= open(file_name, access_mode) This function returns a
If a string contains a single quote or double quote - use the other one to avoid
Python is considered a multi-paradigm language. file object called file handle which is stored in the variable file_object. We can use this
escaping it with a backslash, which improves readability.
variable to transfer data to and from the file (read and write) by calling the functions print(str(count)+" "+"times")
read_data()
a new empty file and assigns it the name we specify in the statement.
File overwrites an existing file or File retains the old data and adds
Closing: Once we are done with the read/write operations on a file, it is a good creates a non-existing file new data to the file
practice to close the file. Python provides a close() method to do so. While closing a file, def read_data():
the system frees the memory allocated to it. The syntax of close() is: file_object.close() Opens a file for writing and reading Opens a file for both appending
f = open("[Link]", 'r')
Here, file_object is the object that was returned while opening the file. Python makes and reading
sure that any unwritten or unsaved data is flushed off (written) to the file before it is s = [Link]()
closed. Hence, it is always advised to close the file once our work is done. Also, if the file
object is re-assigned to some other file, the previous file is automatically closed. for i in s:
closed: Returns true if file is closed, false otherwise.
if i[0] == 'I' or i[0] == 'C':
4. Define file. What are the different type of files available in python .
mode: Returns access mode with which file was opened.
differentiate them.(1+1+3) print(i)
name: Returns name of the file.
Ans-- A file is a named location on a secondary storage media where data are else:
permanently stored for later access. softspace: Returns false if space explicitly required with print, true otherwise
pass
Computers store every file as a collection of 0s and 1s i.e., in binary form. def uppercount():
read_data()
Therefore, every file is basically just a series of bytes stored one after the other. There
upper=0
are mainly two types of data files text file and binary file. 1. Write a procedure to traverse every third character of a string.
f1=open("[Link]",'r') Write a Python program to calculate the length of a string. Write
TEXT FILES BINARY FILES
line=[Link]() a program to check if a string is composed of all lower-case
In text file, text, character, numbers In binary file data is stored in binary format and
for i in line:
characters. What is meant by immutable strings? 5+5+3+2
are stored one character per byte i.e. each data would occupy the same number of bytes
32667 occupies 5 bytes even though on disks as it occupies in memory. Ans: -
if ([Link]() == True):
it occupies 2 bytes in memory
upper+=1
In the text file, the newline character In binary file, conversion of newline to carriage-
print("Total no. of upper-case alphabets :",upper) for ch in range(0,len(S),3):
is converted to carriage- return and linefeed does not take place.
return/linefeed before being written
uppercount()
to the disk.
When we call the open command, it returns to us a file object or reference to the #=> i v y o
Text files are used to store data Binary files are used to store data more compactly.
file, it is called file handle. def string_length(str1):
more user friendly.
This file handle is used to carry out any subsequent operation on the file like read or count = 0
In the text file, a special character In the binary file no such character is present. Files
write.
whose ASCII value is 26 inserted keep track of the end of the file from the number for char in str1:
after the last character to mark the of characters present. 3. Differentiate between Text file and Binary files? What is standard
count += 1
end of file. input, output and error steams? Write a program to count the words
Write a short note return count
Content written in text files is Content written in binary files is not human
human readable. readable and looks like encrypted content. on flush() function.4+3+5+2 x=str(input())
[Link] a file. What are the different operations we can perform on Text Files Binary Files print(string_length(x))
file? How to open and close file? Also give the Syntax for same. #=>
What are different modes to open a file? 2+3+5+5 Stores in ASCII or Unicode Contains raw data so not human readable
i love python 13
format so human readable
ANS: - A file is a collection of records. A record is a group of related data items. These
data items may contain information related to students, employees, customers, etc. In islower() returns True only if all characters in a string are lowercase.
other words, a fi le is a collection of numbers, symbols and text and can be considered a Each line is delimited by EOL No delimiter for a line
'all lower case'.islower() #=> True
stream of characters. or end of Line (\n).
'not aLL lowercase'.islower() # False
There are three basic operations we can perform on file
Usually with extension .txt and Has app specific extension and needs In python, the string data types are immutable. Which means a string value
Read r mode can be opened in notepad specific app to open like word, excel, jpg cannot be updated. We can verify this by trying to update a part of the string
etc. which will led us to an error.
Write w mode
Append a mode Slower than Binary File Faster than text files 2. Write the function which returns the words of the string given
by user in the reverse order. Define the following function with
The key function for working with files in Python is the open() [Link]
example- i)istitle ii) swapcase. Count all letters, digits, and
open() function takes two parameters; filename, and mode and it returns a
Standard input device(stdin) reads from the keyboard special symbols from a given string. 5+5+5
File Handle.
Standard output device(stdout)- prints to the display and can be redirected as Ans: - string = str(input())
o Syntax:
standard input
s = [Link]()[::-1]
File = open(filename [, mode] [, buffering])
Standard error device(stderr)- Same as stdout but normally only for errors. Having
l = []
[Link]() error output separately allows the user to divert regular output to a file and still be able
to read error messages. for i in s:
o Where, filename is name of the file we want to access
fname = "[Link]" [Link](i)
o mode is a string like
num_words = 0 print(" ".join(l))
for a in words: Python String istitle() Method is a built-in string function that returns True if all
the words in the string are title cased, otherwise returns False
o buffering
string = "Geeks"
0 Means no buffering num_words = num_words + 1
print([Link]())
1 Yes to buffering print("Number of words:", num_words)
#=>true
> 1 considered buffer size [Link]()
Python String swapcase() method converts all uppercase characters to lowercase and
While writing, Python writes everything into a buffer and pushes it into file at a
vice versa of the given string and returns it.
later time. When flush() function is called it immediately empties the buffer and
writes into the file. This function is called automatically when file is closed. string = "iLOVEpythON"
Mode Description 4. Write a function in python to read the content from a text file print([Link]())
t Open in Text Mode (default option) "[Link]" line by line and display the same on screen. Write a string = "ILOVEPYTHON"
2. Differentiate between file modes r+ and w+ with respect to Python. elif [Link]():
print(a)
digit_count += 1
in Python? Write a program to count the number of upper-case alphabets present
[Link]()
What is file handle? 2+2+4+5+2 else:
def read_data():
symbol_count += 1
f = open("[Link]", 'r')
print("Chars =", char_count, "Digits =", digit_count, "Symbol =", symbol_count)
r+ w+ count = 0
str = "P@yn2at&#i5ve"
s = [Link]()
print("total counts of chars, Digits, and symbols \n")
File must exist otherwise File is created if it does not exist. If exists, the data is
error is raised truncated x = [Link]()
find_digits_chars_symbols(str)
for i in x:
#=> total counts of chars, Digits, and symbols
Cannot truncate a file Can truncate a file if it exists
if i == "the":
Chars = 8 Digits = 2 Symbol = 3
count +=1
3. Define dictionary in python. Create and print a dictionary. What are Dict and List comprehensions? What are Literals in Python and For example: 5 // 2 returns 2
Compare between four collection data types available in python. explain about different Literals? Write a Program to calculate the area of a
operator compares the id of the two objects.
Define the following function with example- i)pop() ii) update(). rectangle. How is memory managed in Python? 3+5+3+4
list1=[1,2,3]
3+2+5+5 Ans: Dictionary and list comprehensions are just another concise way to define
dictionaries and lists. Essentially, the only difference between this and the list list2=[1,2,3]
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection comprehension is the use of curly braces to contain the comprehension and the
which is ordered*, changeable and do not allow duplicates. Dictionaries are written placement of x before the colon to indicate that this represents the key. This can be list3=list1
with curly brackets, and have keys and values: then also be used to create a dictionary based on an already existing list.
list1 == list2 - True
thisdict = { A literal in python source code represents a fixed value for primitive data types.
list1 is list2 - False
There are 5 types of literals in python-
"brand": "Ford",
list1 is list3 True
1. String literals A string literal is created by assigning some text enclosed in
"model": "Mustang", single or double quotes to a variable. To create multiline literals, assign the
"year": 1964 multiline text enclosed in triple quotes. Eg.
2. A character literal It is created by assigning a single character enclosed in Q4. How does break, continue and pass work? What is the difference between
} double quotes. Eg. range & xrange? What is pickling and unpickling? What are the generators in
3. Numeric literals include numeric values that can be either integer, floating point python? -allocated?
print(thisdict) value, or a complex number. Eg. a=50
4. Boolean literals These can be 2 values- either True or False. 3+3+3+1+2+3
#=> {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} 5. Literal Collections These are of 4 types-
There are four collection data types in the Python programming language: a) List collections-Eg. Break - Allows loop termination when some condition is met and the control is
b) Tuple literals- Eg. a=(5,6,7,8) transferred to the next statement.
List is a collection which is ordered and changeable. Allows duplicate members. c) Dictionary literals- Eg.
d) Set literals- Eg. Continue - Allows skipping some part of a loop when some specific condition is met
Tuple is a collection which is ordered and unchangeable. Allows duplicate members. 6. Special literal- Python has 1 special literal None which is used to return a null and the control is transferred to the beginning of the loop
variable.
Set is a collection which is unordered, unchangeable, and unindexed. No duplicate Algorithm to Calculate the Area of a Rectangle Pass work - Used when you need some block of code syntactically, but you want to skip
members. A. Get the length and breadth of the rectangle from the user. its execution. This is basically a null operation. Nothing happens when this is executed.
B. Use the relevant formula to calculate the area
Dictionary is a collection which is ordered and changeable. No duplicate members. For the most part, xrange and range are the exact same in terms of functionality.
Area = Length * Breadth
The pop() method removes the item with the specified key name. C. Finally display the area of the rectangle. They both provide a way to generate a list of integers for you to use, however you
This algorithm can be written as code as shown in program please. The only difference is that range returns a Python list object and x range
thisdict = { returns an xrange object.
Length = 10
"brand": "Ford", Breadth = 20 This -time like range does.
It creates the values as you need them with a special technique called yielding. This
"model": "Mustang", area = length * breadth technique is used with a type of object known as generators. That means that if you have
"year": 1964 function to use.
} Memory is managed in Python in the following ways:
Pickle module accepts any Python object and converts it into a string
[Link]("model") 1. Memory management in python is managed by Python private heap space. All representation and dumps it into a file by using dump function, this process is
Python objects and data structures are located in a private heap. The programmer called pickling. While the process of retrieving original Python objects from the
print(thisdict) does not have access to this private heap. The python interpreter takes care of this stored string representation is called unpickling.
instead. Functions that return an iterable set of items are called generators.
#=> {'brand': 'Ford', 'year': 1964} 2. 1. Whenever Python exits, especially those Python modules which are having circular
manager. The core API gives access to some tools for the programmer to code. references to other objects or the objects that are referenced from the global
The update() method will update the dictionary with the items from a given argument. 3. Python also has an inbuilt garbage collector, which recycles all the unused memory namespaces are not always de-allocated or freed.
If the item does not exist, the item will be added. and so that it can be made available to the heap space. 2. It is impossible to de-allocate those portions of memory that are reserved by the C
library.
The argument must be a dictionary, or an iterable object with key:value pairs. Q2. What is namespace in Python? What is PYTHONPATH? What are 3. On exit, because of having its own efficient clean up mechanism, Python would try
thisdict = { python modules? Name some commonly used built-in modules in Python? to de-allocate/destroy every other object.
What are local variables and global variables in Python? Is python case
"brand": "Ford", sensitive? What is type conversion in Python? 1+2+2+3+4+1+2
"model": "Mustang", split()
A namespace is a naming system used to make sure that names are unique to avoid
sub() finds all substrings where the regex pattern matches and then replace them
naming conflicts.
"year": 1964 with a different string
It is an environment variable which is used when a module is imported. Whenever
subn() it is similar to sub() and also returns the new string along with the no. of
} a module is imported, PYTHONPATH is also looked up to check for the presence of
replacements.
the imported modules in various directories. The interpreter uses it to determine
[Link]({"color": "red"}) which module to load.
What is python class? Define Python Class. What is attributes and methods in
Python modules are files containing Python code. This code can either be functions
print(thisdict) classes or variables. A Python module is a .py file containing executable code. class. 3+3+9
Some of the commonly used built-in modules are: A class is considered as a blueprint of objects. We can think of the class as a sketch
#=> {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
os (prototype) of a house. It contains all the details about the floors, doors, windows,
4. Write down the function of given methods- i)isalnum() ii)title() sys etc. Based on these descriptions we build the house. House is the object. Since
iii)endswith() iv)count() v)find() vi) index() vii) upper() . What is a math
Module in Python? What is a Package in Python? Write down random many houses can be made from the same description, we can create many objects
difference between module and package in Python. 7+2+2+4 data time from a class.
JSON
We use the class keyword to create a class in Python. For example,
Ans: - i) isalnum() - Returns True if all characters in the string are alphanumeric
Global Variables : Variables declared outside a function or in global space are class ClassName:
ii) title() - Converts the first character of each word to upper case called global variables. These variables can be accessed by any function in the
program. Here, we have created a class named ClassName.
iii)endswith() - Returns true if the string ends with the specified value Local Variables : Any variable declared inside a function is known as a local Let's see an example,
variable. This variable is present in the local space and not in the global space.
iv) count() - Returns the number of times a specified value occurs in a string Yes. Python is a case sensitive language. class Bike:
v) find() - Searches the string for a specified value and returns the position of where it Type conversion refers to the conversion of one data type into another. name = ""
was found int() converts any data type into integer type gear = 0
vi) index() - Searches the string for a specified value and returns the position of where float() converts any data type into float type Here,
it was found Bike - the name of the class
ord() converts characters into integer
vii) upper() - Converts a string into upper case name/gear - variables inside the class with default values "" and 0 respectively.
hex() converts integers to hexadecimal
In Python, a module is a single file containing Python definitions and statements. A class by itself is of no use unless there is some functionality associated with
These definitions and statements can include variables, functions, and classes and oct() converts integer to octal it. Functionalities are defined by setting attributes, which act as containers for
can be used to organize related functionality into a single, reusable package.
tuple() This function is used to convert to a tuple. data and functions related to those attributes. Those functions are called
Module organizes and reuses code in Python by grouping related code into a
single file. methods.
set() This function returns the type after converting to set.
Modules can be imported and used in other python files using the import statement. list() This function is used to convert any data type to a list type. Attributes:
Some popular modules in python are math, random, csv, and datetime. dict() This function is used to convert a tuple of order (key, value) into a dictionary. You can define the following class with the name Snake. This class will have an
Python Packages are collections of modules that provide a set of related str() Used to convert integer into a string. attribute name.
functionalities, and these modules are organized in a directory hierarchy. In
simple terms, packages in Python are a way of organizing related modules in a complex(real,imag) This function converts real numbers to complex(real,imag) >>> class Snake:
single namespace. number.
... name = "python"
Packages in Python are installed using a package manager like pip (a tool for installing
3. What is the Difference Between a Shallow Copy and Deep Copy?How is
and managing python packages). You can assign the class to a variable. This is called object instantiation. You will then
Memory managed in Python? How Would You Generate Random Numbers in
Each python package must contain a file named _init_.py. Python? What Does the // Operator Do? be able to access the attributes that are present inside the class using the dot .
operator. For example, in the Snake example, you can access the attribute name of the
Parameter Module Package
Deep copy creates a different object and populates it with the child objects of the class Snake.
Definition It can be a simple A Package is a collection of different original object. Therefore, changes in the original object are not reflected in the
python file (.py modules with an _init_.py file. copy. [Link]() creates a Deep Copy. >>> snake = Snake()
extensions) that
contains collections of >>> print([Link])
Shallow copy creates a different object and populates it with the references of the child
functions and global objects within the original object. Therefore, changes in the original object are reflected
variables. python
in the copy. [Link] creates a Shallow Copy.
Purpose Code organization Code distribution and reuse Methods
Python has a private heap space that stores all the objects. The Python memory
Organization Code within a single Related modules in a directory
manager regulates various aspects of this heap, such as sharing, caching,
file hierarchy
segmentation, and allocation. The user has no control over the heap; only the access the class attribute. These functions are called methods. When you define
Sub-modules None Multiple sub-modules and sub- Python interpreter has access.
methods, you will need to always provide the first argument to the method with a self
packages
To generate random numbers in Python, you must first import the random keyword.
Required Files Only Python File(.py module.
format) For example, you can define a class Snake, which has one attribute name and one
The random() function generates a random float value between 0 & 1.
How to import import module_name import package_name.module_name method change_name. The method change name will take in an argument new_name
> [Link]() along with the keyword self.
Example math, random, os, Numpy, Pandas, Matplotlib, django
datetime, csv The randrange() function generates a random number within a given range.
>>> class Snake:
Syntax: randrange(beginning, end, step)
... name = "python"
Example - > [Link](1,10,2)
... def change_name(self, new_name): # note that the first argument is self
In Python, the / operator performs division and returns the quotient in the float.
For example: 5 / 2 returns 2.5 ... [Link] = new_name # access the class attribute with the self keyword
50.24 Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
(i) Identifiers,
class Rectangle: (ii) Keywords,
def __init__(self, length, breadth): (iii) Operators,
[Link] = length (iv) Delimiters and
[Link] = breadth (v) Literals.
def display(self): (i) Identifiers :
Describe in detail the procedure Script mode programming. Write a program to The function prototype is as follows:
calculate the salary of a medical representative considering the sales bonus and
def function_name(*list)
incentives offered to him are based on the total sales. If the sales exceed or equal
to `1,00,000 follow the particulars of Column 1, else follow Column 2. 5+10 >>def fun(*var):
print(i)
>>fun(1)
A script is a text file containing the Python statements. Python Scripts are reusable code. >>fun(1,25,6)
Once the script is created, it can be executed again and again without retyping. The In the above code, * indicates that there are multiple arguments of a variable.
Scripts are editable.
Creating Scripts in Python: __name__ is a special variable that holds the name of the current module. Program
execution starts from main or code with 0 indentations. Thus, __name__ has a value
__main__ in the above case. If the file is imported from another module, __name__ holds
A - A script is a text frame
the name of this module.
R - Text file contain Python script
(1) All text file does not Python scripts
num=1
(2) All text file must contain Python script x=num
(3) A is T B for i in range(1,6,1):
num=num+1;
(ii) An untitled blank script text editor will be displayed on screen.
for j in range(1,num,1):
(iii) Type the code in Script editor print(
x=num+1
Saving python script:
print()
(i) Choose or press Ctrl+S
(ii) Now, Save As dialog box appears on the screen. Output
(iii) In the Save As dialog box, select the location where you want to save your Python Star Pattern Display
code, and type the file name in File Name box. Python files are by default saved with *
extension .py. Thus, while creating Python scripts using Python Script editor, no need **
to specify the file extension. ***
****
(iv) Finally, click Save button to save your Python script. *****
Executing Python Script: End of Program
(i) Choose or press F5
To Execute Python Script
(ii) If code has any error, it will be shown in red color in the IDLE window," and
Python describes the type of error occurred. To correct the errors, go back to
Script editor, make corrections, save the file using Ctrl + S or File Save and
execute it again.
(ii) For all error free code, the output will appear in the IDLE window of Python.