🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

M1_Variables_Data_Types_I_O Statements_Casting _and_Operators.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

GreatCerberus

Uploaded by GreatCerberus

R.V. College of Engineering

Tags

python programming data types variables programming

Full Transcript

Python Variables, Data Types, I/O Statements, Casting and Operators - Krishnan 1. Python Python is a high-level,...

Python Variables, Data Types, I/O Statements, Casting and Operators - Krishnan 1. Python Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability and a clean syntax, which makes it ideal for beginners as well as experienced programmers. 1.1. Difference between Other Programming Languages and Python: Syntax: Many programming languages have different syntax rules and conventions. For example, languages like C and Java use curly braces ({}) to denote code blocks, while Python uses indentation. Readability: Python emphasizes readability and simplicity, making it easier to write and understand code compared to some other languages. Dynamic Typing: Python is dynamically typed, meaning you don't need to declare variable types explicitly. Other languages like C++ and Java are statically typed, requiring variable types to be explicitly declared. Interpreted vs. Compiled: Python is an interpreted language, executing code line by line. Compiled languages like C and C++ translate the entire code into machine language before execution. Development Speed: Python is known for its rapid development capabilities due to its concise syntax and built-in data structures. Versatility: Python is a versatile language used in various domains such as web development, data analysis, machine learning, and automation. Community and Libraries: Python has a large and active community, with a vast ecosystem of libraries and frameworks that make it suitable for a wide range of tasks. https://orion021.github.io/krishnan_t/ 1 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 1.2. History of Python: Python was created by Guido van Rossum and first released in 1991. Guido van Rossum aimed to create a language that was easy to read and write, with a focus on code readability and simplicity. Python's name was inspired by the British comedy group Monty Python. The language went through several iterations, with Python 2.x being the predominant version for many years. Python 3.x was introduced in 2008 with various improvements and changes, leading to some backward compatibility issues. Python has since become one of the most popular programming languages globally, known for its simplicity, versatility, and readability. 2. Keywords, Identifiers and Comments 2.1. Keywords: Keywords in Python are reserved words that have special meaning and are part of the language syntax. They cannot be used as identifiers (variable names, function names, etc.) because they are reserved for specific purposes within the language. Python has a set of built-in keywords that serve various purposes, such as defining control flow, declaring functions and classes, and performing operations. Here are the keywords in Python: False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise 2.2. Identifiers: Identifiers in Python are names used to identify variables, functions, classes, modules, or other objects in a program. An identifier can consist of letters (both uppercase and lowercase), digits, and underscores, but it must start with a letter (either uppercase or lowercase) or an underscore. Python is case-sensitive, meaning myVar and MyVar are treated as different identifiers. Here are some rules for naming identifiers in Python: They cannot be used as keywords. They can contain letters (both uppercase and lowercase), digits, and underscores. They must start with a letter (either uppercase or lowercase) or an underscore. They are case-sensitive. Examples: stud_name, loopCount, a, A, a_1, my_var, noOfEmp https://orion021.github.io/krishnan_t/ 2 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 2.3. Comments: Comments in Python are non-executable statements that are used to annotate code, provide explanations, or temporarily disable certain parts of code. They are intended for human readers and are ignored by the Python interpreter during program execution. Types of Comments: Single-line Comments: Begin with the # character and extend until the end of the line. Multi-line Comments: Enclosed within triple quotes (""" or ''') and can span multiple lines. Purpose of Comments: Documentation: Provide explanations of code logic, functionality, and usage. Clarification: Make code more readable by explaining complex logic or intentions. Temporary Disabling: Temporarily deactivate certain code segments for debugging or testing purposes. Example:- # This is a single-line comment # This program calculates the area of a rectangle # Define the dimensions of the rectangle length = 10 # Length of the rectangle width = 5 # Width of the rectangle # Calculate the area of the rectangle area = length * width # Formula: length * width # Output the result print("The area of the rectangle is:", area) """ This is a multi-line comment. It provides additional explanation about the program. In this case, it explains the purpose of each section of code. """ # End of the program https://orion021.github.io/krishnan_t/ 3 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 3. Python operators and operator precedence Python Operators 3.1. Arithmetic Operators: Arithmetic operators are used to perform mathematical operations between variables or values. Addition (+) : Adds two operands. Subtraction (-) : Subtracts the second operand from the first. Multiplication (*) : Multiplies two operands. Division (/) : Divides the first operand by the second. Floor Division (//) : The division that results in the quotient rounded down to the nearest integer. Modulus (%) : Returns the remainder of the division. Exponentiation (**) : Raises the left operand to the power of the right operand. Example:- a = 10 b = 3 addition = a + b subtraction = a - b multiplication = a * b division = a / b floor_division = a // b modulus = a % b exponentiation = a ** b print("Addition:", addition) print("Subtraction:", subtraction) print("Multiplication:", multiplication) print("Division:", division) print("Floor Division:", floor_division) print("Modulus:", modulus) print("Exponentiation:", exponentiation) Output:- Addition: 13 Subtraction: 7 Multiplication: 30 Division: 3.3333333333333335 Floor Division: 3 Modulus: 1 Exponentiation: 1000 https://orion021.github.io/krishnan_t/ 4 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 3.2. Comparison Operators: Comparison operators are used to compare the values of two operands. Equal to (==) : Returns True if the operands are equal. Not equal to (!=) : Returns True if the operands are not equal. Greater than (>) : Returns True if the first operand is greater than the second. Less than (=) : Returns True if the first operand is greater than or equal to the second. Less than or equal to ( y) print("Less than:", x < y) print("Greater than or equal to:", x >= y) print("Less than or equal to:", x 3 ---------------- --------------- 01010000 (80) 00010101 (21) In left shift, each bit in the number is In right shift, each bit in the number is shifted to the left by the specified number of shifted to the right by the specified number of positions. Zeros are filled in from the right. positions. Zeros are filled in from the left. Operator Precedence Operator precedence determines the order in which operators are evaluated in an expression. In Python, as in many programming languages, operators have different levels of precedence. Operators with higher precedence are evaluated before operators with lower precedence. For example, in the expression 2 + 3 * 4, multiplication (*) has a higher precedence than addition (+), so 3 * 4 is evaluated first, resulting in 12, and then 2 + 12 is evaluated, resulting in 14. Here's a brief overview of operator precedence in Python, from highest to lowest: 1. Parentheses () 2. Exponentiation ** 3. Unary plus +, unary minus - (negation) 4. Multiplication *, division /, floor division //, modulus % 5. Addition +, subtraction - 6. Bitwise shift operators 7. Bitwise AND & 8. Bitwise XOR ^ 9. Bitwise OR | 10. Comparison operators ==, !=, =, is, is not, in, not in 11. Boolean NOT `not` 12. Boolean AND `and` 13. Boolean OR`or` Operators with the same precedence are evaluated from left to right. For example, + and - have the same precedence, so 2 + 3 - 4 is evaluated as (2 + 3) - 4. Understanding operator precedence is important for writing expressions that behave as expected and avoiding errors caused by incorrect evaluation order. https://orion021.github.io/krishnan_t/ 10 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 4. Python data types & Type Casting 4.1. Built-in Types: These are the basic data types provided by Python, and the functions mentioned above are used to create instances of these types. Examples of built-in types include integers, floats, strings, lists, tuples, dictionaries, sets, booleans, complex numbers, and ranges. 1. Numeric Types: int: Integers, whole numbers without decimal points. e.g., 5, -3, 1000. x = 5 y = -3 z = 1000 print("int examples:", x, y, z) float: Floating-point numbers, numbers with decimal points. e.g., 3.14, -0.001, 2.0. pi = 3.14 value = -0.001 height = 2.0 print("float examples:", pi, value, height) complex: Complex numbers, numbers with a real and imaginary part. e.g., 2 + 3j, -1 - 0.5j. z1 = 3 + 4j # 3 + 4i z2 = complex(2, -5) # 2 - 5i print(z1, z2) 2. Sequence Types: str: Strings, sequences of characters enclosed in quotes. e.g., "hello", 'Python', "123". message = "hello" language = 'Python' number_string = "123" print("str examples:", message, language, number_string) list: Lists, ordered collections of items enclosed in square brackets. e.g., [1, 2, 3], ['a', 'b', 'c']. numbers = [1, 2, 3] letters = ['a', 'b', 'c'] print("list examples:", numbers, letters) https://orion021.github.io/krishnan_t/ 11 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators tuple: Tuples, ordered, immutable collections of items enclosed in parentheses. e.g., (1, 2, 3), ('a', 'b', 'c'). coordinates = (1, 2, 3) vowels = ('a', 'e', 'i', 'o', 'u') print("tuple examples:", coordinates, vowels) 3. Mapping Type: dict: Dictionaries, collections of key-value pairs enclosed in curly braces, e.g., {'name': 'John', 'age': 30, 'city': 'New York'}. person = {'name': 'John', 'age': 30, 'city': 'New York'} print("dict examples:", person) 4. Set Types: set: Sets, unordered collections of unique items enclosed in curly braces. e.g., {1, 2, 3}, {'a', 'b', 'c'}. number_set = {1, 2, 3} letter_set = {'a', 'b', 'c'} print("set examples:", number_set, letter_set) frozenset: Immutable sets, similar to sets but immutable e.g., frozenset({1, 2, 3}). immutable_set = frozenset({1, 2, 3}) print("frozenset examples:", immutable_set) 5. Boolean Type & None Type: bool: Boolean values representing True or False & None: Represents absence of value or a null value. is_true = True is_false = False print("bool examples:", is_true, is_false) null_value = None print("None examples:", null_value) https://orion021.github.io/krishnan_t/ 12 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 4.2. Type Casting in Python:- Typecasting, is the process of converting one data type into another. In Python, you can perform type conversion using built-in functions or constructors. Here are some common type conversion functions: 1. int(): Converts a value to an integer. 2. float(): Converts a value to a floating-point number. 3. str(): Converts a value to a string. 4. list(): Converts a sequence (e.g., tuple, string, or range) to a list. 5. tuple(): Converts a sequence (e.g., list, string, or range) to a tuple. 6. set(): Converts a sequence (e.g., list, tuple, or string) to a set. # Integer to float int_num = 5 float_num = float(int_num) print(float_num) # Output: 5.0 # Float to integer float_num = 3.14 int_num = int(float_num) print(int_num) # Output: 3 # Integer to string int_num = 42 str_num = str(int_num) print(str_num) # Output: '42' # String to integer str_num = '123' int_num = int(str_num) print(int_num) # Output: 123 # List to tuple my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # Output: (1, 2, 3) # Tuple to list my_tuple = (4, 5, 6) my_list = list(my_tuple) print(my_list) # Output: [4, 5, 6] # String to list my_string = "hello" my_list = list(my_string) print(my_list) # Output: ['h', 'e', 'l', 'l', 'o'] # List to set my_list = [1, 2, 3, 3, 4, 5] my_set = set(my_list) print(my_set) # Output: {1, 2, 3, 4, 5} https://orion021.github.io/krishnan_t/ 13 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 5. Input & Output Statement 5.1. Input Statement and Getting Different Types of Input: The input() function is used to get input from the user. By default, the input is always treated as a string. To get input of different types (like integer or float), you can use type casting. # Getting string input name = input("Enter your name: ") # Getting integer input age = int(input("Enter your age: ")) # Getting float input height = float(input("Enter your height in meters: ")) 5.2. Output Statement with and without Variables: The print() function is used to display output to the console. You can print fixed strings or use variables to dynamically include values. # Printing fixed strings print("Hello, World!") # Printing with variables name = "Doraemon" age = 3 print("My name is", name, "and I am", age, "years old.") 5.3. Formatted Output Statement: i) % Formatting with All Types of Values: % formatting allows you to specify a format string with placeholders for variables. Syntax: "format string" % (value1, value2,...) name = "Doraemon" age = 3 print("My name is %s and I am %d years old." % (name, age)) ii) Using f-string (Formatted String Literals): Introduced in Python 3.6, f-strings provide a more concise and readable way to format strings. Syntax: f"format string {variable1} {variable2}..." name = "Doraemon" age = 3 print(f"My name is {name} and I am {age} years old.") https://orion021.github.io/krishnan_t/ 14 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 6. Lists 6.1. List Definition and Characteristics: A list in Python is an ordered collection of items that can contain elements of different data types. Here are some characteristics: Ordered: Elements in a list maintain their order, which means you can access elements by their index. Mutable: Lists are mutable, meaning you can modify, add, or remove elements after the list is created. Heterogeneous: Lists can contain elements of different data types, including integers, strings, floats, and even other lists. Indexed: Elements in a list are indexed with integers starting from 0. Dynamic: Lists can grow or shrink in size dynamically as elements are added or removed. Different types of lists: # List of integers int_list = [1, 2, 3, 4, 5] # List of strings str_list = ['apple', 'banana', 'orange'] # List of mixed data types mixed_list = [1, 'hello', True, 3.14, [5, 6, 7]] # List of lists nested_list = [[1, 2, 3], ['a', 'b', 'c'], [True, False]] # Empty list empty_list = [] 6.2. Accessing List Elements: You can access elements in a list using square brackets [] with the index of the element you want to access. Python uses zero-based indexing. Example: my_list = ['apple', 'banana', 'orange', 'grape'] print(my_list) # Output: 'apple' print(my_list) # Output: 'orange' print(my_list[-1]) # Output: 'grape' (Negative index, starts from the end) https://orion021.github.io/krishnan_t/ 15 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 6.3. List Methods List’s are having built in methods to manipulate them with different ways. 1. append(element): Description: Appends a single element to the end of the list. my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] 2. clear(): Description: Removes all elements from the list, leaving it empty. my_list = [1, 2, 3] my_list.clear() print(my_list) # Output: [] 3. copy(): Description: Returns a shallow copy of the list. my_list = [1, 2, 3] new_list = my_list.copy() print(new_list) # Output: [1, 2, 3] 4. count(element): Description: Returns the number of occurrences of a specified element in the list. my_list = [1, 2, 3, 2] count = my_list.count(2) print(count) # Output: 2 5. extend(iterable): Description: Extends the list by appending elements from the specified iterable. my_list = [1, 2, 3] my_list.extend([4, 5, 6]) print(my_list) # Output: [1, 2, 3, 4, 5, 6] 6. index(element): Description: Returns the index of the first occurrence of the specified element in the list. my_list = [1, 2, 3, 2] index = my_list.index(2) print(index) # Output: 1 https://orion021.github.io/krishnan_t/ 16 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 7. insert(index, element): Description: Inserts a single element at the specified index. my_list = [1, 2, 3] my_list.insert(1, 1.5) print(my_list) # Output: [1, 1.5, 2, 3] 8. pop(index): Description: Removes and returns the element at the specified index. my_list = [1, 2, 3] popped_element = my_list.pop(1) print(popped_element) # Output: 2 print(my_list) # Output: [1, 3] 9. remove(element): Description: Removes the first occurrence of the specified element from the list. my_list = [1, 2, 3, 2] my_list.remove(2) print(my_list) # Output: [1, 3, 2] 10. reverse(): Description: Reverses the order of the elements in the list. my_list = [1, 2, 3] my_list.reverse() print(my_list) # Output: [3, 2, 1] 11. sort(key, reverse): Description: Sorts the elements of the list in place, optionally accepting a key function to customize sorting. my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5] my_list.sort() print(my_list) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9] # Sorting in descending order my_list.sort(reverse=True) print(my_list) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1] # Custom functions def myFunc(t): return len(t) cars = ['VW', 'BMW', 'Ford', 'Mitsubishi'] cars.sort(key=myFunc) print(cars) https://orion021.github.io/krishnan_t/ 17 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 7. Tuple’s 7.1. Tuple Definition & It’s characteristics A tuple in Python is an ordered collection of elements, similar to a list, but with the key difference that tuples are immutable, meaning they cannot be modified after creation. Tuples are defined using parentheses () and can contain elements of different data types. Here are the key characteristics of tuples: 1. Ordered: Tuples maintain the order of elements as they are added. 2. Immutable: Once created, the elements of a tuple cannot be changed or modified. 3. Heterogeneous: Tuples can contain elements of different data types, including integers, floats, strings, and other tuples. 4. Indexed: Elements in a tuple can be accessed using zero-based indexing. 5. Iterative: Tuples support iteration, allowing you to loop through the elements using a for loop or other iterable methods. 6. Hashable: Tuples are hashable, meaning they can be used as keys in dictionaries and elements in sets. 7.2. Accessing Tuple values my_tuple = (1, 2, 3, 4, 5) # Accessing individual elements first_element = my_tuple second_element = my_tuple third_element = my_tuple print(first_element) # Output: 1 print(second_element) # Output: 2 print(third_element) # Output: 3 7.3. Tuple methods 1. count(value): Returns the number of occurrences of a specified value in the tuple. 2. index(value, start, end): Returns the index of the first occurrence of a specified value within a specified range of indices. # Define a tuple my_tuple = (1, 2, 3, 4, 2, 5, 2) # Using count() method count_2 = my_tuple.count(2) print("Number of occurrences of 2:", count_2) # Output: 3 # Using index() method index_4 = my_tuple.index(4) print("Index of first occurrence of 4:", index_4) # Output: 3 https://orion021.github.io/krishnan_t/ 18 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 8. Dictionary 8.1.Dictionary & Characteristics A dictionary in Python is an unordered collection of key-value pairs. 1. Key-Value Structure: Data is stored in the form of key-value pairs. 2. Unordered: Items in a dictionary are not stored in any specific order. 3. Mutable: Dictionaries can be modified after creation. 4. Key Unique: Each key in a dictionary must be unique. 5. Keys Immutable: Keys must be of an immutable data type, such as strings, integers, or tuples. 6. Values Any Type: Values in a dictionary can be of any data type, including other dictionaries. 7. Access by Key: Values in a dictionary are accessed using their corresponding keys rather than indices. 8. Dynamic Size: Dictionaries can grow or shrink in size as needed to accommodate more elements or remove existing ones. 8.2.Accessing Dictionary Elements # Define a dictionary my_dict = {"name": "John", "age": 30, "city": "New York"} # Accessing elements print(my_dict["name"]) # Output: John print(my_dict.get("age")) # Output: 30 8.3.Dictionary methods 1. clear(): Removes all items from the dictionary. my_dict = {'a': 1, 'b': 2} my_dict.clear() print("Dict Cleared:", my_dict) # Output: Dict Cleared: {} 2. copy(): Returns a shallow copy of the dictionary. my_dict = {'a': 1, 'b': 2} new_dict = my_dict.copy() print("Dict Copied:", new_dict) # Output: Dict Copied: {'a': 1, 'b': 2} 3. fromkeys(keys, value=None): Returns a new dictionary with keys from an iterable and values set to a specified value (default None). keys = ['a', 'b', 'c'] my_dict = dict.fromkeys(keys, 0) print("Dict from keys:", my_dict) # Output: Dict from keys: {'a': 0, 'b': 0, 'c': 0} https://orion021.github.io/krishnan_t/ 19 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 4. get(key, default=None): Returns the value for a specified key. If the key is not found, returns the default value (default None). my_dict = {'a': 1, 'b': 2} value = my_dict.get('d', 'Not found') print("Get value:", value) # Output: Get value: Not found 5. items(): Returns a view object that displays a list of key-value pairs as tuples. my_dict = {'a': 1, 'b': 2} items = my_dict.items() print("Items:", items) # Output: Items: dict_items([('a', 1), ('b', 2)]) 6. keys(): Returns a view object that displays a list of all keys in the dictionary. my_dict = {'a': 1, 'b': 2} keys = my_dict.keys() print("Keys:", keys) # Output: dict_keys(['a', 'b']) 7. pop(key, default): Removes and returns the value associated with the specified key. If the key is not found, returns the default value (default None). my_dict = {'a': 1, 'b': 2} value = my_dict.pop('a', 'Not found') print("Popped value:", value) # Output: Popped value: 1 8. popitem(): Removes and returns an arbitrary (key, value) pair from the dictionary. my_dict = {'a': 1, 'b': 2} pair = my_dict.popitem() print("Popped item:", pair) # Output: Popped item: ('b', 2) 9. setdefault(key, default=None): Returns the value for a specified key. If the key is not found, inserts the key with the specified default value (default None) and returns the default value. my_dict = {'a': 1, 'b': 2} value = my_dict.setdefault('c', 0) print("Setdefault value:", value) # Output: Setdefault value: 0 https://orion021.github.io/krishnan_t/ 20 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 10. update(key:value): Updates the dictionary with the key-value pairs from another dictionary or iterable. my_dict = {'a': 1, 'b': 2} my_dict.update({'c': 3, 'd': 4}) print("Updated dict:", my_dict) # Output: Updated dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4} 11. values(): Returns a view object that displays a list of all values in the dictionary. my_dict = {'a': 1, 'b': 2} values = my_dict.values() print("Values:", values) # Output: Values: dict_values([1, 2]) 9. List VS Tuple VS Dictionary Characteristic List Tuple Dictionary Mutability Mutable Immutable Mutable Syntax Defined with Defined with Defined with curly square brackets parentheses braces Order Ordered Ordered Unordered (Keys are ordered in Python 3.7+) Indexing Access by index Access by index Access by key Elements Homogeneous Homogeneous Key-value pairs or or (heterogeneous) heterogeneous heterogeneous Iteration Iteration is Iteration is Iteration over possible possible keys, values, or items Performance Slower for large Faster for Efficient key- datasets iteration based operations Memory More memory Less memory Moderate overhead overhead memory overhead https://orion021.github.io/krishnan_t/ 21 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 10. Sets 10.1. Sets & Characteristics: Sets in Python are unordered collections of unique elements. They are defined using curly braces {} and can contain various data types. Sets do not allow duplicate elements. If you try to add a duplicate element, it will be ignored. Sets are mutable, meaning you can add or remove elements from them. Sets are commonly used for membership testing, removing duplicates from a sequence, and mathematical operations like union, intersection, etc. Example: my_set = {1, 2, 3, 4, 5} print(my_set) 10.2. Accessing Set Values: Since sets are unordered, you cannot access elements using indices like you do with lists or tuples. However, you can iterate over the elements of a set using a loop, or check for membership of a specific element. Program: my_set = {1, 2, 3, 4, 5} # Iterate over the set for element in my_set: print(element) # Check membership if 3 in my_set: print("3 is present in the set") 10.3. set methods: add(): Adds an element to the set if it is not already present. my_set = {1, 2, 3} my_set.add(4) print(my_set) # Output: {1, 2, 3, 4} remove(): Removes the specified element from the set. Raises an error if the element is not present. my_set = {1, 2, 3} my_set.remove(2) print(my_set) # Output: {1, 3} discard(): Removes the specified element from the set if it is present. Unlike remove(), it does not raise an error if the element is not found. my_set = {1, 2, 3} my_set.discard(2) print(my_set) # Output: {1, 3} clear(): Removes all elements from the set. https://orion021.github.io/krishnan_t/ 22 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators my_set = {1, 2, 3} my_set.clear() print(my_set) # Output: set() union(): Returns a new set containing all the distinct elements from both sets. set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5} intersection(): Returns a new set containing the common elements between two sets. set1 = {1, 2, 3, 7} set2 = {3, 4, 5, 7} intersection_set = set1.intersection(set2) print(intersection_set) # Output: {3, 7} difference(): Returns a new set containing the elements that are present in the first set but not in the second set. set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1.difference(set2) print(difference_set) # Output: {1, 2} pop(): Removes and returns an arbitrary element from the set. If the set is empty, raises a KeyError. my_set = {1, 2, 3} popped_element = my_set.pop() print(popped_element) # Output: 1 print(my_set) # Output: {2, 3} update(): Updates the set with the union of itself and others. set1 = {1, 2, 3} set2 = {3, 4, 5} set1.update(set2) print(set1) # Output: {1, 2, 3, 4, 5} issubset(): Returns True if all elements of the set are present in the specified set, otherwise returns False. set1 = {1, 2} set2 = {1, 2, 3, 4, 5} print(set1.issubset(set2)) # Output: True issuperset(): Returns True if all elements of the specified set are present in the set, otherwise returns False. set1 = {1, 2, 3, 4, 5} set2 = {1, 2} print(set1.issuperset(set2)) # Output: True https://orion021.github.io/krishnan_t/ 23 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators intersection_update(): Updates the set with the intersection of itself and another set. set1 = {1, 2, 3, 10} set2 = {3, 4, 5, 10} set1.intersection_update(set2) print(set1) # Output: {3} symmetric_difference(): Returns a new set containing elements that are in exactly one of the sets. set1 = {1, 2, 3} set2 = {3, 4, 5} sym_diff_set = set1.symmetric_difference(set2) print(sym_diff_set) # Output: {1, 2, 4, 5} 11. Augmented assignment operators for sequence data types Augmented assignment operators are shorthand operators in Python that combine assignment with another operation, such as arithmetic or bitwise operations. They provide a concise way to perform an operation and update the value of a variable in a single step. The operator that are applicable for list is += and *=. But -=, /=, //=, **== are not supported. For List: my_list = [1, 2, 3] my_list += [4,5,6] print(my_list) # Output: [1, 2, 3, 5] my_list = [1, 2, 3] my_list *= 3 print(my_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3] For Tuples: my_list = (1, 2, 3) my_list += (4,5,6) print(my_list) # Output: (1, 2, 3, 4, 5, 6) my_list = (1, 2, 3) my_list *= 3 print(my_list) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3) Even if, Tuples are immutable, meaning their contents cannot be changed after creation. So, while the augmented assignment operators for tuples (+= and *=) create new tuples as a result of the operation, they effectively produce new tuple objects rather than modifying the existing ones. https://orion021.github.io/krishnan_t/ 24 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 12. Using dictionaries to model real-world things and 12.1. Dictionaries to Real-World objects: Dictionaries in programming are like real-world dictionaries in that they provide a way to store and retrieve information. In Python, for example, a dictionary is a collection of key-value pairs where each key is unique and associated with a value. This structure can be used to model real-world things in various ways as follows: Example 1(Employee Info) and output: Program: employee = { "id": 101, "details": { "name": "Disha", "position": "Manager", "department": "Sales", "salary": 60000, "email": "[email protected]", "phone": "12345-67890", "hire_date": "2023-05-15" } } print("Employee Information:") print("ID:", employee["id"]) print("Name:", employee["details"]["name"]) print("Position:", employee["details"]["position"]) print("Department:", employee["details"]["department"]) print("Salary:", employee["details"]["salary"]) print("Email:", employee["details"]["email"]) print("Phone:", employee["details"]["phone"]) print("Hire Date:", employee["details"]["hire_date"]) Output: "C:\Program Files\Python310\python.exe" "D:\IN Progrss\Advance Python\Others\f.py" Employee Information: ID: 101 Name: Disha Position: Manager Department: Sales Salary: 60000 Email: [email protected] Phone: 12345-67890 Hire Date: 2023-05-15 https://orion021.github.io/krishnan_t/ 25 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators Example 2(Student Info) and output: Program student = { "id": "S001", "info": { "name": "Ujwal", "grade": 9, "subjects": ["Math", "Science", "English"], "address": "123 Main St", "parent_contact": "12345-67890", "birthdate": "2010-03-21" } } print("Student Information:") print("ID:", student["id"]) print("Name:", student["info"]["name"]) print("Grade:", student["info"]["grade"]) print("Subjects:", student["info"]["subjects"]) print("Address:", student["info"]["address"]) print("Parent Contact:", student["info"]["parent_contact"]) print("Birthdate:", student["info"]["birthdate"]) Output: "C:\Program Files\Python310\python.exe" "D:\IN Progrss\Advance Python\Others\f.py" Student Information: ID: S001 Name: Ujwal Grade: 9 Subjects: ['Math', 'Science', 'English'] Address: 123 Main St Parent Contact: 12345-67890 Birthdate: 2010-03-21 https://orion021.github.io/krishnan_t/ 26 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators Example 3(An MNC) Program: zoho_corporation = { "founding_year": 1996, "founders": ["Sridhar Vembu", "Tony Thomas"], "headquarters": "Chennai, Tamil Nadu, India", "products": ["CRM software", "Email hosting", "Project management tools", "Office suite", "Invoicing software"], "offices_and_data_centers": ["India", "China", "Japan", "Europe", "United States",]} print("Zoho Corporation Information:") print("Founding Year:", zoho_corporation["founding_year"]) print("Founders:", ", ".join(zoho_corporation["founders"])) print("Headquarters:", zoho_corporation["headquarters"]) print("Products:", ", ".join(zoho_corporation["products"])) print("Offices:", ", ".join(zoho_corporation["offices_and_data_centers"])) Output: "C:\Program Files\Python310\python.exe" "D:\IN Progrss\Advance Python\Others\f.py" Zoho Corporation Information: Founding Year: 1996 Founders: Sridhar Vembu, Tony Thomas Headquarters: Chennai, Tamil Nadu, India Products: CRM software, Email hosting, Project management tools, Office suite, Invoicing software Offices: India, China, Japan, Europe, United States https://orion021.github.io/krishnan_t/ 27 | 😁 👻 ✌️ 😎 Python - Variables, Data Types, I/O Statements, Casting and Operators 12.2. Pretty Printing: Pretty printing is the process of formatting complex data structures, such as dictionaries or lists, in a visually appealing and easy-to-read manner. It helps improve the readability of the output by adding appropriate spacing, indentation, and line breaks. Program: import pprint zoho_corporation = { "founding_year": 1996, "founders": ["Sridhar Vembu", "Tony Thomas"], "headquarters": "Chennai, Tamil Nadu, India", "products": ["CRM software", "Email hosting", "Project management tools", "Office suite", "Invoicing software"], "offices_and_data_centers": ["India", "China", "Japan", "Europe" "United States",]} pprint.pprint(zoho_corporation) Output: "C:\Program Files\Python310\python.exe" "D:\IN Progrss\Advance Python\Others\f.py" {'founders': ['Sridhar Vembu', 'Tony Thomas'], 'founding_year': 1996, 'headquarters': 'Chennai, Tamil Nadu, India', 'offices_and_data_centers': ['India', 'China', 'Japan', 'EuropeUnited States'], 'products': ['CRM software', 'Email hosting', 'Project management tools', 'Office suite', 'Invoicing software']} https://orion021.github.io/krishnan_t/ 28 | 😁 👻 ✌️ 😎

Use Quizgecko on...
Browser
Browser