1. Introduction to Python Language
Python is a popular, high-level programming language known for its readability and simplicity. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant indentation. It's a versatile language used for web development, data analysis, artificial intelligence, scientific computing, and more. Python's extensive standard library and supportive community make it a preferred choice for beginners and professionals alike.
# Numeric types num_int = 10 num_float = 3.14 num_complex = 2 + 3j # Boolean types bool_true = True bool_false = False # Compound types list_example = [1, 2, 3, 4] tuple_example = (1, 2, 3, 4) dict_example = {'a': 1, 'b': 2, 'c': 3} # Print the data types print("Numeric types:") print(type(num_int)) print(type(num_float)) print(type(num_complex)) print("\nBoolean types:") print(type(bool_true)) print(type(bool_false)) print("\nCompound types:") print(type(list_example)) print(type(tuple_example)) print(type(dict_example))
# Input and Output Operations # Input name = input("Enter your name: ") age = int(input("Enter your age: ")) # Output print("Hello, " + name + "! You are " + str(age) + " years old.")
# Looping with break and continue numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("Loop with break:") for num in numbers: if num == 5: break # exit the loop when num equals 5 print(num) print("\nLoop with continue:") for num in numbers: if num % 2 == 0: continue # skip even numbers print(num)
2. Functions in Python.
Functions in Python are reusable blocks of code designed to perform a specific task. They help in organizing code into manageable sections, enhancing readability and reusability. A function is defined using the def keyword followed by the function name and parentheses. Functions can accept parameters and return values. They are crucial in breaking down complex problems into simpler, modular pieces, making the code easier to understand and maintain.
# Function definition def greet(name): """ This function greets the user. """ print("Hello,", name) # Using the function greet("Alice") greet("Bob")
# Using built-in functions numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] # Finding the length of a list print("Length of numbers:", len(numbers)) # Finding the maximum and minimum values print("Maximum number:", max(numbers)) print("Minimum number:", min(numbers)) # Summing up the elements of the list print("Sum of numbers:", sum(numbers)) # Sorting the list sorted_numbers = sorted(numbers) print("Sorted numbers:", sorted_numbers)
# Lambda function to calculate square of a number square = lambda x: x ** 2 # Using the lambda function print("Square of 5:", square(5)) # Lambda function to check if a number is even is_even = lambda x: x % 2 == 0 # Using the lambda function print("Is 10 even?", is_even(10)) print("Is 7 even?", is_even(7))
3. Array and String in Python.
In Python, arrays are used to store multiple values in a single variable, but the standard library does not include a built-in array data type; instead, lists or the array module are used. Strings are sequences of characters enclosed in quotes. Python provides various methods to manipulate strings, such as slicing, concatenation, and formatting. Strings are immutable, meaning their values cannot be changed once created.
# Importing the array module import array # Creating an array of integers int_array = array.array('i', [1, 2, 3, 4, 5]) # Accessing elements using indexing print("First element:", int_array[0]) print("Second element:", int_array[1]) # Accessing elements using slicing print("First three elements:", int_array[:3]) print("Last two elements:", int_array[-2:])
# String declaration my_string = "Hello, World!" # String operations print("Original string:", my_string) print("Uppercase:", my_string.upper()) print("Lowercase:", my_string.lower()) print("Replace 'World' with 'Python':", my_string.replace("World", "Python")) # String properties print("Length of the string:", len(my_string)) print("Does the string start with 'Hello'? ", my_string.startswith("Hello")) print("Does the string end with 'World!'? ", my_string.endswith("World!")) # String indexing and slicing print("First character:", my_string[0]) print("Last character:", my_string[-1]) print("Substring (first 5 characters):", my_string[:5])
# Membership operators fruits = ["apple", "banana", "cherry"] print("Is 'apple' in the list of fruits?", "apple" in fruits) print("Is 'orange' not in the list of fruits?", "orange" not in fruits) # Identity operators a = 10 b = 10 c = a print("Is 'a' identical to 'b'? ", a is b) print("Is 'a' not identical to 'b'? ", a is not b) # Changing the value of b b = 20 print("After changing b, is 'a' identical to 'b'? ", a is b) print("Is 'a' identical to 'c'? ", a is c)
# Importing the numpy module import numpy as np # Creating a 1-dimensional array one_d_array = np.array([1, 2, 3, 4, 5]) # Creating a 2-dimensional array two_d_array = np.array([[1, 2, 3], [4, 5, 6]]) # Accessing elements in a 1-dimensional array print("Element at index 2 in 1D array:", one_d_array[2]) # Accessing elements in a 2-dimensional array print("Element at row 1, column 2 in 2D array:", two_d_array[1, 2]) # Slicing in 1-dimensional array print("First three elements in 1D array:", one_d_array[:3]) # Slicing in 2-dimensional array print("First row in 2D array:", two_d_array[0, :]) print("Second column in 2D array:", two_d_array[:, 1])
4. List and Tuples in Python.
Lists and tuples are data structures in Python used to store collections of items. Lists are mutable, meaning their elements can be changed, added, or removed. They are defined using square brackets. Tuples, on the other hand, are immutable and defined using parentheses. Both can store heterogeneous data types, and are widely used for organizing data.
# Creating a list my_list = [10, 20, 30, 40, 50] # Applying various functions to the list print("Original list:", my_list) # Appending an element to the list my_list.append(60) print("After appending 60:", my_list) # Inserting an element at a specific position my_list.insert(2, 25) print("After inserting 25 at index 2:", my_list) # Removing an element from the list my_list.remove(40) print("After removing 40:", my_list) # Popping an element from the list popped_element = my_list.pop() print("After popping the last element:", my_list) print("Popped element:", popped_element) # Sorting the list my_list.sort() print("After sorting:", my_list) # Reversing the list my_list.reverse() print("After reversing:", my_list) # Finding the index of an element index_of_30 = my_list.index(30) print("Index of 30:", index_of_30) # Counting occurrences of an element count_of_20 = my_list.count(20) print("Count of 20:", count_of_20)
# Aliasing original_list = [1, 2, 3, 4, 5] alias_list = original_list # aliasing the list # Modifying the alias list alias_list.append(6) print("Original list after modifying alias:", original_list) print("Alias list:", alias_list) # Cloning cloned_list = original_list[:] # cloning the list # Modifying the cloned list cloned_list.append(7) print("Original list after modifying clone:", original_list) print("Cloned list:", cloned_list)
# Creating a tuple my_tuple = (10, 20, 30, 40, 50) # Accessing elements in the tuple print("Original tuple:", my_tuple) print("First element:", my_tuple[0]) print("Last element:", my_tuple[-1]) # Trying to modify an element (should raise an error) try: my_tuple[0] = 100 # This will raise a TypeError except TypeError as e: print("Error:", e) # Demonstrating immutability # We cannot modify the elements, but we can create a new tuple new_tuple = my_tuple + (60, 70) print("New tuple after concatenation:", new_tuple)
5. Dictionaries and Sets.
Dictionaries and sets are Python data structures used to store collections of data. Dictionaries store data in key-value pairs, allowing for fast retrieval based on the key. They are defined using curly braces. Sets are unordered collections of unique elements, useful for membership testing and eliminating duplicates. They are defined using the set() function or curly braces with comma-separated elements.
# Creating a dictionary my_dict = { "name": "Alice", "age": 25, "city": "New York" } # Printing the original dictionary print("Original dictionary:", my_dict) # Accessing elements by key print("Name:", my_dict["name"]) print("Age:", my_dict["age"]) # Adding a new key-value pair my_dict["email"] = "alice@example.com" print("After adding email:", my_dict) # Updating the value of an existing key my_dict["age"] = 26 print("After updating age:", my_dict) # Removing a key-value pair using pop removed_value = my_dict.pop("city") print("After removing city:", my_dict) print("Removed value:", removed_value) # Checking if a key exists if "name" in my_dict: print("The key 'name' exists in the dictionary.") # Getting all keys keys = my_dict.keys() print("All keys:", keys) # Getting all values values = my_dict.values() print("All values:", values) # Getting all key-value pairs items = my_dict.items() print("All key-value pairs:", items) # Clearing the dictionary my_dict.clear() print("After clearing:", my_dict)
# Creating sets set_a = {1, 2, 3, 4, 5} set_b = {4, 5, 6, 7, 8} # Printing the original sets print("Set A:", set_a) print("Set B:", set_b) # Adding an element to a set set_a.add(6) print("Set A after adding 6:", set_a) # Removing an element from a set set_a.remove(2) print("Set A after removing 2:", set_a) # Checking if an element is in a set print("Is 3 in Set A?", 3 in set_a) print("Is 2 in Set A?", 2 in set_a) # Set operations # Union union_set = set_a | set_b print("Union of Set A and Set B:", union_set) # Intersection intersection_set = set_a & set_b print("Intersection of Set A and Set B:", intersection_set) # Difference difference_set = set_a - set_b print("Difference of Set A and Set B:", difference_set) # Symmetric difference symmetric_difference_set = set_a ^ set_b print("Symmetric difference of Set A and Set B:", symmetric_difference_set) # Checking subsets and supersets print("Is Set A a subset of Set B?", set_a.issubset(set_b)) print("Is Set A a superset of Set B?", set_a.issuperset(set_b))
6. Regular Expression.
Regular expressions (regex) are sequences of characters that form search patterns, primarily used for string matching and manipulation. Python's re module provides support for regex operations. Regex is powerful for tasks like validating input, searching for patterns within text, and replacing text based on patterns. They are essential for text processing and data validation.
# String for searching and replacing operations text = "Python is a powerful programming language. Python is widely used for various purposes." # Searching operations # Find the index of the first occurrence of a substring index = text.find("Python") print("Index of 'Python':", index) # Count the number of occurrences of a substring count = text.count("Python") print("Number of occurrences of 'Python':", count) # Replacing operations # Replace all occurrences of a substring with another substring new_text = text.replace("Python", "Java") print("After replacing 'Python' with 'Java':", new_text)
# Importing the BeautifulSoup module for parsing HTML from bs4 import BeautifulSoup # HTML content html_content = """Sample HTML Page Welcome to my website
This is a sample HTML page.
- Item 1
- Item 2
- Item 3
7. Date and Time in Python.
Python's datetime module provides classes for manipulating dates and times. It allows for date arithmetic, formatting, and parsing. The datetime module supports various functionalities like getting the current date and time, converting between different date formats, and performing time zone conversions. This is crucial for applications requiring date and time manipulations, such as logging and scheduling.
# Importing necessary modules import datetime import calendar # Comparing Dates date1 = datetime.date(2023, 5, 15) date2 = datetime.date(2023, 5, 20) # Comparing dates if date1 < date2: print("Date 1 is before Date 2") elif date1 > date2: print("Date 1 is after Date 2") else: print("Both dates are equal") # Implementing Calendar Module # Creating a calendar for a specific month year = 2023 month = 5 print("\nCalendar for May 2023:") print(calendar.month(year, month)) # Determining the first weekday of a month (0 - Monday, 6 - Sunday) first_weekday = calendar.weekday(year, month, 1) print("First weekday of May 2023:", first_weekday) # Determining the number of days in a month num_days = calendar.monthrange(year, month)[1] print("Number of days in May 2023:", num_days)
8. Using Ipython.
IPython is an enhanced interactive Python shell that provides a rich toolkit to help you make the most out of using Python interactively. It offers powerful introspection, additional shell syntax, tab completion, and rich history. IPython is widely used in data science for interactive data analysis, providing an efficient environment for exploratory computing.
HeaderUsing IPython, Jupyter Notebook & Debugging IPython:
Steps to Use IPython:
1.Install IPython if you haven't alreadyUse the code provide below in your terminal OR Open cmd propmt or bash to use the below provided code.
bash or cmdpip install ipython2.Open a terminal or command prompt.3.Type ipython and press Enter to start the IPython interactive shell.4.You can now execute Python code directly in the IPython shell..
Steps to Debugging Errors in IPython:
1.Identify the error message displayed in the IPython shell.2.Determine which line of your code is causing the error.3.Use IPython's %debug magic command to enter the interactive debugger:Python%debug4.Once in the debugger, you can inspect variables, navigate through the code, and identify the source of the error.
Steps to Use Jupyter Notebook:
1.Install Jupyter Notebook if you haven't alreadyUse the code provide below in your terminal OR Open cmd propmt or bash to use the below provided code.
bash or cmdpip install jupyterlab2.Open a terminal or command prompt.3.Navigate to the directory where you want to store your Jupyter Notebook files.4.Type jupyter notebook and press Enter.5.Your default web browser will open, showing the Jupyter Notebook dashboard.6.Click on New and select Python 3 to create a new Jupyter Notebook.7.You can now write and execute Python code in cells within the notebook.
9. Using the NumPy Package.
NumPy (Numerical Python) is a fundamental package for scientific computing in Python. It provides support for arrays, matrices, and many mathematical functions to operate on these data structures. NumPy enables efficient numerical computations and is the foundation for many other scientific computing packages in Python, making it essential for data analysis and machine learning.
# Importing NumPy import numpy as np # Creating arrays # 1D array arr_1d = np.array([1, 2, 3, 4, 5]) print("1D Array:", arr_1d) # 2D array arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("\n2D Array:") print(arr_2d) # Array properties print("\nShape of 2D Array:", arr_2d.shape) print("Number of dimensions of 2D Array:", arr_2d.ndim) print("Number of elements in 2D Array:", arr_2d.size) print("Data type of elements in 2D Array:", arr_2d.dtype) # Reshaping arrays arr_reshaped = arr_1d.reshape(5, 1) print("\nReshaped Array:") print(arr_reshaped) # Slicing arrays print("\nSliced Array:") print(arr_2d[:2, 1:]) # Array operations arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) # Element-wise addition print("\nElement-wise Addition:") print(np.add(arr1, arr2)) # Element-wise subtraction print("\nElement-wise Subtraction:") print(np.subtract(arr1, arr2)) # Element-wise multiplication print("\nElement-wise Multiplication:") print(np.multiply(arr1, arr2)) # Element-wise division print("\nElement-wise Division:") print(np.divide(arr1, arr2)) # Dot product print("\nDot Product:") print(np.dot(arr1, arr2)) # Transpose of an array print("\nTranspose of 2D Array:") print(np.transpose(arr_2d)) # Generating random numbers # Random integers random_integers = np.random.randint(low=1, high=100, size=(3, 3)) print("\nRandom Integers:") print(random_integers) # Random numbers from a normal distribution random_normal = np.random.normal(loc=0, scale=1, size=(3, 3)) print("\nRandom Numbers from Normal Distribution:") print(random_normal)
10. Using the Pandas package.
Pandas is a powerful data manipulation and analysis library for Python. It provides data structures like Series and DataFrame to handle structured data intuitively. Pandas offers numerous functions for data cleaning, transformation, and visualization. It's an indispensable tool for data analysis in Python, especially for handling large datasets and performing complex operations efficiently.
# Importing Pandas import pandas as pd # Creating a DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emma'], 'Age': [25, 30, 35, 40, 45], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia']} df = pd.DataFrame(data) print("DataFrame:") print(df) # Accessing columns print("\nColumn 'Name':") print(df['Name']) # Accessing rows print("\nRow 1:") print(df.iloc[0]) # Adding a new column df['Gender'] = ['Female', 'Male', 'Male', 'Male', 'Female'] print("\nDataFrame after adding 'Gender' column:") print(df) # Descriptive statistics print("\nDescriptive Statistics:") print(df.describe()) # Sorting by a column sorted_df = df.sort_values(by='Age') print("\nSorted DataFrame by 'Age':") print(sorted_df) # Filtering rows based on a condition filtered_df = df[df['Age'] > 30] print("\nFiltered DataFrame with Age > 30:") print(filtered_df) # Grouping data grouped_df = df.groupby('Gender').mean() print("\nGrouped DataFrame by 'Gender':") print(grouped_df) # Reading data from a CSV file csv_file_path = 'data.csv' csv_df = pd.read_csv(csv_file_path) print("\nDataFrame from CSV file:") print(csv_df) # Writing data to a CSV file output_csv_file_path = 'output_data.csv' df.to_csv(output_csv_file_path, index=False) print("\nDataFrame written to CSV file:", output_csv_file_path)