0% found this document useful (0 votes)
3 views

Python(2)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python(2)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Revision Notes

1. Revision of Python Basics


 Data Types:
o Integers (int): Whole numbers (e.g., -2, 0, 100)
o Floa ng-point numbers (float): Numbers with
decimal points (e.g., 3.14, -2.5)
o Strings (str): Sequences of characters enclosed in
single or double quotes (e.g., "Hello", 'Python')
o Booleans (bool): Represent truth values (True or
False)
 Operators:
o Arithme c Operators: + (addi on), - (subtrac on), *
(mul plica on), / (division), % (modulo - remainder),
** (exponen a on), // (floor division)
o Rela onal Operators: > (greater than), < (less than),
>= (greater than or equal to), <= (less than or equal
to), == (equal to), != (not equal to)
o Logical Operators:1 and (logical AND), or (logical OR),
not (logical NOT)
o Assignment Operators: = (assign), += (add and
assign), -= (subtract and assign), etc.
 Input/Output:
o input(): Reads a line of input from the user as a string.
o print(): Displays output to the console.
 Type Conversion:
o int(): Converts a value to an integer.
o float(): Converts a value to a floa ng-point number.
o str(): Converts a value to a string.
 Control Flow:
o Condi onal Statements:
 if: Executes a block of code if a condi on is true.
 elif: (else if) Executes a block of code if the
previous condi on(s) were false and this
condi on is true.
 else: Executes a block of code if none of the
preceding condi ons were true.
o Loops:
 for: Iterates over a sequence (e.g., a list, string, or
range of numbers).
 while: Repeats a block of code as long as a
condi on is true.
2. Working with Data Structures
 Lists:
o Ordered collec ons of items.
o Mutable (can be changed a er crea on).
o Defined using square brackets [].
o Example opera ons: append(), insert(), remove(),
pop(), sort(), reverse().
 Tuples:
o Ordered collec ons of items.
o Immutable (cannot be changed a er crea on).
o Defined using parentheses ().
o O en used for storing related pieces of data.
 Dic onaries:
o Collec ons of key-value pairs.
o Unordered.
o Mutable.
o Defined using curly braces {}.
o Keys must be unique and immutable (e.g., strings,
numbers, tuples).
o Example opera ons: accessing values by key, adding
new key-value pairs, upda ng values.
 Sets:
o Unordered collec ons of unique items.
o Mutable.
o Defined using curly braces {} or the set() constructor.
o Useful for removing duplicates from a list or
performing set opera ons (union, intersec on,
difference).
3. String Manipula on
 String Indexing and Slicing:
o Strings are indexed star ng from 0.
o Access individual characters using their index (e.g.,
my_string[0] for the first character).
o Extract substrings using slicing (e.g., my_string[1:4]
for characters at indices 1, 2, and 3).
 String Methods:
o upper(): Converts the string to uppercase.
o lower(): Converts the string to lowercase.
o strip(): Removes leading and trailing whitespace. 2
o split(): Splits the string into a list of substrings based
on a delimiter.
o join(): Joins a list of strings into a single string using 3 a
delimiter.
o replace(): Replaces occurrences of a substring with
another substring.
o ...and many more!
 String Forma ng:
o f-strings: Embed variables and expressions directly
within strings using curly braces {}. (e.g., f"My age is
{age}")
o format() method: Use placeholders {} in a string and
provide values to fill them using the format() method.
4. Func ons
 Defining Func ons:
o Use the def keyword followed by the func on name,
parentheses for parameters, and a colon.
o The func on body is indented.
 Func on Arguments and Parameters:
o Parameters are variables listed in the func on
defini on.
o Arguments are the actual values passed to the
func on when it's called.
 Return Values:
o Use the return statement to send a value back from
the func on.
 Scope of Variables:
o Local variables: Variables defined inside a func on
are only accessible within that func on.
o Global variables: Variables defined outside any
func on are accessible throughout the program.
5. File Handling
 Opening and Closing Files:
o open(filename, mode): Opens a file in the specified
mode.
o file.close(): Closes the file.
 File Modes:
o "r": Read mode (default).
o "w": Write mode (creates a new file or overwrites an
exis ng one).
o "a": Append mode (adds data to the end of an
exis ng file).
o "x": Create mode (creates a new file, but raises an
error if the file already exists).
o You can also add "b" for binary mode (e.g., "rb" for
reading a binary file).
 Reading and Wri ng Data:
o read(): Reads the en re file content as a string.
o readline(): Reads a single line from the file.
o readlines(): Reads all lines from the file and returns
them as a list4 of strings.
o write(data): Writes data to the file.
6. Using Python Libraries
 math module:
o Provides mathema cal func ons like sqrt(), sin(),
cos(), tan(), log(), ceil(), floor(), and more.
 random module:
o Generates random numbers.
o random(): Returns a random float between 0.0 and
1.0.
o randint(a, b): Returns a random integer between a
and b (inclusive).
o choice(seq): Returns a random element from a
sequence (e.g., a list or tuple).
 sta s cs module:
o Performs sta s cal calcula ons.
o mean(data): Calculates the mean (average) of a
dataset.
o median(data): Calculates the median of a dataset.
o stdev(data): Calculates the standard devia on of a
dataset.
7. Addi onal Topics (Depending on your curriculum)
 Object-Oriented Programming (OOP):
o Classes: Blueprints for crea ng objects.
o Objects: Instances of classes.
o Inheritance: Crea ng new classes that inherit
proper es and methods from exis ng classes.
o Polymorphism: The ability of objects of different
classes to respond to the same method call in
different ways.
 Excep on Handling:
o try: A block of code that might raise an excep on.
o except: Handles specific types of excep ons.
o finally: Code that always executes, regardless of
whether an excep on occurred.
 Modules and Packages:
o Modules: Python files containing func ons, classes,
and variables that can be reused in other programs.
o Packages: Collec ons of related modules.
 Database Connec vity:
o Using libraries like sqlite3 to connect to and interact
with databases (e.g., crea ng tables, inser ng data,
retrieving data).

You might also like