Python Fundamentals for Data Analytics, Lecture notes of Structural Analysis

After completing thus unit, you will be able to: • Understand the fundamental principles of Python programming, including data structures, data types, and operators. Learn how to effectively use tuples, lists, dictionaries, and other essential data structures to store, manipulate, and organize data efficiently. • Delve into the world of event-driven programming, learning how to create programs that respond dynamically to user interactions. • Develop a clear comprehension of variable scopes, differentiating between local and global variables. • Discover how to design modular, reusable, and organized code using OOP principles. • Learn how to manipulate files efficiently, paving the way for data storage and retrieval.

Typology: Lecture notes

2024/2025

Uploaded on 12/14/2025

ashish-zade
ashish-zade 🇮🇳

1 document

1 / 67

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Unit 1- Python Fundamentals for Data
Analytics
Unit Objectives
Introduction
Learning Outcomes
1.1 Python data structures
1.2 Data Types
1.3 Tuples
1.4 Operators, Event-Driven Programming
1.5 local and global variables
1.6 buttons and input fields - The canvas
1.7 static drawing, Timers
1.8 interactive drawing
1.8.1 Lists
1.8.2 Keyboard input
1.8.3 Motion
1.9 Positional/Velocity Control
1.9.1 Mouse Inputs
1.9.2 More Lists
1.9.3 Dictionaries
1.10 Control Statements
1.11 Functions
1.12 Object Oriented programming concepts using classes
1.13 Objects and Methods
1.14 Exception Handling
1.15 Implementation of user-defined Modules and Package
1.16 File handling in python
1.17 Summary
1.18 Keywords
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43

Partial preview of the text

Download Python Fundamentals for Data Analytics and more Lecture notes Structural Analysis in PDF only on Docsity!

Unit 1- Python Fundamentals for Data

Analytics

Unit Objectives Introduction Learning Outcomes 1.1 Python data structures 1.2 Data Types 1.3 Tuples

1.4 Operators, Event-Driven Programming

1.5 local and global variables 1.6 buttons and input fields - The canvas 1.7 static drawing, Timers 1.8 interactive drawing 1.8.1 Lists 1.8.2 Keyboard input 1.8.3 Motion

1.9 Positional/Velocity Control

1.9.1 Mouse Inputs

1.9.2 More Lists

1.9.3 Dictionaries

1.10 Control Statements

1.11 Functions

1.12 Object Oriented programming concepts using classes

1.13 Objects and Methods

1.14 Exception Handling

1.15 Implementation of user-defined Modules and Package

1.16 File handling in python

1.17 Summary 1.18 Keywords

Unit Objectives After completing thus unit, you will be able to:

  • Understand the fundamental principles of Python programming, including data structures, data types, and operators. Learn how to effectively use tuples, lists, dictionaries, and other essential data structures to store, manipulate, and organize data efficiently.
  • Delve into the world of event-driven programming, learning how to create programs that respond dynamically to user interactions.
  • Develop a clear comprehension of variable scopes, differentiating between local and global variables.
  • Discover how to design modular, reusable, and organized code using OOP principles.
  • Learn how to manipulate files efficiently, paving the way for data storage and retrieval. Introduction Python programming is exciting! In this extensive section, we will learn about Python data structures, data types, and basic programming ideas. We'll teach you Python's fundamentals so you can write powerful programmes. Start by diving into Python data structures and types. Any Python programme relies on these fundamentals to organise, store, and modify data. We'll learn about tuples, which group similar values. Additionally, you will learn operators, which allow you to conduct numerous data operations and release the entire potential of your programmes. We'll introduce event-driven programming, which lets programmes react dynamically to user actions. You will learn how local and global variables affect programme behaviour. Discover the power of buttons and input fields in graphical user interfaces (GUIs) to develop interactive and user-friendly apps. The canvas of learning increases more. Static and interactive drawing will be explored to create visual wonders using code. Timers will help you manage time-sensitive jobs, and keyboard input will let your programmes respond to keystrokes. We'll unlock mouse input's secrets to create programmes that respond to user input precisely. Lists and dictionaries will help you understand control statements and functions. You will learn about Object-Oriented Programming (OOP), where classes, objects, and methods structure complicated programmes. Your skills include gracefully handling exceptions, ensuring your programmes are strong even in difficult scenarios. Prepare to explore Python modules and packages, the building blocks of modular code. File handling lets your programme read and write files, boosting its memory capacities. Mastering programming is the goal of this class, not only Python syntax. By the end of this adventure, you will have a solid Python foundation to solve problems, build unique solutions,

In Python, a data structure is a way to organize and store data in a particular format, allowing efficient manipulation and retrieval of that data. Different types of data structures are used depending on the requirements of the problem you're trying to solve. Python offers a variety of built-in data structures, each with its own characteristics and use cases. Let's delve into some of the main types of data structures in Python:

1. Lists: Lists are ordered collections of items that can hold various data types. They are mutable, which means you can modify their contents after creation. Lists are enclosed in square brackets ‘[ ]’ and items are separated by commas. Here's an example: numbers = [1, 2, 3, 4, 5] fruits = ['apple', 'banana', 'cherry'] mixed = [1, 'hello', 3.14, True] empty_list = [] 2. Tuples: A tuple is another type of data structure in Python, similar to a list. However, tuples are immutable, meaning their elements cannot be changed after they are created. Tuples are often used to group related data together. They are enclosed in parentheses ( ) and elements within the tuple are separated by commas. 3. Sets: Sets are unordered collections of unique elements. They are commonly used for membership testing and to eliminate duplicate values. my_set = {1, 2, 3, 'apple', 'banana'} 4. Dictionaries: Dictionaries are key-value pairs where each key maps to a value. They are useful for storing and retrieving data quickly based on keys. my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'} 5. Strings: Strings are sequences of characters and are commonly used to store and manipulate text data. my_string = "Hello, world!" 6. Lists, Tuples, and Dictionaries comprehensions:

Python allows you to create new lists, tuples, and dictionaries using comprehensions, which provide a concise way to generate these data structures. squares = [x ** 2 for x in range(10)]

7. Queues and Stacks (using collections module): The collections module provides implementations of data structures like deque (double-ended queue) that can act as both queues and stacks. from collections import deque my_queue = deque() my_queue.append(1) # Enqueue my_queue.popleft() # Dequeue These are just some of the core data structures in Python. Depending on your use case, you might also encounter more specialized data structures from external libraries, such as NumPy arrays for numerical operations, pandas DataFrames for data manipulation, and more. 1.2 Data Types Python has many built-in data types for building complicated programmes. Fundamental data types like integers, floats, and booleans represent numeric and truth values. Booleans represent truth values (True or False) and are utilised for logical comparisons and flow control. Python has sequence data types like lists, tuples, and strings. Mutable lists allow dynamic addition, removal, and alteration. Tuples, on the other hand, are immutable sequences, commonly used to group related data. Strings are sequences of characters, used to represent textual information and support various string manipulation methods. Lastly, there are mapping and set data types. Dictionaries (dict) are used for key-value pairs, enabling efficient data retrieval through keys. Sets are collections of unique elements, facilitating tasks like membership testing and eliminating duplicates from data. These data types collectively empower Python programmers to efficiently handle a wide range of data and solve diverse programming challenges. In Python, data types are classifications that categorize and define the type of values that variables can hold. Python is a dynamically-typed language, which means you don't need to explicitly declare the data type of a variable; it's determined at runtime based on the value assigned to it. Python offers a variety of built-in data types to handle different types of data efficiently. Here are some of the most common data types in Python:

my_dict = {"name": "Alice", "age": 30, "city": "Wonderland"}

4. Set Types: a. set: Represents unordered collections of unique elements. b. frozenset: Represents immutable sets. my_set = {1, 2, 3, 4, 4} # Contains only unique elements: {1, 2, 3, 4} my_frozenset = frozenset([2, 3, 4]) 5. Boolean Type: a. bool: Represents boolean values, either True or False. is_true = True is_false = False 6. None Type: a. NoneType: Represents the absence of a value or a null value. empty_value = None Python's built-in type() function can be used to determine the data type of a variable: value = 42 print(type(value)) # Output: It's important to understand these data types as they impact how you manipulate and interact with data in your Python programs. Python also allows for type conversion, which lets you change the type of a value, often through built-in functions like int(), float(), str(), etc.

  1. Dictionaries (dict): Dictionaries are unordered collections of key-value pairs, where keys are unique and associated with values. student = {"name": "Bob", "age": 20, "grade": "A"} car = {"make": "Toyota", "model": "Camry", "year": 2023} 1.3 Tuples Introduction to Tuples: In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning their elements cannot be modified after creation. Tuples are created by enclosing a comma-separated sequence of values within parentheses. For instance, (1, 2, 3) is a tuple containing three elements. Tuples can store elements of different data types

and are particularly useful when you want to group related data together while ensuring that the data remains unchanged. Usage and Importance of Tuples: Tuples have several important use cases due to their immutability. One primary use is in scenarios where you want to represent a collection of values that should remain constant throughout the program's execution. This makes tuples suitable for holding data that should not be accidentally modified, such as coordinates, configuration settings, or keys in dictionaries. Tuples are also used to return multiple values from functions, as they provide a convenient way to bundle and pass around related data without the risk of modification. Tuples in Python are essential data structures due to their immutability and versatility. They provide a convenient way to bundle and manage related data while ensuring that the data remains constant. Tuples are commonly used for scenarios like representing coordinates, returning multiple values from functions, and creating dictionary keys with composite values. By grasping the concept of tuples and understanding their significance, Python programmers can write more efficient and robust code for various tasks. Tuples are an essential part of Python's data structures, offering immutability, efficient memory usage, and various applications. Their use cases range from representing unchangeable data to returning multiple values from functions and creating dictionary keys. Understanding how to create, manipulate, and use tuples effectively can significantly enhance your ability to write clean, efficient, and reliable Python code. Example 1: Coordinates: Consider representing 2D coordinates. These coordinates consist of an x and y value that should remain unchanged together. Using a tuple, you can create a coordinate tuple and prevent accidental changes: coordinate = (3, 4) # This is a tuple

Example 6: Immutable Data for Safety: Tuples are often used in situations where data integrity is crucial. Since tuples are immutable, they can't be modified accidentally. This property makes tuples suitable for cases where you want to pass data between different parts of your program without worrying about unintended changes: _settings = ("high", 60) # Game settings: difficulty and framerate

Later in the code

settings[1] = 30 # This would result in an error due to immutability_

Example 7: Named Tuples: Python provides the collections.namedtuple class, which is a subclass of tuple. Named tuples allow you to give names to the elements within the tuple, making the code more readable and self-explanatory. They combine the benefits of tuples and dictionaries: _from collections import namedtuple

Define a named tuple class

Person = namedtuple("Person", ["name", "age", "occupation"])

Create an instance of the named tuple

person = Person("Alice", 28, "Doctor") print(person.name, person.age)_ 1.4 Operators, Event-Driven Programming

Operators in Python Programming: In Python programming, operators are symbols that

represent computations or operations to be performed on operands, which can be

variables, constants, or expressions. Python supports a wide range of operators that

facilitate various types of calculations and manipulations. These operators are categorized

into different types: arithmetic, comparison, logical, assignment, bitwise, membership, and

identity operators.

  • Arithmetic operators (+, - , *, /, %, //) are used for basic mathematical calculations.

For example, x + y adds the values of x and y.

x = 10

y = 3

addition = x + y # 10 + 3 = 13

subtraction = x - y # 10 - 3 = 7

multiplication = x * y # 10 * 3 = 30

division = x / y # 10 / 3 = 3.333...

modulo = x % y # 10 % 3 = 1

floor_division = x // y # 10 // 3 = 3 (floor division)

exponentiation = x ** y # 10 ** 3 = 1000

  • Comparison operators (==, !=, <, >, <=, >=) are used to compare values. For instance,

a == b checks if a is equal to b.

a = 5

b = 8

equal = a == b # False

not_equal = a != b # True

greater_than = a > b # False

less_than = a < b # True

greater_than_equal = a >= b # False

less_than_equal = a <= b # True

  • Logical operators (and, or not) are used for logical operations. x and y returns True

if both x and y are True.

p = True

q = False

logical_and = p and q # False

logical_or = p or q # True

logical_not_p = not p # False

logical_not_q = not q # True

  • Assignment operators (=, +=, - =, *=, /=) are used to assign values to variables. x += 5

is equivalent to x = x + 5.

x = 5 # Assigns the value 5 to x

x += 3 # Equivalent to x = x + 3 (x is now 8)

x - = 2 # Equivalent to x = x - 2 (x is now 6)

x *= 4 # Equivalent to x = x * 4 (x is now 24)

x /= 6 # Equivalent to x = x / 6 (x is now 4.0)

x %= 3 # Equivalent to x = x % 3 (x is now 1.0)

x //= 2 # Equivalent to x = x // 2 (x is now 0.0)

x **= 5 # Equivalent to x = x ** 5 (x is still 0.0)

  • Bitwise operators (&, |, ^, ~, <<, >>) perform operations at the bit level. a & b

performs a bitwise AND operation on a and b.

a = 5 # Binary: 0101

decisions based on comparisons, and perform complex calculations. For instance, arithmetic operators are essential for numerical computations, while logical operators are vital for implementing conditional statements. Event-Driven Programming is important as it enables the creation of interactive and user- friendly applications. It allows developers to build software that responds in real-time to user actions, creating a more engaging user experience. For instance, in a game, event-driven programming allows the game to react to player inputs immediately, enhancing gameplay. In a web application, event-driven programming enables dynamic updates without requiring the user to refresh the page. By combining event-driven programming with operators, you can create sophisticated applications that respond intelligently to user inputs. For example, in a drawing application, you can use event-driven programming to respond to mouse movements and clicks. Operators can then be applied to manipulate the drawn shapes, change colors, or adjust sizes based on these events. In conclusion, operators and event-driven programming are fundamental concepts in Python programming that empower developers to build versatile, interactive, and dynamic applications. Understanding operators allows for effective data manipulation and decision- making, while event-driven programming ensures applications can respond seamlessly to user inputs, ultimately enhancing the overall user experience. Example: Using Operators and Event-Driven Programming in Python: Let's consider a simple example of a calculator application built using event-driven programming and operators. We'll use the Tkinter library to create a basic GUI calculator that performs arithmetic calculations based on user inputs. import tkinter as tk def on_button_click(number): current = entry.get() entry.delete(0, tk.END) entry.insert(0, current + str(number)) def calculate(): expression = entry.get() result = eval(expression) entry.delete(0, tk.END) entry.insert(0, result) def clear(): entry.delete(0, tk.END)

root = tk.Tk() root.title("Simple Calculator") entry = tk.Entry(root, width=30, borderwidth=5) entry.grid(row=0, column=0, columnspan=4) buttons = [ ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3), ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3), ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3), ] for button_text, row, col in buttons: button = tk.Button(root, text=button_text, padx=20, pady=20, command=lambda text=button_text: on_button_click(text)) button.grid(row=row, column=col) clear_button = tk.Button(root, text="Clear", padx=20, pady=20, command=clear) clear_button.grid(row=5, column=0, columnspan=4) root.mainloop() In this example, we've created a simple calculator GUI using Tkinter. The calculator responds to button clicks by appending the clicked number/operator to the input expression. The on_button_click function handles the button clicks, while the calculate function evaluates the expression and displays the result in the entry field. The use of operators like +, - , *, and / enables arithmetic calculations, while the event-driven nature of the GUI allows the user to interactively input values and see the results instantly. Operators and event-driven programming are both vital concepts in Python programming. Operators empower you to perform various operations on data, while event-driven programming allows you to create interactive and responsive applications. Combining these concepts, as demonstrated in the calculator example, enables you to build dynamic and user- friendly software that responds intelligently to user inputs. Whether you're developing GUI applications, games, or web applications, a solid understanding of operators and event-driven programming is essential for creating engaging and effective software solutions. Benefits of Operators and Event-Driven Programming: Operators and event-driven programming are two foundational concepts that contribute significantly to the versatility and functionality of Python applications. Operators facilitate data manipulation and decision-making, while event-driven programming enables the creation of interactive, user-centric applications. By mastering these concepts and their practical implementation, developers can create software that not only performs tasks

1.5 local and global variables In Python, local and global variables are fundamental concepts in programming that dictate the scope and visibility of variables within a program. These concepts play a crucial role in managing data and maintaining a structured codebase. Local variables are those that are declared within a specific function or block of code and are only accessible within that particular scope. They are created when the function is called and are destroyed when the function completes its execution. Local variables provide isolation and encapsulation, preventing unintended interactions between different parts of the code. Here's an example to illustrate this: _def example_function(): local_var = 10 print(local_var) example_function()

Output: 10_

In this example, local_var is a local variable within the example_function. It cannot be accessed outside of this function. Global variables , on the other hand, are declared outside of any function or block and can be accessed from any part of the code, including within functions. They have a broader scope and can be useful for storing data that needs to be shared across different parts of a program. However, using global variables excessively can lead to code complexity and potential bugs. Here's a global variable example: _global_var = 20 def another_function(): print(global_var) another_function()

Output: 20_

In this case, global_var is accessible within the another_function even though it's defined outside of it. It's important to note that if you want to modify a global variable from within a function, you need to use the global keyword to indicate that you are referring to the global variable, not creating a new local variable with the same name. Here's an example: global_var = 20 def modify_global(): global global_var

_global_var += 10 modify_global() print(global_var)

Output: 30_

In this example, the global keyword ensures that the function modifies the existing global variable, rather than creating a new local variable. To avoid potential naming conflicts and improve code clarity, it's a good practice to use different names for local and global variables. In cases where a local variable shares its name with a global variable, the local variable takes precedence within its scope. This is known as variable shadowing. Consider this example: value = 5 # Global variable def shadow_example(): value = 10 # Local variable, shadows the global 'value' print(value) # Prints the local 'value' shadow_example() print(value) # Prints the global 'value' In this example, the local variable value within the shadow_example function shadows the global variable value within the function's scope. The output will be: 10 5 In addition to local and global variables, there's also the concept of nonlocal variables. These variables are used within nested functions, where you want to modify a variable from an enclosing (but non-global) scope. The nonlocal keyword is used to indicate that a variable should refer to the nearest enclosing scope that is not global. Here's an example: def outer_function(): outer_var = 15 def inner_function(): nonlocal outer_var outer_var += 5 print(outer_var) inner_function() outer_function() In this example, the nonlocal keyword allows the inner_function to modify the outer_var from the enclosing outer_function, rather than creating a new local variable.

  • Output and Interaction: When you run the Python script, a GUI window will appear with the button and input field you defined. Users can input text into the field, and when the button is clicked, the entered text will be retrieved and printed to the console.
  • Types of Buttons and Input Fields: Buttons in Tkinter can come in different types, such as standard buttons, checkbuttons, and radiobuttons. Checkbuttons allow users to toggle between selected and deselected states, while radiobuttons allow users to select one option from a group of options. These variations can be created using tk.Checkbutton() and tk.Radiobutton() classes. Input fields can also be customized. You can set default values, restrict input to specific formats (e.g., numbers only), and add validation to ensure correct data entry. This enhances the user experience and ensures data integrity.
  • Further Customization and Styling: Tkinter allows you to style and customize the appearance of buttons and input fields. You can set colors, fonts, and sizes to match your application's design. Additionally, you can bind events to buttons and input fields. For instance, you can bind the Enter key press event to trigger the same action as clicking the button.
  • Output Display and Widgets Interaction: The output of the example we've discussed might look like a simple window with a button and an input field. When you run the code and interact with the GUI, you'll see the text you entered in the input field being printed to the console when the button is clicked. This interaction is a basic demonstration of how user input can be processed and displayed.
  • Building More Complex Applications: The example provided is just the tip of the iceberg. As you become more familiar with GUI programming, you can build more complex applications with multiple windows, menus, dialog boxes, and other interactive elements. GUI programming is an essential skill when creating user-friendly applications that provide intuitive ways for users to interact with your software.
  • GUI Best Practices: When designing GUIs, it's crucial to follow user experience (UX) and user interface (UI) design principles. This includes ensuring consistency in layout, using clear labels for buttons and input fields, providing helpful tooltips, and creating responsive designs that work well on different screen sizes.
  • Layout Management: In GUI programming, proper layout management is essential to ensure that your interface looks organized and is responsive. Tkinter provides different layout managers like pack(), grid(), and place() to help you arrange widgets on the

canvas. The pack() manager organizes widgets in a linear fashion, grid() allows you to create a grid-like structure, and place() offers precise control over widget placement.

  • Event Handling: GUIs are interactive, and event handling is a fundamental aspect. Buttons and input fields generate events when users interact with them, such as clicking a button or pressing the Enter key. Tkinter allows you to bind functions to these events using the bind() method. This way, you can define custom actions based on user actions, enhancing the user experience.
  • Dialog Windows and Feedback: Beyond buttons and input fields, GUIs often require dialog windows for tasks like displaying messages, asking for confirmation, or getting file selections. Tkinter provides predefined dialog boxes through the tkinter.simpledialog and tkinter.filedialog modules, making it easy to gather user input and provide feedback.
  • Combining Widgets and Application State: Sophisticated GUI applications involve combining various widgets to create a coherent user interface. You can use frames to group related widgets, tabs to organize content, and canvas widgets for custom graphics. Maintaining the application state becomes important as the user interacts with different elements. Global variables or a class-based approach can be used to store and manage this state.
  • Internationalization and Accessibility: Consideration for internationalization (i18n) and accessibility (a11y) is crucial when designing GUIs. Tkinter supports the use of Unicode for international characters. Additionally, providing proper labels, tooltips, and alternate text for images ensures that your application is usable by a wider audience, including those with disabilities.
  • Debugging and Testing: As GUI applications grow in complexity, debugging and testing become vital. GUI testing tools like pytest-tk can help automate the testing of your interface, ensuring that it functions correctly. Debugging GUI applications might require identifying event handling issues, layout problems, or issues related to widget interaction.
  • Beyond Basic Widgets: In advanced GUI development, you might encounter more complex widgets like canvas for custom drawings, treeviews for displaying hierarchical data, and text widgets for formatted text input. These widgets expand your toolkit and enable you to create sophisticated applications with rich functionality.
  • Third-Party Libraries and Modern Approaches: While Tkinter is a widely used library for GUI programming, there are other libraries like PyQt and wxPython that offer more advanced features and modern design patterns. These libraries might require more