Python Basics
I was programming when I found interest in data science, earlier for nearly 5 years I was using MS Excel for data analysis and data handling until I touched the limits of excel. I found alternatives for excel that is the python for data analysis
Let me explain the python basics which I know is most useful for any data enthusiast
Environment for using python
I like to use Jupyter note book and VS code for the execution and writing the code
The extension of the python I like to use ipynb because it allows me to write multiple cells of code and execute it instantly
Print function prints whatever content given to it, example
print(“Hello everyone!”)
Output: Hello everyone!
Here Hello everyone! Is the argument for the print function
Passing the variable in print function
no_of_chcolate = 10
print(f”I have {no_of_chcolate} chocolates”)
Output: I have 10 chocolates
Operators in python
Arithmetic operators in python
- ** (Exponent)
- % (modulo or remainder)
- / (division)
- // (quotient)
- * (multiply)
- – (subtract)
- + (add)
Comparison operators
- > Greater than
- < Less than
- <= Less than or equal to
- >= Greater than or equal to
- == Checking equality
- != Not equal to
Logical (or Boolean) operators
- True
- False
Assignment operators
- = assigns a value to a variable
- += adds the variable along with itself
- -= subtracts the variable along with itself
- *= multiplies the variable along with itself
- %= returns the remainder after dividing the variable along with itself
- /= gives quotient, after dividing with the variable along with itself
- //= returns only the integer part of the quotient with the variable along with itself
Data types
Data type | Description | Example |
Numeric | ||
int | Integers (whole numbers) | X =10 |
Float | Decimal numbers | X=10.01 |
complex | Real + imaginary part | X=10+2j |
String | ||
String | Sequence of characters | text = “Hello, world!” |
Boolean | ||
Boolean | True or False | X= True |
Ordered collections | ||
List | Ordered collection of items (mutable) | my_list = [1, 2, 3, “apple”] |
Tuple | Ordered collection of items (immutable) | my_tuple = (1, 2, 3, “apple”) |
Set | Unordered collection of unique items | my_set = {1, 2, 3, “apple”} |
Dictionary | Unordered collection of key-value pairs | my_dict = {“name”: “Alice”, “age”: 30} |
String operations
Operation | Description | Syntax | Example |
Accessing characters | Access individual characters using index | string[index] | text = “Python”; print(text[0]) |
Slicing | Extract a substring | string[start:end:step] | text = “Python”; print(text[1:4]) |
Concatenation | Combine strings | string1 + string2 | str1 = “Hello”; str2 = “World”; result = str1 + ” ” + str2 |
Length | Get the length of a string | len(string) | text = “Python”; print(len(text)) |
Case conversion | Convert case of characters | .lower(), .upper(), .title(), .capitalize(), .swapcase() | text = “Hello”; print(text.upper()) |
Searching | Find substrings | .find(), .index(), .startswith(), .endswith() | text = “Python”; print(text.find(“on”)) |
Replacing | Replace substrings | .replace(old, new) | text = “Python”; print(text.replace(“Py”, “Ja”)) |
Stripping | Remove leading/trailing whitespace | .strip(), .lstrip(), .rstrip() | text = ” Python “; print(text.strip()) |
Splitting | Split a string into a list of substrings | .split(separator) | text = “apple,banana,cherry”; fruits = text.split(“,”) |
Joining | Join a list of strings into a single string | delimiter.join(list) | fruits = [“apple”, “banana”, “cherry”]; joined_text = “-“.join(fruits) |
Checking content | Check for specific content | .isalpha(), .isdigit(), .isalnum(), .isspace() | text = “123”; print(text.isdigit()) |
Formatting | Format strings with variables | f”string” or .format() | name = “Alice”; age = 30; print(f”Hello, {name}! You are {age} years old.”) |
Justification | Adds spaces | rjust, ljust, or center | ‘328’.rjust(5,”*”) -> **328 |
Indentation
- Enhances readability
- Prevents error
- Places indentation after : in loops or condition
Conditional statements
If-elif-else
grade = 85
if grade >= 90:
print(“Excellent”)
elif grade >= 80:
print(“Good”)
else:
print(“Needs improvement”)
Shorthand way to write if statements
age = 10
is_adult = True if age >= 18 else False
is_adult
Nested if conditions
age = 25
country = “India”
if age >= 18:
if country == “India”:
print(“You are an adult citizen of the India “)
else:
print(“You are an adult, but not a Indian citizen”)
else:
print(“You are a minor”)
Control flow statements
Break, Continue, Pass
Statement | Description | Example |
break | Terminate the loop | for i in range(10): if i == 5: break print(i) |
continue | Skips current iteration | for i in range(5): if i == 3: continue print(i) |
pass | Does nothing (place holder) | if condition: pass |
Loops
While loop | For Loop |
Controlled by a condition | Controlled by the sequence length |
count = 0 while count < 5: print(count) count += 1 | fruits = [“apple”, “banana”, “cherry”] for fruit in fruits: print(fruit) |
i = 0 while i < 3: j = 0 while j < 2: print(i, j) j += 1 i += 1 | for i in range(3): for j in range(2): print(i, j) |
Functions
Function | Lambda function |
def keyword | lambda keyword |
Multiple lines, can have complex logic | Single expression |
General-purpose functions | Short, simple operations |
def greet(name): print(“Hello,”, name + “!”) greet(“Alice”) # Output: Hello, Alice! | double = lambda x: x * 2 result = double(5) # Output: 10 |
Syntax errors
Error Type | Description | Example |
Missing colon | Required after if, else, for, while, def, and class statements | if condition print(“Hello”) |
Incorrect indentation | Indentation to define code blocks | if condition: print(“Hello”) print(“World”) |
Mismatched parentheses/brackets/braces | Unbalanced parentheses, brackets, or braces | print(“Hello, world(“) |
Missing quotes | Unclosed strings | print(Hello) |
Invalid characters | Using characters not allowed in variable names | 123variable = 10 |
Keyword misuse | Using keywords as variable names | print = “Hello” |
Unexpected EOF (End of File) | Code ends prematurely, missing closing parentheses, brackets, or quotes | print(“Hello |
Errors in python
Error Type | Description | Example |
NameError | Use a variable that doesn’t exist | print(x) (if x is not defined) |
TypeError | Operation on incompatible types | hello’ + 5 |
ValueError | Correct type but improper value | int(‘abc’) |
IndexError | Access index which is out of range | my_list[5] (if list has only 4 elements) |
ZeroDivisionError | Division by zero | 10 / 0 |
KeyError | Access a nonexistent key in a dictionary | my_dict[‘nonexistent_key’] |
Read files in excel
df = sns.load_dataset(“titanic”)
df = pd.read_csv(r”C:\Users\User\Documents\file.csv”)
Save to a file
df.to_csv(r”Data.csv”)
Containers
Lists
Operation | Syntax | Description | Example |
Accessing elements | list[index] | Access an element at a specific index (starts from 0) | my_list = [1, 2, 3]; print(my_list[0]) |
Slicing | list[start:end:step] | Extract a sublist | my_list = [1, 2, 3, 4, 5]; print(my_list[1:4:2]) |
Changing elements | list[index] = new_value | Modify an element at a specific index | my_list[0] = 10 |
Adding elements | list.append(item) | Add an element to the end of the list | my_list.append(6) |
Inserting elements | list.insert(index, item) | Insert an element at a specific index | my_list.insert(2, ‘hello’) |
Adding multiple elements | list.extend(iterable) | Extend the list with elements from another iterable | my_list.extend([2, ‘hello’]) |
Removing elements | list.remove(item) | Remove the first occurrence of an item | my_list.remove(3) |
Delete element | Del list. [index] | Delete element in index | del my_list [0] |
Removing element by index | list.pop(index) | Remove and return the element at a specific index (default: last) | removed_item = my_list.pop(1) |
Finding index of an element | list.index(item) | Return the index of the first occurrence of an item | index = my_list.index(‘hello’) |
Counting elements | list.count(item) | Count the number of occurrences of an item | count = my_list.count(2) |
Sorting the list | list.sort() | Sort the list in ascending order | my_list.sort() |
Reversing the list | list.reverse() | Reverse the order of elements in the list | my_list.reverse() |
Concatenating lists | list1 + list2 | Combine two lists | combined_list = my_list + [7, 8] |
List length | len(list) | Get the number of elements in the list | length = len(my_list) |
Checking for membership | item in list | Check if an item is present in the list | if 3 in my_list: |
Copying a list | new_list = list.copy() | Create a shallow copy of the list | new_list = my_list.copy( |
Finding minimum and maximum | min(list), max(list) | ||
Multiplying a list | list * n |
Creating new list form existing list
Function | Syntax | Description | Example |
List Comprehension |
Expression for item in iterable if condition
Creates a new list based on an iterable with optional filtering
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers if x % 2 == 0]
# Squares of even numbers
print(squares)
# Output: [4, 16]
Map
map(function, iterable, …)
Applies a function to each element of an iterable
numbers = [1, 2, 3, 4, 5]
def square(x):
return x**2
squared_numbers = list(map(square, numbers))
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]
Filter
filter(function, iterable)
Creates an iterator of elements for which the function returns True
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4]
Zip
zip(*iterables)
Aggregates elements from multiple iterables into tuples
numbers = [1, 2, 3]
letters = [‘a’, ‘b’, ‘c’]
zipped_list = list(zip(numbers, letters))
print(zipped_list)
# Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’)]
enumerate
enumerate(iterable, start=0)
Adds a counter to an iterable and returns it as an enumerate object
fruit = [‘apple’, ‘banana’, ‘cherry’]
for index, fru in enumerate(fruit):
print(index, fru)
Concatenate
list1 + list2
Concatenate
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
extend
list1.extend(iterable)
Appends all elements
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
Tuples
Operation | Syntax | Description | Example |
Accessing elements | tuple[index] | Access an element at a specific index (starts from 0) | my_tuple = (1, 2, 3) print(my_tuple[0]) |
Slicing | tuple[start:end:step] | Extract a sub-tuple | my_tuple = (1, 2, 3, 4, 5) print(my_tuple[1:4:2]) |
Concatenation | tuple1 + tuple2 | Combine two tuples into a new tuple | tuple1 = (1, 2) tuple2 = (3, 4) combined_tuple = tuple1 + tuple2 |
Length | len(tuple) | Get the number of elements in the tuple | my_tuple = (1, 2, 3) length = len(my_tuple) |
Membership testing | item in tuple | Check if an item exists in the tuple | if 2 in my_tuple: |
Indexing and counting | tuple.index(item), tuple.count(item) | Find the index of an item or count its occurrences | index = my_tuple.index(2) count = my_tuple.count(1) |
Converting to a list | list(tuple) | Convert a tuple to a list (for modification) | my_list = list(my_tuple) |
Applications of tuple
my_dict = {(1, 2): ‘value1’, (3, 4): ‘value2’}
Dictionary
Operation | Syntax | Description | Example |
Accessing value | dictionary[key] | Retrieves the value associated with the given key | my_dict = {‘a’: 1, ‘b’: 2} value = my_dict[‘a’] |
Adding or modifying a key-value pair | dictionary[key] = value | Adds a new key-value pair or modifies an existing one | my_dict[‘c’] = 3 |
Deleting a key-value pair | del dictionary[key] | Removes the key-value pair with the given key | del my_dict[‘b’] |
Checking if a key exists | key in dictionary | Returns True if the key exists, False otherwise | if ‘a’ in my_dict: |
Getting all keys | dictionary.keys() | Returns a view of the dictionary’s keys | keys = my_dict.keys() |
Getting all values | dictionary.values() | Returns a view of the dictionary’s values | values = my_dict.values() |
Getting key-value pairs | dictionary.items() | Returns a view of the dictionary’s key-value pairs as tuples | items = my_dict.items() |
Removing and returning a random item | dictionary.popitem() | Removes and returns an arbitrary (key, value) pair | removed_item = my_dict.popitem() |
Getting a value with a default | dictionary.get(key, default_value) | Returns the value for the key if it exists, otherwise returns the default value | value = my_dict.get(‘d’, 0) |
Updating multiple key-value pairs | dictionary.update(other_dict) | Updates the dictionary with key-value pairs from another dictionary | my_dict.update({‘e’: 5, ‘f’: 6}) |
Clear the dictionary | dictionary.clear() | Removes all items from the dictionary | my_dict.clear() |
Creating a copy of the dictionary | new_dict = dictionary.copy() | Creates a shallow copy of the dictionary | new_dict = my_dict.copy() |
Clear | new_dict.clear() | Clears all key value pairs | new_dict.clear() |
Setdefault | dictionary.setdefault(key, default_value) | insert a key-value pair if the key doesn’t already exist in the dictionary It returns the value for the key if it exists | my_dict = {‘a’: 1, ‘b’: 2} # Accessing an existing key value = my_dict.setdefault(‘a’, 10) print(value) # Output: 1 # Adding a new key with a default value value = my_dict.setdefault(‘c’, 3) print(value) # Output: 3 print(my_dict) # Output: {‘a’: 1, ‘b’: 2, ‘c’: 3} |
Object oriented programming (oops)
Object-Oriented Programming (OOP) is a way to organize and structure code so that it’s easier to understand, reuse, and maintain
OOP allows to model real-world things using classes and objects
Key Concepts of OOP:
- Class
- A class is like a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have
- For example, think of a class as a blueprint for a car. It defines what a car is (attributes like color, brand, model) and what it can do (methods like drive, stop)
class Car:
def __init__(self, color, brand, model):
self.color = color
self.brand = brand
self.model = model
def drive(self):
print(f”The {self.color} {self.brand} {self.model} is driving.”)
def stop(self):
print(f”The {self.color} {self.brand} {self.model} has stopped.”)
- Object
- An object is an instance of a class. If a class is the blueprint, then an object is the actual car built from the blueprint
- We can create multiple objects from a single class, each with its own unique properties
my_car = Car(“red”, “Toyota”, “Corolla”)
my_car.drive() # Output: The red Toyota Corolla is driving.
my_car.stop() # Output: The red Toyota Corolla has stopped.
- Attributes
- Attributes are the properties of an object
- They represent the state or data of an object
- In the Car class, attributes are color, brand, and model
- Methods
- Methods are the functions defined inside a class that describe the behaviors of an object. In the Car class, drive and stop are methods
- Inheritance
- Inheritance is a way to create a new class from an existing class
- The new class, called the child class, inherits the attributes and methods of the existing class, called the parent class
- This allows for code reuse and the creation of a hierarchical relationship between classes
class ElectricCar(Car):
def __init__(self, color, brand, model, battery_capacity):
super().__init__(color, brand, model)
self.battery_capacity = battery_capacity
def charge(self):
print(f”The {self.color} {self.brand} {self.model} is charging its {self.battery_capacity} kWh battery.”)
my_electric_car = ElectricCar(“blue”, “Tesla”, “Model S”, 100)
my_electric_car.drive() # Output: The blue Tesla Model S is driving.
my_electric_car.charge() # Output: The blue Tesla Model S is charging its 100 kWh battery.
- Encapsulation
- Encapsulation is the concept of bundling data (attributes) and methods that operate on the data into a single unit or class
- It also involves restricting access to certain details of an object to protect its integrity
- In Python, you can indicate that an attribute is private by prefixing it with an underscore (_)
class Car:
def __init__(self, color, brand, model):
self._color = color # Private attribute
def get_color(self):
return self._color
def set_color(self, new_color):
self._color = new_color
my_car = Car(“red”, “Toyota”, “Corolla”)
print(my_car.get_color()) # Output: red
my_car.set_color(“blue”)
print(my_car.get_color()) # Output: blue
- Polymorphism
- Polymorphism allows methods to do different things based on the object it is acting upon, even if they share the same name
- This is often achieved through method overriding, where a child class provides a specific implementation of a method that is already defined in its parent class
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return “Woof!”
Example:
Class: Define a class called Person with attributes like name, age, and gender, and methods like introduce and birthday.
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def introduce(self):
print(f”Hi, my name is {self.name}. I am {self.age} years old and I am {self.gender}.”)
def birthday(self):
self.age += 1
print(f”Happy birthday {self.name}! You are now {self.age} years old.”)
Object: Create instances of the Person class (objects) and call their methods.
# Create a person object
person1 = Person(“Alice”, 30, “female”)
# Call the introduce method
person1.introduce()
# Output: Hi, my name is Alice. I am 30 years old and I am female.
# Call the birthday method
person1.birthday()
# Output: Happy birthday Alice! You are now 31 years old.
# Create another person object
person2 = Person(“Bob”, 25, “male”)
# Call the introduce method
person2.introduce()
# Output: Hi, my name is Bob. I am 25 years old and I am male.
- Class: Person is the class.
- Attributes: name, age, and gender are attributes of the Person class.
- Methods: introduce and birthday are methods of the Person class.
- Objects: person1 and person2 are instances (objects) of the Person class.