Python Revision Tour

Python Revision TOur

1. About Python

Python is a high-level programming language developed by Guido Van Rossum. It is an interpreted and platform-independent language, meaning the exact same code can run on any operating system. Python is completely free to use, based on the ABC and Modula-3 programming languages, and supports both procedural and object-oriented programming approaches.

2. Basic Terms Used in Python

  • Token / Lexical Unit: The smallest individual unit in a Python program. A token has a specific meaning for the Python interpreter. Examples include Keywords, Identifiers, Literals, Operators, and Punctuators.
  • Keywords: Words assigned a specific purpose that can only be used for that purpose (e.g., and, while, del, with, True, None, False, return, try).
  • Identifiers: Names given to variables, objects, classes, or functions. You must follow predefined rules when forming identifiers to avoid a Syntax Error.
  • Literals: Data items that have a fixed value. If it holds numbers, it is a Numeric Literal; if it holds text, it is a String Literal. Python also uses the special literal None to indicate the absence of a value.
  • Operators: Symbols that perform specific operations on operands (variables). The operator precedence in Python goes from highest to lowest: Parentheses (), Exponentiation **, Bitwise NOT ~x, Unary positive/negative +x, -x, Multiplication/Division/Floor Division/Remainder *, /, //, %, Addition/Subtraction +, -, Bitwise AND &, Bitwise XOR ^, Bitwise OR |, Comparisons/Identity >, <, ==, is, is not, Boolean not, and Boolean and. Note: When comparing variables, == checks for equality of value, while is (identity) checks if both variables point to the exact same object in memory.
  • Punctuators: Symbols used to organize sentence structure in programming.
  • Variables: Unlike other languages, variables in Python are temporary memory locations, not storage containers. Every time you assign a new value to a variable, it points to a new memory location. You do not need to specify the size and type of the variable upfront.

3. Data Types in Python

A Data Type specifies the kind of data stored in a variable, which dictates how memory is allocated and what operations can be performed. When you assign a value directly, Python decides the type at run time (implicit conversion). For example:

a = 'hello'  # a is of string type
a = 12       # a is of integer type
a = 12.56    # a is of float type

Type Casting is when data type conversion is done explicitly by forcing the variable through built-in functions like int(), float(), str(), list(), tuple(), or dict().

a = 12       # a is of integer type
b = float(a) # changing a from integer to float
# now b will contain float value of a: 12.0

Mutable vs. Immutable Data Types

  • Mutable Data Types: Values can be changed directly at their specific memory location without creating a new object.
  • Immutable Data Types: Values cannot be changed after they are created. Making any changes will assign the object to a completely new memory location.

Core Data Type Categories

  1. Numeric:
    • Integers: Store whole positive or negative numbers.
    • Floating-point numbers: Used for fractional parts (represents 15-digit double precision).
    • Complex numbers: Stored in the form A + Bj (where A is real and B is imaginary).
  2. Boolean: Allows storing only True (internally 1) and False (internally 0).
  3. Sequence Data Types: Stores a collection of values in an ordered manner, traversable via indexing. These include Strings, Lists, and Tuples.

4. Sequence Type: STRINGS

A String is an immutable sequence made up of one or more UNICODE characters (letters, digits, whitespaces, symbols). Strings are created by enclosing characters in single, double, or triple quotes.

>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""

Indexing: Individual characters are accessed using an index in square brackets []. The first character index is 0 and the last is n-1 (where n is length). Negative indexing ranges from -n to -1.

String Operations

1. Concatenation (+): Joins two strings together.

>>> str1 = 'Hello' 
>>> str2 = 'World!' 
>>> str1 + str2 
'HelloWorld!'

2. Repetition (*): Repeats the string a given number of times.

>>> str1 = 'Hello' 
>>> str1 * 2  
'HelloHello'

3. Membership (in and not in): Returns True if the first string appears as a substring in the second.

>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' not in str1
False

4. Slicing: Extracts a substring by specifying an index range [n:m], returning characters from index n up to m-1.

>>> str1 = 'Hello World!' 
>>> str1[1:5]  # substring from index 1 to 4 
'ello' 
>>> str1[7:10] # substring from 7 to 9 
'orl' 
>>> str1[3:20] # index too big is truncated to end of string 
'lo World!' 
>>> str1[7:2]  # first index > second index results in empty string 
''

Traversing a String Using Loops

Using for Loop: The loop automatically ends when the last character is accessed.

>>> str1 = 'Hello World!' 
>>> for ch in str1:
...     print(ch)

Using while Loop:
>>> index = 0  
>>> while index < len(str1):
...     print(str1[index], end = '')
...     index += 1
Hello World!

Essential Built-In String Functions

  • len(): Returns string length. len('Hello World!') -> 12.
  • title(): First letter of every word is uppercase. 'hello WORLD!'.title() -> 'Hello World!'.
  • lower(): Converts all to lowercase. 'hello WORLD!'.lower() -> 'hello world!'.
  • upper(): Converts all to uppercase. 'hello WORLD!'.upper() -> 'HELLO WORLD!'.
  • count(str, start, end): Counts occurrences of a substring.
  • find(str, start, end): Returns first occurrence index, or -1 if not found.
  • index(): Similar to find, but raises a ValueError if not found.
  • endswith(): Returns True if the string ends with the substring. str1.endswith('World!') -> True.
  • startswith(): Returns True if string starts with substring. str1.startswith('He') -> True.
  • isalnum(): Returns True if characters are only alphabets or numeric (no spaces/symbols). 'HelloWorld!!'.isalnum() -> False.
  • islower(): Returns True if all alphabetic characters are lowercase. 'hello 1234'.islower() -> True.
  • isupper(): Returns True if all alphabetic characters are uppercase. 'HELLO WORLD!'.isupper() -> True.
  • isspace(): Returns True if all characters are whitespaces. ' \n \t \r'.isspace() -> True.
  • istitle(): Returns True if in title case.
  • lstrip() / rstrip() / strip(): Removes spaces from the left, right, or both sides respectively.
  • replace(oldstr, newstr): Replaces all occurrences. 'Hello World!'.replace('o','*') -> 'Hell* W*rld!'.
  • join(): Joins characters by a separator. '-'.join('HelloWorld!') -> 'H-e-l-l-o-W-o-r-l-d-!'.
  • partition(): Partitions at the first occurrence into 3 parts (before, separator, after).
  • split(): Delimits string into a list of words. 'India is a Great Country'.split('a') -> ['Indi', ' is ', ' Gre', 't Country'].

5. Sequence Type: LISTS

A List is an ordered, mutable sequence made of elements that can be of mixed data types (integers, strings, tuples, or even other lists) enclosed in square brackets [].

List Operations

Concatenation (+) & Repetition (*):

>>> list1 = [1, 3, 5, 7, 10]   
>>> list2 = [2, 4, 6, 8, 11]   
>>> list1 + list2    
[1-8, 10, 11]  

>>> list1 = ['Hello']   
>>> list1 * 4  
['Hello', 'Hello', 'Hello', 'Hello']

Membership & Slicing:

>>> list1 = ['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']  
>>> 'Green' in list1  
True  
>>> list1[2:6]  
['Blue', 'Cyan', 'Magenta', 'Yellow']

Traversal (Using for loop):

>>> list1 = ['Red','Green','Blue','Yellow', 'Black']  
>>> for item in list1:
...     print(item)  
Red  
Green  
Blue  
Yellow  
Black

Essential Built-In List Functions

  • len() / list(): Get length, or create an empty/cast list. list('aeiou') -> ['a', 'e', 'i', 'o', 'u'].
  • append(): Appends a single element at the end. list1.append() adds a list inside the list.
  • extend(): Appends each element of a passed sequence to the end. .extend() -> .
  • insert(): Inserts element at a specific index. list1.insert(2,25).
  • count(): Returns occurrences of an element.
  • index(): Returns first occurrence index (throws ValueError if not found).
  • remove(): Removes the first occurrence of an element (throws ValueError if not present).
  • pop(): Removes and returns an element at an index (removes the last element if no parameter is passed).
  • reverse(): Reverses elements in place.
  • sort(): Sorts elements in place. list1.sort(reverse = True) sorts in descending order.
  • sorted(): Returns a new sorted list without changing the original.
  • min() / max() / sum(): Returns minimum, maximum, and sum of elements.

6. Sequence Type: TUPLES

A Tuple is an ordered sequence of elements enclosed in round brackets (). The primary difference between lists and tuples is that tuples are immutable; their elements cannot be changed after creation.

>>> tuple1 = (1,2,3,4,5)  
>>> tuple1[4] = 10  
TypeError: 'tuple' object does not support item assignment

Note: If a sequence has comma-separated elements without parentheses, it is still treated as a tuple.

Tuple Operations: Like lists and strings, tuples fully support Concatenation (+), Repetition (*), Membership (in), and Slicing.

>>> tuple1 = (1,3,5,7,9)  
>>> tuple2 = (2,4,6,8,10)  
>>> tuple1 + tuple2          
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

>>> tuple1 = ('Hello','World')  
>>> tuple1 * 3  
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

Tuples also support the built-in functions: len(), tuple(), count(), index(), sorted(), min(), max(), and sum() exactly like lists.

7. Data Type: DICTIONARY (Mapping)

A Dictionary is an unordered collection mapping a set of unique keys to values. They are mutable, enclosed in curly braces {}, and the key-value pair is separated by a colon :.

  • Rules: Dictionary keys must be unique and of an immutable data type (like strings, numbers, or tuples). Values can be repeated and of any data type.

Creating & Accessing Dictionaries

>>> dict1 = {}  # Empty dictionary
>>> dict3 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}  
>>> dict3['Ram']  # Accessing via key
89
>>> dict3['Shyam']  # Throws error if key doesn't exist
KeyError: 'Shyam'

Modifying & Membership

Because dictionaries are mutable, you can easily add new items or overwrite existing values.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}  
>>> dict1['Meena'] = 78  # Adding new item
>>> dict1['Suhel'] = 93.5  # Overwriting item
>>> 'Suhel' in dict1 # Membership checks keys!
True

Traversing a Dictionary

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}  
# Method 1
>>> for key in dict1:                 
...     print(key,':',dict1[key])

# Method 2
>>> for key,value in dict1.items():                        
...     print(key,':',value)

Essential Built-in Dictionary Methods

  • len() / dict(): Get length or create from sequence.
  • keys(): Returns list of keys. dict1.keys() -> dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta']).
  • values(): Returns list of values. dict1.values() -> dict_values().
  • items(): Returns a list of tuple key-value pairs. dict1.items() -> dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]).
  • get(): Returns the value safely, returning None if the key isn’t found instead of a KeyError. dict1.get('Sohan') -> returns None.
  • update(): Appends key-value pairs from a passed dictionary.
  • del() / clear(): Deletes a specific item or clears the entire dictionary.

8. Practice Questions & Assignments

Test your Python Revision Tour knowledge with these practice questions taken straight from the syllabus!

Multiple Choice Questions:

  1. What will be the output of the following expression? float(5 + int(4.39 + 2.1) % 2) a. 5.0 | b. 5 | c. 8.0 | d. 8
  2. What is the value of this expression? 3*1**3 a. 27 | b. 9 | c. 3 | d. 1
  3. What can be a possible output at the time of execution of the program from the following code? import random AR =; FROM = random.randint(1,3) TO = random.randint(2,4) for K in range(FROM,TO+1): (i) 10#40#70# | (ii) 30#40#50# | (iii) 50#60#70# | (iv) 40#50#70#
  4. Identify the invalid python statement from the following: a. d = dict() | b. l = {} | c. f = () | d. g = dict {}
  5. List AL is defined as follows: AL =. Which of the following statements removes the middle element 3 from it, so that list AL equals ? (Multiple options are correct) a. del a | b. a[2:3] = [] | c. a[2:2] = [] | d. a = [] | e. a.remove(3)
  6. Select the correct output of the following string operation (slicing notation snippet missing in source): a. Wah Bhyi Wah | b. Wah Bhyi aha | c. WahBhyiWah | d. WahBhyiWaha
  7. Select the correct output of the following code print(L[::-2]): a. (blank) | b. G20 | c. (blank)
  8. What is printed when the following code is executed? print(K[-1][-1]) a. R | b. m | c. Ram | d. Gita | e. a
  9. What will be the output of the following code? print(dict) a. | c. | d. Error
  10. What will be the output of the following Python code? for i in d1: str1 = str1 + str2 = str1[:-1] print(str2[::-1]) a. 3, 2 | b. 3, 2, 10 | c. 3, 2, 01 | d. Error

Assertion & Reason Based Questions: Options for below: A – Both true & R is correct explanation of A. B – Both true but R is NOT correct explanation of A. C – A is true but R is false. D – A is false but R is true. E – Both A and R are false.

  1. Assertion (A): List is a mutable data type of Python. Reason (R): In place change is not possible in list elements.
  2. Assertion (A): in and not in are called membership operators. Reason (R): They return True based on the presence of a character/substring in a given string.
  3. Assertion (A): Python strings are mutable in nature. Reason (R): Python strings are stored in memory by storing individual characters in contiguous memory locations.
  4. Assertion (A): append() and extend() are both methods to insert elements in a list. Reason (R): While append() adds elements at the end of the list, extend can add elements anywhere in the list.
  5. Assertion (A): A dictionary cannot have two same keys with different values. Reason (R): Keys of a dictionary must be unique.

Fill in the blanks:

  1. The ________ statement is an empty statement in Python. (pass)
  2. A _________ statement skips the rest of the loop and jumps over to the statement following the loop. (break)
  3. Python’s __________ cannot be used as variable name. (keywords)
  4. The explicit conversion of an operand to a specific type is called _________ . (type casting)
  5. The data types whose values cannot be changed in place are called _________ types. (immutable)
  6. The _______ can add an element in the middle of a list. (insert())
  7. The _________ only adds an element at the end of a list. (append())
  8. The keys of a dictionary must be of ________ type. (immutable)
  9. Dictionary is an _________ set of elements. (unordered)
  10. To get all the keys of a dictionary, ________ method is used. (keys())

Leave a Reply

Your email address will not be published. Required fields are marked *