0% found this document useful (0 votes)
2 views11 pages

Python Revision Tour Quick Revision Notes

The document provides a comprehensive overview of fundamental Python concepts, including tokens, keywords, identifiers, literals, operators, and data types. It explains the structure of Python programs, the importance of dynamic and static typing, and the behavior of mutable and immutable data types. Additionally, it covers control flow mechanisms like conditional statements and loops, as well as string operations and data structure manipulations.

Uploaded by

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

Python Revision Tour Quick Revision Notes

The document provides a comprehensive overview of fundamental Python concepts, including tokens, keywords, identifiers, literals, operators, and data types. It explains the structure of Python programs, the importance of dynamic and static typing, and the behavior of mutable and immutable data types. Additionally, it covers control flow mechanisms like conditional statements and loops, as well as string operations and data structure manipulations.

Uploaded by

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

Python Revision Tour

Topic 1: Tokens (Lexical Units)

●​ Definition: A token is the smallest individual unit in a Python program that is meaningful
to the interpreter. It is the fundamental building block of the language's syntax.
●​ In-Depth Explanation: Think of a Python script as an English sentence. The sentence is
made up of words, punctuation, and spaces. Similarly, a Python script is made up of
tokens. The interpreter first performs lexical analysis, which is the process of breaking
the raw text of your code into a stream of these meaningful tokens. Understanding tokens
is like learning the alphabet and punctuation before you can form words and sentences.
●​ Example: In the line print("Hello"), the tokens are:
1.​ print (an Identifier, which happens to be a built-in function name)
2.​ ( (a Punctuator)
3.​ "Hello" (a String Literal)
4.​ ) (a Punctuator)

Topic 2: Keywords
●​ Definition: A keyword is a word that is reserved by the Python language and has a
special, predefined meaning and function.
●​ In-Depth Explanation: Keywords form the structural foundation of Python. They define
the rules and logic of the language, such as how to create a loop (for, while), make a
decision (if, else), or define a function (def). You cannot use these words for any other
purpose, such as naming a variable or function, because the interpreter would be
confused.
●​ Example:​
Python​
# Using the 'if' and 'else' keywords to create a conditional statement.​
age = 18​
if age >= 18: # 'if' is a keyword​
print("You are eligible to vote.")​
else: # 'else' is a keyword​
print("You are not eligible to vote.")​

# for = 10 # This would cause a SyntaxError because 'for' is a keyword.​

Topic 3: Identifiers
●​ Definition: An identifier is a custom name given by a programmer to an entity like a
variable, function, class, or module.
●​ In-Depth Explanation: Identifiers are the labels you create to keep track of things in
your program. Choosing good, descriptive identifiers is one of the most important
aspects of writing readable and maintainable code. student_name is a much better
identifier than sn.
●​ Syntax & Rules:
1.​ Must start with a letter (a-z, A-Z) or an underscore (_).
2.​ Can be followed by any combination of letters, numbers (0-9), and underscores.
3.​ Cannot be a keyword.
4.​ Are case-sensitive (score and Score are different).
●​ Illustrative Example:​
Python​
# A good, descriptive identifier following conventions.​
player_score = 100​

# Also valid, often used for "private" or internal variables by convention.​
_internal_counter = 0​

# A valid, but poor, identifier. It's confusing.​
__l_ = "Some value" # 'l' looks like '1'​

# An invalid identifier.​
# 2nd_player_score = 50 # Will cause a SyntaxError: cannot start with a number.​

Topic 4: Literals
●​ Definition: A literal is a fixed data value that appears directly in the source code. It
represents itself.
●​ In-Depth Explanation: When you write x = 10, x is the identifier, but 10 is the literal. It's
the raw, hard-coded data. Python supports various kinds of literals to represent different
types of data.
●​ Illustrative Examples:

Type Sub-Type Description Example Code

String str Textual data in name = "Riya",


quotes. message = 'You
won!'

Numeric int Whole numbers. score = 100,


temperature = -5
int (bases) Different number binary_val = 0b101,
systems. hex_val = 0xFF

float Decimal numbers. pi = 3.14, price =


99.99

complex Real and imaginary c = 3 + 5j


numbers.

Boolean bool Represents truth is_active = True,


values. game_over = False

Special NoneType Represents the winner = None


absence of a value.

Collection list, tuple, dict, set Literals that define scores = [98, 95,
data structures. 100], point = (10,
20)

Topic 5 & 6: Operators and Punctuators


●​ Definition:
○​ An operator is a symbol that performs a specific operation (e.g., arithmetic,
comparison) on values called operands.
○​ A punctuator is a symbol used to organize code structure and syntax.
●​ In-Depth Explanation: Operators are the "verbs" of Python—they perform actions (+, *,
>). Punctuators are the "grammar"—they provide structure and clarity ((), {}, [], ,, :).
●​ Example:​
Python​
# In this line, we see operators and punctuators working together.​
scores = [10, 20, 30] # Punctuators: '=', '[', ']', ','​

total_score = scores[0] + scores[1] + scores[2] # Operators: '=', '+'. Punctuators: '[', ']'​

if total_score > 50: # Operators: '>', Punctuators: '()' and ':'​
print("Pass")​

Topic 7: Barebones & Statement Types


●​ Definition:
○​ The barebones of a program refers to its fundamental structure and layout.
○​ A Simple Statement is a single executable instruction.
○​ A Compound Statement is a statement that contains a block of other statements
and controls their execution.
●​ In-Depth Explanation: A simple statement is like a single command. A compound
statement is a container for other statements; it always has a header ending with a colon
(:) and a body of one or more indented statements. Indentation is how Python groups
statements into a block.
●​ Illustrative Example:​
Python​
# --- BAREBONES STRUCTURE ---​

# 1. Imports​
import sys​

# 2. Function Definition (A Compound Statement)​
def check_score(score):​
# 3. An 'if-else' block (also a Compound Statement)​
if score >= 50:​
# 4. A Simple Statement inside the block​
print("Status: Pass")​
else:​
print("Status: Fail")​

# 5. Main logic​
my_score = 75 # A Simple Statement​
check_score(my_score) # A Simple Statement that calls a function​

Topic 8, 9, 10, 11: Data Types & Mutability


This is a critical section that defines how Python treats data.

Dynamic Typing
●​ Definition: Dynamic Typing means the data type of a variable is determined at runtime
and can change during the program's execution.
●​ Explanation: You don't pre-declare a variable's type (like int x; in other languages).
Python automatically detects the type from the value you assign. A variable is just a name
pointing to an object, and that name can be made to point to a different type of object
later.
Immutable Data Types
●​ Definition: An immutable object is one whose internal state cannot be changed after it
has been created.
●​ Analogy: Think of an immutable object as an engraved stone tablet. To change the
text, you cannot erase it; you must carve a new tablet.
●​ Types: int, float, bool, str, tuple.
●​ Illustrative Example:​
Python​
name = "Amit"​
print(f"Initial name: {name}, Memory ID: {id(name)}")​

# It looks like we are changing the string, but we are not.​
# We are creating a NEW string object "Amit Sharma" and making the 'name'​
# label point to this new object. The original "Amit" object may be garbage collected.​
name = name + " Sharma"​

print(f"Updated name: {name}, Memory ID: {id(name)}") # The ID will be different!​

Mutable Data Types


●​ Definition: A mutable object is one whose internal state can be changed in-place after it
has been created.
●​ Analogy: Think of a mutable object as a whiteboard. You can erase a part of it and write
something new without needing a new whiteboard.
●​ Types: list, dict, set.
●​ Illustrative Example:​
Python​
student_scores = [90, 85, 92]​
print(f"Initial scores: {student_scores}, Memory ID: {id(student_scores)}")​

# We are modifying the list object IN-PLACE.​
# No new list object is created.​
student_scores.append(99)​

print(f"Updated scores: {student_scores}, Memory ID: {id(student_scores)}") # The ID will be THE
SAME!​

Topic 12, 13, 14, 15: Expressions & Conversions


Evaluating Arithmetic Operators
●​ Definition: An arithmetic expression is a combination of numeric literals, variables, and
arithmetic operators that evaluates to a numeric value.
●​ Illustrative Example:​
Python​
a = 13​
b = 4​

print(f"{a} / {b} = {a / b}") # True Division always results in a float​
print(f"{a} // {b} = {a // b}") # Floor Division rounds down to the nearest integer​
print(f"{a} % {b} = {a % b}") # Modulo gives the remainder​
print(f"{b} ** 3 = {b ** 3}") # Exponentiation (b to the power of 3)​

# --- Expected Output ---​
# 13 / 4 = 3.25​
# 13 // 4 = 3​
# 13 % 4 = 1​
# 4 ** 3 = 64​

Implicit & Explicit Conversions


●​ Definition:
○​ Implicit Conversion (Coercion): An automatic conversion of data types done by the
Python interpreter to avoid data loss.
○​ Explicit Conversion (Casting): A manual conversion of data types done by the
programmer using built-in functions.
●​ Illustrative Example:​
Python​
# Implicit Conversion: int is automatically "promoted" to float​
result = 5 + 2.5 # 5 becomes 5.0 before the addition​
print(f"Implicit conversion result: {result} (Type: {type(result)})")​

# Explicit Conversion: We force the conversion​
user_input = "101" # input() always returns a string​
# We must explicitly cast it to an integer to perform math​
value = int(user_input)​
print(f"Explicit conversion result: {value * 2} (Type: {type(value)})")​

Common Pitfall: Trying to explicitly convert an incompatible value will raise a


ValueError. For example, int("hello") will crash the program.

Operator Precedence
●​ Definition: Operator Precedence is the set of rules that dictates the order in which
operators are evaluated in a complex expression.
●​ Explanation: The acronym PEMDAS is a useful guide: Parentheses, Exponents,
Multiplication/Division, Addition/Subtraction. Operators on the same level (like * and /)
are evaluated from left to right.
●​ Illustrative Example:​
Python​
# Without parentheses, precedence rules apply:​
# 1. 3 * 5 = 15​
# 2. 10 + 15 = 25​
result_1 = 10 + 3 * 5​
print(f"Result without parentheses: {result_1}") # 25​

# With parentheses, we override the default order:​
# 1. (10 + 3) = 13​
# 2. 13 * 5 = 65​
result_2 = (10 + 3) * 5​
print(f"Result with parentheses: {result_2}") # 65​

Evaluation of Logical Operators


●​ Definition: Logical operators (and, or, not) are used to combine conditional statements
and evaluate to either True or False.
●​ Short-Circuiting Explanation: Python is efficient. For A and B, if A is False, it doesn't
bother checking B. For A or B, if A is True, it doesn't bother checking B. This is called
short-circuiting.
●​ Illustrative Example:​
Python​
def is_valid():​
print("---is_valid() function was called---")​
return True​

# Example 1: Short-circuiting with 'or'​
# Since the first part is True, the function is_valid() is never called.​
print("Testing 'or':")​
if True or is_valid():​
print("Result is True")​

# Example 2: Short-circuiting with 'and'​
# Since the first part is False, the function is_valid() is never called.​
print("\nTesting 'and':")​
if False and is_valid():​
print("This will not be printed")​
else:​
print("Result is False")​
Topic 16, 17, 18, 19: Control Flow
Conditional Statements
●​ Definition: A conditional statement (if, elif, else) executes a block of code only if a certain
condition is met.
●​ Example: See Section 7.1.

Loops
●​ Definition: A loop (for, while) repeatedly executes a block of code.
●​ Explanation: Use a for loop when you want to iterate over a known sequence (definite
iteration). Use a while loop when you want to repeat as long as a condition is true
(indefinite iteration).

Jump Statements in Loops


●​ Definition: Jump statements (break, continue, pass) alter the normal flow of a loop.
●​ break: Exits the loop entirely.
●​ continue: Skips the current iteration and moves to the next.
●​ pass: Does nothing; acts as a placeholder.

The else Clause in Loops


●​ Definition: The else block attached to a loop executes only if the loop completes its
entire sequence without being terminated by a break statement.
●​ Illustrative Example:​
Python​
# Scenario 1: The 'else' block RUNS because break is not executed.​
print("--- Searching for a number NOT in the list ---")​
my_numbers = [1, 5, 9, 13]​
for num in my_numbers:​
if num == 10:​
print("Found 10!")​
break​
else:​
print("The number 10 was not found after checking the whole list.")​

# Scenario 2: The 'else' block DOES NOT RUN because break is executed.​
print("\n--- Searching for a number IN the list ---")​
for num in my_numbers:​
if num == 9:​
print("Found 9!")​
break​
else:​
print("This line will not be printed.")​

Topic 20, 21, 22, 23: Data Structure Operations


This section serves as a detailed reference for manipulating the core data structures.

Strings (str) Operations


An immutable sequence of characters.

Method Description Example

s.upper() Converts the string to "Hello".upper() -> "HELLO"


uppercase.

s.lower() Converts the string to "Hello".lower() -> "hello"


lowercase.

s.strip() Removes leading/trailing " Hello ".strip() -> "Hello"


whitespace.

s.replace(old, new) Replaces all occurrences of "Hi Hi".replace("i", "ey") ->


old with new. "Hey Hey"

s.split(del) Splits the string at del and "a-b-c".split('-') -> ['a', 'b',
returns a list. 'c']

'del'.join(list) Joins a list of strings using "-".join(['a', 'b', 'c']) ->


del as a separator. "a-b-c"

s.find(sub) Returns the first index of "hello".find('ll') -> 2


sub; -1 if not found.

s.count(sub) Counts occurrences of sub. "hello".count('l') -> 2

Lists (list) Operations


A mutable, ordered sequence of items.

Method Description Example

L.append(item) Adds item to the end of the L=[1]; L.append(2) -> [1, 2]
list.

L.insert(i, item) Inserts item at index i. L=[1,3]; L.insert(1, 2) -> [1,


2, 3]

L.extend(iterable) Appends all items from L=[1]; L.extend([2,3]) -> [1,


iterable. 2, 3]

L.pop(i) Removes and returns item L=[1,2]; L.pop() -> 2; L is [1]


at index i (or last item).

L.remove(val) Removes the first L=[1,2,1]; L.remove(1) -> [2,


occurrence of val. 1]

L.sort() Sorts the list in-place. L=[3,1,2]; L.sort() -> L is [1,


2, 3]

L.reverse() Reverses the list in-place. L=[1,2,3]; L.reverse() -> L is


[3, 2, 1]

L.copy() Returns a shallow copy of L2 = L.copy()


the list.

Tuples (tuple) Operations


An immutable, ordered sequence of items. Fewer methods because they can't be changed.

Operation Description Example

len(T) Returns the number of T=(1,2); len(T) -> 2


items.

T[i] Accesses the item at index T=(1,2); T[0] -> 1


i.

T.count(val) Counts occurrences of val. T=(1,2,1); T.count(1) -> 2

T.index(val) Returns the index of the T=(1,2,1); T.index(1) -> 0


first val.

Dictionaries (dict) Operations


A mutable collection of key-value pairs.

Method Description Example

D[key] Accesses the value for key. D={'a':1}; D['a'] -> 1

D[key] = val Sets the value for key. D={'a':1}; D['b']=2 -> {'a':1,
'b':2}

D.get(key, def) Gets value for key, returns D.get('c', 0) -> 0


def if not found.

D.keys() Returns a view object of all list(D.keys()) -> ['a', 'b']


keys.

D.values() Returns a view object of all list(D.values()) -> [1, 2]


values.

D.items() Returns a view object of list(D.items()) -> [('a',1),


(key, value) pairs. ('b',2)]

D.pop(key) Removes key and returns D.pop('a') -> 1; D is {'b':2}


its value.

D.update(D2) Merges dictionary D2 into D.update({'c':3}) -> {'b':2,


D. 'c':3}

You might also like