Python Programming Basics Guide
Python Programming Basics Guide
Python is a widely used high-level programming language for general-purpose programming, created by
Guido Van Rossum and first released in 1991. My first program in Python is:
print(“Hello World”)
Python shell can be used in two ways: interactive mode and script mode.
Interactive mode does not save commands in the form of a program. It is used for testing code.
Script mode is useful for creating programs and then trying the programs later and getting complete output.
Python is an interpreted language.
Python is a case-sensitive language.
1. KEYWORDS
Predefined words with special meaning to the language processor; are reserved for special purposes and
must not be used as normal identifier names.
Example - True, for, if, else, elif, from, is, and, or, break, continue, def, import, in, while, False, try, finally,
except, global, etc.
2. IDENTIFIERS
Python Identifier is a name used to identify a variable, function, class, module or other object. The rules for
creating Identifiers :
Start with the alphabet or underscore. Followed by digits or more letters
Python keyword cannot be used as an Identifier.
Identifier should not contain special characters except underscore.
Identifiers are unlimited in length.
Some valid identifiers are: Myfile, MYFILE, Salary2021, _Chk ,First_Number
Invalid Identifies are: [Link], break, 2021salary, if#, First Number
3. LITERALS
Data items that have a fixed value.
String Literals: are sequence of characters surrounded by quotes (single, double or triple)
S1=”Hello” S2=”Hello” S3=”””Hello”””
Python allows nongraphic characters in string values. E.g. \r,\n,,\a,\b,\u,\v
Numerical Literals: are numeric values in decimal/octal/hexadecimal form. D1=10 D2=0o56 (Octal)
D3=0x12 (Hex)
Floating point literals: real numbers and may be written in fractional form (0.45) or exponent form
(0.17E2).
Complex number literal: are of the form a+bJ, where a, b are int/floats and J(or i) represents −1 i.e.
imaginary number. Ex: C1=2+3j
Boolean Literals: It can have value True or False. Ex: b=False
Special Literal None: The None literal is used to indicate absence of value.
Ex: c=None
4. OPERATORS
Tokens that trigger some computation/action when applied to variables and other objects in an expression.
These are
Arithmetic : +, -, *, /, %, **, //
Bitwise : &, ^, |
Identity : is, is not
Relational : >, >=, <, <=,!=, ==
Logical : and, or, not
Assignment : =
Membership : in, not in
Arithmetic assignment: /=, +=, -=, *=, %=, **=, //=
PRECEDENCE OF ARITHMETIC OPERATORS
PE(MD) (AS) = read PEMDAS
P=parenthesis () → E=exponential →M, D = multiplication and division → A, S=addition and subtraction
Ex: 12*(3%4)//2+6 = 24 (Try at your end)
5. PUNCTUATORS
Punctuators are symbols that are used to organize sentence structure. Common punctuators used in
Python are: ‘ “ # \ ( ) [ ] { } @ , : .
DATA TYPES
Means to identify type of data and set of valid operations for it. These are
1. NUMBERS
To store and process different types of numeric data: Integer, Boolean, Floating-point, Complex no.
2. STRING
Can hold any type of known characters i.e. letters, numbers, and special characters, of any known scripted
language. It is immutable datatype means the value can’t be changed at place. Example: “abcd”, “12345”,”This
is India”, “SCHOOL”.
-6 -5 -4 -3 -2 -1
S C H O O L
0 1 2 3 4 5
3. LISTS
Represents a group of comma-separated values of any datatype between square brackets. Examples:
L1=list()
L2=[1, 2, 3, 4, 5]
L3=[5, ‘Neha’, 25, 36, 45]
L4=[45, 67, [34, 78, 87], 98]
In list, the indexes are numbered from 0 to n-1, (n= total number of elements). List also supports forward and
backward traversal. List is mutable datatype (its value can be changed at place).
4. TUPLE
Group of comma-separated values of any data type within parenthesis. Tuple are immutable i.e. non-
changeable; one cannot make change to a tuple.
t1=tuple()
t2=(1, 2, 3, 4, 5)
t3=(34, 56, (52, 87, 34), 67, ‘a’)
5. DICTIONARY
The dictionary is an unordered set of comma separated key:value pairs, within { }, with the requirement that
within a dictionary, no two keys can be the same. Following are some examples of dictionary:
d1=dict()
d2={1:’one’, 2:’two’, 3:’three’}
d3={‘mon’:1, ‘tue’:2, ‘wed’:3}
d4={‘rno’:1, ‘name’:’lakshay’, ‘class’:11}
In dictionary, key is immutable whereas value is mutable.
STRING PROCESSING AND OTHER FUNCTIONS
STRING
In Python, a string literal is a sequence of characters surrounded by quotes.
Python supports single, double and triple quotes for a string
A Character literal is a single character surrounded by single or double quotes.
The value with triple-quote ’’’ ‘’’ is used to give multiline string literal.
Example:
strings = “This is Python”
char = “C”
multiline_str = ‘’’This is multiline string with
more than one line code.’’’
print(strings)
print(char)
print(multiline_str)
STRING REPLICATION
When a string is multiplied by a number, string is replicated that number of times.
Note: Other datatype – list and tuple also show the same behavior when multiplied by an integer number.
>>> STR=’Hi’
>>> print(STR*5)
>>>HiHiHiHiHi
>>> L=[1, 2]
>>> print(L*5)
>>> [1,2,1,2,1,2,1,2,1,2]
>>> t=(1, 2)
>>> print(t*5)
>>> (1,2,1,2,1,2,1,2,1,2)
STRING SLICE
String Slice refers to part of a string containing some contiguous characters from the string. The syntax is
str_variable[start:end:step].
start: from which index number to start
end: upto (end-1) index number characters will be extracted
step: is step value. (optional) By default it is 1
Example : Suppose S='KENDRIYA'
Backward Index no -8 -7 -6 -5 -4 -3 -2 -1
Character K E N D R I Y A
Forward Index no 0 1 2 3 4 5 6 7
CREATING LIST
1) Empty List
>>>L=[] OR >>> L=list()
2) From existing sequence
>>>st=’HELLO’
>>> L1=list(st) # from a string
>>> t=(1, 2, 3)
>>> L2=list(t) # from a tuple
3) from Keyboard entering element one by one
>>> L=[]
>>> for i in range(5):
n=int(input(‘Enter a number :’))
[Link](n)
TRAVERSING A LIST
>>> L=[1, 2, 3, 4, 5]
>>> for n in L:
print(n)
JOINING LISTS
>>> L1=[1, 2, 3]
>>> L2=[33, 44, 55]
>>> L1 + L2 # output: [1, 2, 3, 33, 44, 55]
APPENDING ELEMENT
>>> L=[10, 11, 12]
>>>[Link](20) # Will append 20 at last
>>> L # output : [10, 11, 12, 20]
>>>[Link]([4,5])
# Appended data will be treated as a single element
>>> L # output: [10, 11, 12, 20, [4, 5]]
EXPANDING LIST
>>> L=[10, 11, 12]
>>>[Link]([44,55])
# Will extend given item as separate elements
>>> L # output: [10, 11, 12, 44, 55]
UPDATING LIST
>>> L=[10, 11, 12]
# Suppose we want to change 11 to 50
>>> L[1]=50
>>> L # output: [10, 50, 12]
DELETING ELEMENTS
del List[index]# Will delete the item at given index del List[start : end]# Will delete from index no start to (end-
1)
>>> L=[x for x in range(1,11)]
>>> L # list is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del L[2:5]
>>> L # now list is [1, 2, 6, 7, 8, 9, 10]
TUPLES
The Tuples are depicted through parenthesis or Tuples are sequence of elements enclosed within parenthesis.
Tuples are immutable sequences i.e., you cannot change elements of a tuple in a place
T=()
T=(value,…)
Traversing a Tuple
T=(‘s’,’c’,’h’,’o’,’o’,’l’)
for a in T:
print(T)
The above loop will produce output as
s
c
h
o
o
l
Joining Tuples
The + operator, the concatenation operator, when used with two tuples, joins two tuples.
>>>T1=(10,20,30)
>>>T2 =(50,60,70)
>>>T1+T2
(10,20,30,50,60,70)
DICTIONARY
Dictionaries are a collection of some unordered key:value pairs; are indexed by keys (keys must be of any non-
mutable type). Dictionaries are mutable, unordered collections with elements.
<dictionary-name> = {<key>:<value>,<key>:<value>…}
TRAVERSING A DICTIONARY
>>> d={1:’one’, 2:’two’, 3:’three’}
>>> for key in d:
print(key, “:”, d[key], sep=’\t’)
1 : one 2 : two 3 : three
OTHER FUNCTIONS
Here is a list of functions to recall them which work on dictionaries.
pop(key), len(), values(), items(), keys(), update()
MCQ
[Link] developed Python?
(A)Ritche (B) Guido Van Rossum (C)Bill Gates (D) Sunder Pitchai
[Link] symbol is used to print more than one item on a single line.
(A)Semicolon(;) (B) Dollor($) (C)comma(,) (D) Colon(:)
[Link] Python, the script mode programs can be stored with the extension.
a) .pyt b) .py c) .pyh d) .pon
18. Python uses the symbols and symbol combinations as _____ in expressions
a) literals b) keywords c) delimiters d) identifiers
29. A loop place within another loop is called as ____________ loop structure
a) entry check b) exit check c) conditional d) nested
30. Which statement is used to skip the remaining part of a loop and start with next iteration?
a) condition b) continue c) break d) pass
33. Which of the following function is used to count the number of elements in a list?
(a)count() (b)find () (c)len() (d)index()
36. Which of the following Python function can be used to add more than one element within an existing
list?
(a)append() (b)append_more (c)extend() (d)more()
42. Which of the following is used to delete known elements where the index value is known?
(a)del (b)delete (c)remove() (d)del()
43. Which function is used to convert the result of range() function into list?
(a)convert() (b)range() (c)list() (d)listrange()
46. While creating a tuple from a list, the element should been closed within
(a)[] (b)() (c){} (d)[()]
48. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau (c) udanlimaT (d) udaNlimaT
55. Which of the following formatting character is used to print exponential notation in upper case?
(a) %e (b) %E (c) %g (d) %n
56. Which of the following is used as placeholders or replacement fields which get replaced along with format(
) function?
(a) { } (b) <> (c) ++ (d) ^^
62. Which function returns the number of sub strings occurs within the given range?
a) count() b) range() c) return() d) format()
1. Assertion. Assigning a new value to an int variable creates a new variable internally.
Reason. The int type is immutable data type of Python.
2. Assertion. """"A Sample Python String"""" is a valid Python String.
Reason. Triple Quotation marks are not valid in Python.
3. Assertion. If and For are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in
lower case.
4. Assertion. if and for are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in
lower case.
5. Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement is of no use unless the if statement is part of a looping
construct.
6. Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement will give no error.
7. Assertion. Lists and Tuples are similar sequence types of Python, yet they are two different
datatypes.
Reason. List sequences are mutable and Tuple sequences are immutable.
8. Assertion. Modifying a string creates another string internally but modifying a list does not create
a new list.
Reason. Strings store characters while lists can store any type of data.
9. Assertion. Modifying a string creates another string internally but modifying a list does not create
a new list.
Reason. Strings are immutable types while lists are mutable types of Python.
10. Assertion. Dictionaries are mutable, hence its keys can be easily changed.
Reason. Mutability means a value can be changed in place without having to create new
storage for the changed value.
11. Assertion. Dictionaries are mutable but their keys are immutable.
Reason. The values of a dictionary can change but keys of dictionary cannot be changed
because through them data is hashed.
12. Assertion. In Insertion Sort, a part of the array is always sorted.
Reason. In insertion sort, each successive element is picked and inserted at an appropriate
position in the sorted part of the array.
13. Assertion: The documentation for a Python module should be written in triple-quoted strings.
Reason: The docstrings are triple-quoted strings in Python that are documentation when help
<module> command is issued.
14. Assertion: After importing a module through import statement, all its function definitions,
variables, constants etc. are made available in the program.
Reason: Imported module's definitions do not become part of the program's namespace if
imported through an import <module> statement.
15. Assertion: If an item is imported through from <module> import <item> statement then you do
not use the module name along with the imported item.
Reason: The from <module> import command modifies the namespace of the program and
adds the imported item to it.
16. Assertion: Python's built-in functions, which are part of the standard Python library, can directly
be used without specifying their module name.
Reason: Python's standard library's built-in functions are made available by default in the
namespace of a program.
17. Assertion: Python standard library consists of number of modules.
Reasoning: A function in a module is used to simplify the code and avoids repetition.
18. Assertion: Python offers two statements to import items into the current program : import and
from<module>import, which work identically.
Reason. Both import and from <module> import bring the imported items into the current
program.
Answers
1. a 2. c 3. d 4. a 5. a 6. b 7. a 8. c 9. a 10. d 11. a 12. a 13. A
14. b 15. a 16.a 17.b 18.e
2. Given the lists L=[1, 3, 6, 82, 5, 7, 11, 92], write the output of print(L[2:5]).
Ans: [6,82,5], as it will start from index no 2 to (5-1) i.e. 4.
12. Name tython Library modules which need to be imported to invoke the following functions:
(a) ceil() (b) randrange()
Ans : (a) math (b) random
14. STR=”VIBGYOR”
colors=list(STR) >>>del colors[4]
>>>[Link]("B")
>>>[Link](3)
>>>print(colors)
Ans : It will create a list as colors=['V', 'I', 'B', 'G', 'Y', 'O', 'R']. del colors[4] will delete the element at index
no 4 i.e. so list will be ['V', 'I', 'B', 'G', 'O', 'R']. [Link]("B") will remove ‘B’. so list will be ['V', 'I', 'G',
'O', 'R']. [Link](3) will extract ‘O’. So finally colors will be ['V', 'I', 'G', 'R'].
17. Write a function LShift(Arr,n), which accepts a list Arr of numbers and n is a numeric value by which all
elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output:
Arr = [30,40,12,11,10,20]
21. What are the assignment operators that can be used in Python?
In Python, = is a simple assignment operator to assign values to variable.
There are various compound operators in Python like +=, -=, *=, /=, **= and //= are also available.
Let us consider a=5 i.e. the value 5 from right side is assigned to the variable a to the left side
Assume a+=5 i.e. the value 5 is added to the operand a and assign back the result to the left operand
a itself (a=a+5)
Example:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elifavg>=60 and avg<70:
print (“Grade : C”)
elifavg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)
Output:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
38. Explain while loop with example.
While loop belongs to entry check loop type, that is it not executed even once if the condition is tested False
in the beginning.
SYNTAX
While <condition>:
statements block 1
[else:
statements block2]
In while loop, the condition is any valid Boolean expression returning True or False
The else part of while is optional part of while. The statement block1 is kept executed till the condition is True
If the else part is written, it is executed when the condition is tested false
EXAMPLE
i=1 #initializing part of control variable
while (i<=5): # test condition
print (i,end='\t')
i=i+1 # updation of the control variable
Output:
1 2 3 4 5
40. Explain the difference between del and clear() in dictionary with an example
In python dictionary, del keyword is used to delete a particular element.
The clear() function is used to delete all the elements in a dictionary
To remove the dictionary, we can use del keyword with dictionary name.
Example:
Dict = {‘Roll’: 12101, ‘SName’: ‘Raman’,’Tamil’:98, ‘Eng’:86}
Del Dict[‘Tamil’]
[Link]()
del Dict
Worksheet – 1
1. Identify the output of the following code snippet:
x="AnnualMeetattheCampus"
x=[Link]('a')
y=x[0]+"."+x[1]+"."+x[2]+x[3]
print(y)
6. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?
(A) print(T[1]) (B) T[2] = -29 (C) print(max(T)) (D) print(len(T))
3. 0ntixeC
5. (B) Extend method helps you to insert the list of element at the end of the list
6. (B) T[2] =-29 Tuples in Python are immutable, meaning their elements cannot be changed after the tuple is
created.
7. ['xy', 'yz']
9. [9, 5, 6, 7, 8] Since slicing in Python is safe, it does not throw an error if stop exceeds the list length.
Instead, it returns as many elements as possible.
10. 't'
11. True