LINUX KURIOSITY
Python-I
Learn in a Simple and Smart way
1
Table of contents
1. Introduction---------------------------------------------------------------------------------4-5
a. Objective
b. Benefits
c. Problems
2. Python Environment Setup----------------------------------------------------------------6
a. Objective
b. Benefits
c. Problems
3. Python Programming Syntax--------------------------------------------------------------7
a. Objective
b. Benefits
c. Problems
4. Variables--------------------------------------------------------------------------------------8-9
a. Objective
b. Benefits
c. Problems
5. Numbers---------------------------------------------------------------------------------------10
a. Objective
b. Benefits
c. Problems
6. Control flow tools----------------------------------------------------------------------------11-13
a. Objective
b. Benefits
c. Problems
7. Data structures--------------------------------------------------------------------------------14-17
a. Objective
b. Benefits
c. Problems
8. Modules----------------------------------------------------------------------------------------18-19
a. Objective
b. Benefits
c. Problems
9. Input and Output------------------------------------------------------------------------------20-21
a. Objective
b. Benefits
c. Problems
2
10. Error and Exception-------------------------------------------------------------------------22
a. Objective
b. Benefits
c. Problems
11. Standard Library-----------------------------------------------------------------------------23-26
a. Objective
b. Benefits
c. Problems
3
1. Introduction
Objective: Below problems help you to understand various features of python
Benefits: 1. Using python we can interact with all commercial databases
2. Able to integrate with all the programming language like c, c++ and java.
1. Is it true before executing the python program we need to compile it?
Ans: No, python program can run without doing compile.
2. Is it possible to run the python program on multiple platforms like Macintosh?
Ans: Yes
3. In terms of what python is better than shell scripting?
Ans: 1. Better Structure
2. Support for large programs
3. Support GUI Applications
4. Add modules to increase the features
4. Is it true python is an ideal language for scripting and rapid application development?
Ans: Yes, because of Python's elegant syntax and dynamic typing.
6. Is it true python is easily extended with new functions and data types implemented in c or
c+ +?
Ans: Yes
7. Where is python interpreter# usually installed?
Ans: /usr/local/bin/python3.5
8. How to invoke module in python?
Ans: Command: python -m module-name
9. In python, Is it possible to run the script in interactive mode?
Ans: Yes using option i
10 Is it possible to run the argument in the command?
Ans: Yes
Command: python -c command [arg]
4
11. By default python source files are encoded in which format?
Ans: UTF-8
12. Why is python 3.x interpreter not conflict with the simultaneously installed python 2.x?
Ans: By default, python3.x is not installed with executable named python.
13. What is the use of parentheses?
Ans: parentheses can be used for grouping.
5
2. Python Environment Setup
Objective: Below problems help you to setup the python environment.
Benefits: 1. Able to extract the source code file.
2. Able to setup the path from where python fetches the code.
3. Able to run the python script
4. Able to debug the script.
1. How to install python in the linux environment?
Ans: a. Download Source code
b. Extract it using unzip or tar
c. Run ./configure script
d. Run make
e. Run make install
2. How to setup the path from where python fetch the code?
Ans: export PATH=”$PATH:/usr/local/bin/python”
3. How to run and debug the python script?
Ans: python script-name
or
python -d scriptname
6
3. Python Programming Syntax
Objective: Below problems help you to understand about the syntax of Python
Benefits: 1. Able to differentiate between Interactive mode and Script mode.
2. Know about the location of the python libraries.
3. Know about the line continuation character.
4. Know about when to use single quote , double quote and triple quote.
5. Know about how to use multiple statement on a single line.
6. Able to use help option
1. What is the difference between interactive mode and script mode ?
Ans: Interactive mode : We can write code without using script file
Scripting mode : We can write code using script file.
2. What is the location of the python libraries ?
Ans: Location : #!/usr/bin/python
3. What is the use of line continuation character?
Ans: Line continuation character helps us to write in multiple lines without termination.
Denoted by (\).
4. What is the use of single quote , double and triple quote in python ?
Ans: Single quote : word
Double quote : two words
Triple quote : multiple lines
5. How to use multiple statement on a single line ?
Ans: Using ; (semicolon)
6. How to use help option ?
Ans: python -h
7
4. Variables
Objectives: Below problems help you to understand the concept of variables
Benefits: 1. Able to understand the difference between array and list.
2. Able to assign the same value simultaneously to multiple variables.
1. What are variables?
Ans: Reserved memory location to store values.
2. Is it necessary to declare the variable explicitly?
Ans: No, it is not necessary to declare the variable.
3. Is it possible to assign same value simultaneously to the multiple variables?
Ans: Yes
4. How many types of python data types?
Ans: There are fives python data-types:
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
5. Is it possible to delete the single or multiple objects?
Ans: Yes, it is possible to delete the single or multiple objects using del statement.
Syntax : del variable-name
6. How to declare string and int variable?
Ans: Int variable :
var1 = 1
String variable:
str = 'Hello World!'
print str # print complete string
7. What is the difference between list and array? How to declare the list?
Ans: List: In case of the list we can assign the different data types values.
8
Syntax:
list = [ 'abcd' , 786 , 2.23 , 'john' ]
Array: In case of the array we can only assign same data types value.
8. What is the difference between list and tuple? How to declare tuple?
Ans: In case of list values are enclosed in brackets and their elements & size can be changed.
Whereas in case of tuple values are enclosed in parenthesis and their element cannot be changed.
Syntax :
tuple = ( 'abcd' , 786 , 2.23 , 'john' , 70.2 )
9. How to declare the python dictionary? How to assign values and access?
Ans: Syntax :
tinydict = { 'name' : 'john', 'code':6734 }
Values can be assigned and accessed using square braces [].
dict[2] = “this is two”
Print dict[2] # print value for 2 key.
9
5. Numbers
Objective: Below problems help you to use number data types.
Benefits: 1. Able to use different types of number values.
1. In python Is it possible to use the ** operator to calculate the powers?
Ans: Yes
Example :
>>> 5 ** 2
2. What is the use of = (equal sign)?
Ans: Assign a value to a variable
3. Is it true operators with mixed type operands convert the integer operand to floating type?
Ans: Yes
Example :
>>> 4 * 3.75 -1
14.0
4. Is it true python also has built-in support for complex numbers?
Ans: True
5. How to discard fractional result?
Ans: Use // operator
Example :
>>> 17 // 3
10
6. Control flow tools
Objective: Below problems help you to understand the functions and control flow tools
Benefits:1. Able to use the range function
1. How to avoid excessive indentation in elif statement?
Ans: Using keyword elif
2. Suppose if you don't want to iterate over a sequence of numbers then which function will
you use?
Ans: range () function
3. Is it true the object returned by the range() function behaves as if it is a list?
Ans: No
4. What is the use of the break statement?
Ans: Break statement break out of the innermost enclosing.
5. What is the use of the continue statement?
Ans: Continue statement continues with the next iteration of the loop.
6. When can pass statement be used?
Ans: When a program requires no action.
7. How to define functions?
Ans: Syntax : def function-name (list of parameters):
8. What is the use of symbol table in the function?
Ans: Used for the local variables of the function.
9. In function where all the variables value get stored?
Ans: Symbol Table
10. Where variable reference first look?
11
Ans: 1. First look at the Local symbol table.
2. In the local symbol tables of enclosing functions.
3. In the global symbol table
4. Built-in names
11. Is it true global variables cannot be directly assigned a value within a function, although
they may be referenced?
Ans: True
12. Is it true when a function calls another function, a new symbol table is created?
Ans: True
13. Is it true functions without a return statement do return a value ?if yes, then what it is
called?
Ans: True, None (built-in name).
14. What is a method?
Ans: A method is a function that belongs to an object.
15. Is it true different object type define different methods?
Ans: True
16. Is it possible to define functions with a variable number of assignments?
Ans: True
17. In how many ways the function can be called?
Ans: 1. Giving mandatory arguments
2. Optional arguments
3. Passing all arguments
18. Is it true in a function default value is evaluated only once?
Ans: True
19. Is it possible to call the function using keyword arguments?
Ans: True
12
20. Is it true keyword arguments are printed to match the order in which they were provided
in the function call?
Ans: True
21. How to unpack the arguments out of a list or tuple?
Ans: Using *-operator
22. Is it true lambda function are syntactically restricted to a single expression ?
Ans: True
23. What is function annotations ?
Ans: Function annotations are completely optional metadata information about the types used by
user-defined functions.
24. Where functions annotations are stored ?
Ans: Annotations are stored in the _annotations_ attribute of the function as a dictionary and have
no effect on any other part of the function.
25. How to define parameter annotations ?
Ans: parameter annotations are defined by a colon after the parameter name, followed by an
expression evaluating to the value of the annotations.
13
7. Data Structures
Objective: Below problems help you to understand the data structures of the python.
Benefits: 1. Able to use the different types of list method.
2. Able to use del statement.
1. Suppose if you want to add an item at the end of the list. How will you add?
Ans: Using the method
list.append(x)
2. Suppose if you want to extend the list. How will you extend?
Ans: Using the method
list.extend(iterable)
3. Suppose if you want to insert the item at a given position. How will you insert?
Ans: Using the method
list.insert(i,x)
The first argument is the index of the element before which to insert.
4. Suppose if you want to remove the item from the list whose value is x. How will you
remove?
Ans: Using the method:
list.remove(x)
5. Suppose if you want to remove the item at a given position from the list and return it.How
will you do?
Ans: Using the method:
list.pop([i])
6. Suppose if you want to remove all the items from the list. How will you do?
Ans: Using the method:
list.clear()
7. Suppose if you want to count the item in the list. How will you do?
Ans: Using the method:
14
list.count(x)
8. Suppose if you want to reverse the elements of the list. How will you do?
Ans: Using the method:
list.reverse()
9.In the list, how to add an item to the top of the stack?
Ans: Use append()
10. In the list, how to retrieve an item from the top of the stack?
Ans: Use pop()
11. To implement a queue, use collection.deque which was designed to have fast appends and
pops from both ends.True or False?
Ans: True
12. List comprehensions provide a concise way to create lists. True or False?
Ans: True
13. List comprehensions can contain complex expressions and nested functions. True or
Fasle ?
Ans: True
14. del can also be used to delete entire variables.True or False ?
Ans: True
Example: >>> del a[:]
>>>a
15. The del statement can also be used to remove slices from a list or clear the entire list.True
or False?
Ans: True
16. List and string have many common properties, such as indexing and slicing
operations.True or False?
Ans: True
17. Tuples are immutable and usually contain a hetergeneous sequence of elements.True or
False ?
15
Ans: True
18. List are mutable and their elements are usually homogeneous and are accessed by
iterating over the list. True or False?
Ans: True
19. A set is an unordered collection with no duplicate elements. True or False?
Ans: True
20. What are the basic uses of sets?
Ans: The basic uses are :
1. Membership testing
2. Eliminating duplicate entries.
Example: >>> basket = {'apple','orange','apple'}
>>>print(basket)
{''orange'} (removed duplicate element)
>>> 'orange' in basket (memebership testing )
True
21. Curly braces or the set() function can be used to create sets. True or False ?
Ans: True
22. The main operation on a dictionary is storing a value with some key and extracting the
value given the key. True or False?
Ans: True
23. How to check whether a single key is in the dictionary or not?
Ans: use the in keyword
24. When looping through dictionaries, the key and corresponding value can be retrieved at
the same time using the items() method. True or false?
Ans: True
Example: >>> knights = {'Magic': 'the pure' }
>>> for k,v in knights.items():
print (k.v)
25. When looping through a sequence, the position index and corresponding value can be
retrieved at the same time using the enumerate() function. True or False?
Ans: True
16
Example : >>>for i,v in enumerate(['a', 'b' , 'c'])
.... print(i,v)
0a
1b
2c
26. To loop over two or more sequences at the same time the entries can be paired with the
zip() function. True or False?
Ans: True
>>> questions = ['name']
>>>answers = ['lancelot']
>>> for q, a in zip(questions, answers):
... print('what is your {0}?'.format(q,a))
27. To loop over a sequence in reverse, first, specify the sequence in a forward direction and
then call the reversed() function.True or False?
Ans: True
>>> for i in reversed (range(1, 10)):
... print (i)
28. To loop over a sequence in sorted order, use the sorted () function which returns a new
sorted list while leaving the source unaltered. True or False?
Ans: True
Example:
>>> basket = ['apple', 'orange' , 'apple']
>>> for f in sorted(set(basket)):
...... print(f)
17
8. Modules
Objective: Below problems help you to understand the modules.
Benefits: 1. Know about the different features of the module.
1. If you quit from the python interpreter and enter it again, the definitions you have made
(functions and variables) are lost.True or False?
Ans: True
2. Python has a way to put definitions in a file and use them in a script, False ?such a file is
called a module. True or false?
Ans: True
3. A module can contain executable definitions as well as function definitions. True or False?
Ans: True
4. For efficiency reasons, each module is only imported once per interpreter session.True or
False?
Ans: True
5. If you change your modules, you must restart the interpreter. True or False?
Ans: True
6. What is the use of the importlib.reload()?
Ans: To test one module interactively.
7. To speed up loading modules, python caches the compiled version of each version in the
pycache directory under the name module.version.pyc.True or False?
Ans: True
8. What are the two circumstances when python does not check the cache?
Ans: 1. It always recompiles and does not store the result for the module that's loaded directly from
the command line.
2. It does not check the cache if there is no source module.
9. What are the two switches on the python command to reduce the size of a compiled
module?
Ans: 1. - 0: removes assert statements
18
2. -00: remove both assert statements and doc strings.
10. The module compileall can create .pyc files for all modules in a directory.True or False ?
Ans: True
11. Which function returns a sorted list of strings?
Ans: dir()
12. dir() does not list the names of built-in functions and variables.True or False ?
Ans: True
13. Packages are a way structuring python's module namespace by using “dotted modules
names”.True or False.
Ans: True
19
9. Input and Output
Objective: Below problems help you to understand the different types of functions.
Benefits:1. Able to open the file in write mode.
1. How to convert any value into a string?
Ans: Using : repr() and str() functions
Example:
>>> s = 'Hello World'
>>>repr(s)
“'Hello,world.'”
>>>str(s)
“'Hello, world.'”
2. How to add the zeroes on the left of the string?
Ans: Using str.zfill()
Example:
>>> '12' .zfill(5)
3. How to use str.format() method ?
Ans: Open python interpreter
>>> print(' {0} and {1}'. format('spam' , 'eggs'))
spam and eggs
>>>print('{1} and {0}'.format('spam','eggs'))
eggs and spam
4.The % operator can also be used for string formatting.True or False?
Ans: True
Example:
>>>import math
>>>print('The value of PI is approximately %5.3f.' % math.pi)
5.How to open a file in write mode?
Ans:
>>> f = open('workfile' , 'w' )
6. What is the advantage of using the with keyword when dealing with file objects ?
20
Ans: File is properly closed after its suite finishes, even if an exception is raised at some point.
Example:
>>>with open('workfile') as f:
... read_data = f.read()
>>>f.closed
True
7. How to read a file contents ?
Ans: Use below mentioned method:
>>> f.read()
8. How to read a single line from the file ?
Ans: Use below mentioned method:
>>>f.readline()
21
10. Errors and Exception:
Objective: Below problems help you to understand the Error and Exception.
Benefits:1. Able to use the keyword.
1. What are the two kinds of errors?
Ans: Syntax errors and exceptions
2.Syntax errors are also known as parsing errors.True or False.
Ans: True
3. Errors detected during execution are called exceptions. True or False
Ans: True.
4. A try statement may have more than one except clause, to specify handlers for different
exceptions.True or False
Ans: True
5. The raise statement allows the programmer to force a specified exception to occur.True or
False.
Ans: True.
6. A finally clause is always executed before leaving the try statement, whether an exception
has occurred or not.True or False
Ans: True
7. Where is finally clause useful?
Ans: Releasing external resources (such as files or network connections).
8. What is the advantage of the with the statement?
Ans: The with statement allows objects like files to be used in a way that ensures they are always
cleaned up promptly and correctly.
22
11. Standard Library
Objective: Below problems help you to understand the different types of modules.
Benefits: 1. Able to import different types of modules
1. What is OS module Provides?
Ans: It provides dozens of functions for interacting with the operating system.
2. How to know the current working directory using os module?
Ans: Step 1: Login to Python Interpreter
Command: python3.6
Step 2: Import os module
Command: import os
Step 3: Return the current working directory
Command: os.getcwd()
3. How to change the current working directory?
Ans: >>> os.chdir('/server/accesslogs')
4. How to create a directory using os module?
Ans: >>>os.system('mkdir today')
5. How to get a list of all module functions?
Ans: >>>dir(os)
6.For daily file and directory management task, which module is used?
Ans: >>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db
>>> shutil.move('/build/executables', 'installdir')
7. Which module provides a function for making file lists from directory wildcard searches?
Ans: glob module
Example : >>>import glob
23
>>> glob.glob('*.py')
['primes.py', 'random.py','quote.py']
8. Which is the most powerful and flexible command line processing module?
Ans: argparse module
9. Which module processes sys.argv using the conventions of the Unix getopt() function?
Ans: getopt module
10. How to import sys module?
Ans: >>> import sys
>>>print(sys.argv)
11. The sys module also has attributes for stdin, stdout, and stderr.True or False?Please give
an example.
Ans: True
Example: >>>sys.stderr.write('warning, log file not found starting a new one\n')
12. Which is the most direct way to exit ()?
Ans: sys.exit()
13. Which module provides regular expression tools advanced string processing?
Ans: re module
>>> 'tea for too' .replace('too', 'two')
'tea for two'
14. Which module gives access to the underlying C library functions for floating point math?
Ans: math module
>>> import math
>>> math.cos(math.pi /4)
0.707106
>>>math.log(1024, 2)
10.0
15. Which module provides tools for making random selections?
Ans: random module
>>>import random
>>>random.choice(['apple', 'pear' , 'banana'])
24
>>>random.randrange(6)
4
16. Which module calculates basic statistical properties of numeric data?
Ans: statistics
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25 , 0.5 , 1.25 , 3.25]
>>> statistics.mean(data)
>>>statistics.median(data)
>>>statistics.variance(data)
17. What are the two modules which provide access the internet and processing internet
protocols?
Ans: urllib.request and smtplib
>>> from urllib.request import urlopen
>>>with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
... for line in response:
... line = line.decode('utf-8')
... if 'EST' in line or 'EDT' in line:
... print(line)
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('
[email protected]',
... “””To:
[email protected] ... From:
[email protected] ...Beware
...”””)
>>> server.quit()
18.Which is the module used to supplies classes for manipulating dates and times in both
simple and complex ways?
Ans: datetime module
Example:
>>> from datetime import date
>>> now = date.today()
>>> now
25
>>>birthday = date(1991, 8, 30)
>>>age = now – birthday
>>>age.days
19. What are the common data archiving and compression formats modules?
Ans: zlib,gzip,bz2,lzma,zipfile and tarfile.
Example:
>>> import zlib
>>> s= b'witch which has which witches wrist watch'
>>>len(s)
41
>>> t = zlib.compress(s)
>>>len(t)
37
>>>zlib.decompress(t)
>>>
20. What is the name of the module which quickly demonstrates a modest performance
advantage?
Ans: module name: timeit
21. What is the name of the module which provides a tool for scanning a module and
validating tests embedded in a program's docstrings?
Ans: module name: doctest
26
27