



























































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 67
This page cannot be seen from the preview
Don't miss anything!




























































Unit Objectives Introduction Learning Outcomes 1.1 Python data structures 1.2 Data Types 1.3 Tuples
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.17 Summary 1.18 Keywords
Unit Objectives After completing thus unit, you will be able to:
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.
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
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
Person = namedtuple("Person", ["name", "age", "occupation"])
person = Person("Alice", 28, "Doctor") print(person.name, person.age)_ 1.4 Operators, Event-Driven Programming
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()
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()
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)
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.
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.