Python Cheat SheetPython, designed by Guido van Rossum and initially launched in 1991, is among the most utilised and favoured coding languages. Its straightforward and neat grammar makes it simple for programmers to grasp and apply. Python backs object-oriented programming and is often employed for various reasons, such as Data Analysis, Machine Learning, Advanced Learning, Artificial Intelligence, Scientific Calculation, Automation, Interconnecting, Game Design, Internet Creation, and Internet Data Extraction. Whether you're a beginner or an experienced Python developer, this cheat sheet will be a handy reference for your Python journey. To help Python programmers, we've created a comprehensive Python Cheat Sheet. You'll find essential topics and concepts in this cheat sheet.
Simple Program to Print a Statement in PythonThe following is a simple program to print a statement "Hello World" in Python. Example: Output: Hello World Explanation: In the above code, we have used the print() function to display the text "Hello World". The print() function is a built-in function in Python that outputs the given message inside the braces used after the print statement. Data TypesLet's see the data types in Python and the examples to understand them clearly. StringsThese represent text data and are enclosed in single or double quotes (e.g., "Hello, World!"). Creating a String Example Output: Welcome to javaTpoint Explanation The above codes begin with the variable name greet. Next, we used the equal sign (=) to assign a value to the variable. The value assigned is the string "Welcome to javaTpoint." MethodsSee the below-mentioned string methods explained with examples: 1. To capitalize(): Converts the first character of a string to uppercase. Code: Output: Hello javatpoint! Explanation: In the above code, we have created a variable named greet and insert a value. Then, the capitalize() method is applied to capitalise each word's first letter. 2. lower() and upper(): Convert a string to lowercase or uppercase. Code: Output: david wilson DAVID WILSON Explanation: In the given program, we applied the lower() method to convert all characters to lowercase. Similarly, the upper() method converts the string into uppercase. 3. strip(): This method helps you to remove leading and trailing whitespaces from the given string. Code: Output: hello, javaTpoint! Explanation The above code explains removing whitespace characters from the string by applying the strip() method. To do this, we created a variable and stored some text. Then, another variable was created to store the result. 4. replace(): It replaces occurrences of old with new in the given string. Code: Output: I am a Data Analyst. Explanation: The above code describes replacing the given string with the other value. 5. split(): The .split() method splits the given string into a list of substrings based on the specified separator. Code: Output: ['Java', 'Python', 'PHP'] Explanation: The above code explains how to split the string into a list of substrings using a comma as the separator. 6. startswith(): This method helps you to check if the string starts with the specified prefix. Code: Output: True Explanation: In the above code, we checked if the given string starts with Hello. If the value matches, it returns True as output. 7. join(): The .join() method helps you to combine elements of an iterable into a single string using the current string as a separator. Example: Output: C, C++, Java Explanation: The above code explains how to join elements into a single string, separated by a comma (,). Numbers:Python supports integers and floating-point numbers. 1. Integers Integers are whole numbers without a decimal point. They can be positive, negative, or zero. In Python, the length of an integer value is not limited. For example, 5, -3, 0. Code: Output: Age is: 25 Explanation: The above code explains that a variable named age is created and assigned the value. Then, the string "Age is:" is printed first with the value. The comma separates the different items to be printed. 2. Floating Numbers Floats are numbers with a decimal point. They represent real numbers and have a floating-point representation. Floats are accurate up to 15 decimal places. For example: 3.14159, 4.6, -0.261. Example: Output: Value of x is: 25.54 Explanation: In the above code, we created the variable x and assigned the value 25.54 to the variable x. Then, print the value of x using the print statement. 3. Complex Numbers: Complex numbers consist of real and imaginary numbers. They are represented as (real part) + (imaginary part)j. For example, 2 + 3j, where 2 is the real part, and 3j is the imaginary part. Also, you can use the type() function to determine the data type of variables. Let's take an example: Code: Output: Type of x is: <class 'int'> Type of y is: <class 'float'> Type of z is: <class 'complex'> Explanation: In the above program, we have created x, y, and z variables and inserted them with integer, float, and complex number data type values, respectively. Then, we display the type of each variable using the type() function. Lists:Lists enable us groupings of elements where each element can store several pieces of information. Lists are created using square brackets []. It can store different data types, such as strings, numbers, and boolean values. 1. Creating a List: Here, we are creating a list consisting of some channels. Code: Output: Channels are: ['jeeTpoint', 'sscTpoint', 'cbseTpoint'] Explanation: We created a list called channels containing three strings in the above code. 2. Accessing Items: Each item in a list has an index. You can access items using their index. Let's understand it with an example: Code: Output: sscTpoint Explanation: In the above example, we created channels containing three strings. The print statement displays the channel list's second element indexed with 1. 3. Updating Items: You can change the value of an item by assigning a new value to the index. Let's see an example: Code: Output: ['jeeTpoint', 'englishTpoint', 'cbseTpoint'] Explanation: In the above code, we defined channels containing some string values and replaced the second element in the list. 4. Inserting New Values: Use the .append() method to insert an item at the ending position of the list. Code Output: ['jeeTpoint', 'sscTpoint', 'cbseTpoint', 'englishTpoint'] Explanation In the above code, we defined channels containing some string values. Then, we append the new string value using the .append method to the end of the list. Note: The new value will be added at the last position in the given list. We know the .append() method does not consider two value arguments. If you wish to add the new value at the desired index number, go with the .insert() method, as it supports two arguments at a time that allow you to add the new element at the desired location in the existing list.Using .insert() methodTo add an item at the desired position in the existing list, use the .insert() method: Code Output: ['jeeTpoint', 'englishTpoint', 'sscTpoint', 'cbseTpoint'] Explanation In the program mentioned above, we inserted two arguments. The first argument denotes an index, and the second is the value. Next, print the output using the print method. 1. Removing an ItemUsing .remove() Method: The remove() method removes a specific item from the list based on its value. Syntax Code Output: ['sscTpoint', 'cbseTpoint', 'englishTpoint'] Explanation In the above example, we created channels containing four values. Then, we use the .remove() function to remove the element from the specified index. 2. Using del Statement: The del statement deletes an item from the list by specifying its index. Syntax Code Output: ['php', 'Python', 'Java', 'C++'] Explanation In the above example section, we created a list called languages containing four string values. Then, we use the del statement to delete the element from the provided index. 3. Using List Comprehension:List comprehension enables you to create a new list while excluding specific elements. Code Output: [4, 8, 9, 5] Explanation The list comprehension [ele for ele in integers if ele != 7] creates a new list by iterating through each element in integers. After that, for each element, it checks whether it is not equal to 7. Then, check if an element is not equal to 7; those elements will be included in the new list. 4. Using .pop() MethodThe pop() method removes an item at a specified index and returns its value. The syntax is given below. Syntax Code Output: Deleted car is: Alto ['Volvo', 'Kia', 'Jaguar', 'Audi', 'Mercedes'] Explanation The above code defines a list named cars containing some string values. Then, remove the element at index number 2 using the pop() method and assign it to the variable named deleted_cars. Tuples:Tuples are similar to lists but immutable, meaning you cannot modify them after they are created. Tuples are defined using parentheses. They are typically used when you want to store a collection of values. 1. Creating Tuples: A tuple is defined by enclosing items in parentheses (). For example, Code Output: ('Angular', 'React', 'Django') Explanation In the above example, we created a tuple named frameworks containing three string values separated by a comma. 2. Accessing Items: Tuples are zero-indexed, meaning the first item is at index 0. We can easily access an item using its index number. See the below example. Code Output: 3 Explanation The line in the given example, print(len(frameworks)), calculates the length of the tuple named frameworks. When you run the above code, it will print the value 3 because three elements are in the given tuple. 4. Tuple Immutability Tuples are immutable, meaning you cannot modify their values after creation. This makes them useful for fixed data, like coordinates or database records. Example Output: Traceback (most recent call last): File "c:\Users\hp\Desktop\echo_client.py", line 2, in Explanation After running the above code, we got an error in the output section because tuples are immutable, so we cannot replace the existing value of the tuple with a new one. 5. Packing and Unpacking Tuples: When creating a tuple, we normally assign values. This process is called packing. On the other hand, Unpacking refers to accessing values from a tuple and assigning them to other variables. You can unpack a tuple into separate variables or assign multiple values to a tuple. Here's an example: Packing a Tuple Code Output: (10, 20) Explanation In the above line of code, two variables named x and y were created and simultaneously assigned values 10 and 20. Then, assign the variables x and y in a new coordinate variable. Unpacking a Tuple Code Output: hp Dell Asus Explanation In the above line of code, we created a tuple named my_tuple and added four string values. In the next line, create another variable named x, y, and z and assign the my_tuple to this variable, showing unpacking. It will assign the first value of my_tuple to the variable x, the second to y, and the third to z. Unpacking Tuples Using Asterisk Code Output: 10 ['java', ' T', ' point'] 50 Explanation In the above code, the line x, *y, z = (10, 'java', ' T', ' point', 50) indicates tuple unpacking. x receives the first element of the tuple, which is 10. Next, y is a list that collects all the middle elements (between x and z). As a result, y will contain ['java', ' T', ' point']. And z receives the last element of the tuple, which is 50. Unpacking Using Function Arguments In addition, a tuple can be unpacked when providing parameters to a function: Code Output: 500 500 Explanation The above code defines a multiplication function that takes two arguments and returns their product. It calculates the multiplication of 10 and 50 using direct arguments and a tuple unpacking method. Finally, it prints the results of both multiplications. 6. Concatenate Tuples Code Output: Tuple is concatenated: (2, 4, 6, 'x', 'y', 'z') Explanation The above code defines two tuples, tuple1 and tuple2, each containing elements. It then concatenates these two tuples into a new tuple named new_tuple and prints the concatenated tuple. 7. Slicing Slicing allows you to extract specific subsets of data efficiently. Tuples are ordered, which is similar to list data type, but it is immutable. Immutable means you cannot change the elements of a tuple once you have created it along with the values. Tuple slicing is particularly useful when dealing with datasets or organising information. Let's dive into the details:
Code Output: slcd list 1: [(2, 'Jaguar')] slcd list 2: [(1, 'Audi'), (2, 'Jaguar')] slcd list 3: [(4, 'BMW')] slcd list 4: [(1, 'Audi'), (4, 'BMW') Explanation In the above code, define a tuple named list_of_tuples. Then, we used various methods of slicing and extracting tuples from the list using index ranges and step sizes. Using Negative Indices: You can also use negative indices for slicing. Example Output: Sliced list: [(3, 'Mercedes')] Explanation In the above code, we created a tuple named tuples_list. It shows slicing by extracting a sublist from the tuples_list that starts from the second-to-last tuple and ends before the last tuple. Using a loop with condition Code Output: Filtered list using a loop: [(0, (1, 'Audi')), (2, (3, 'Mercedes'))] Explanation In the above code, create a tuple named tuples_list. Then, we filtered the tuples based on their index positions using a list comprehension with a condition. Next, it selects a tuple item where the index is even. Then, shows the result of the filtered list and their indices. Using List Comprehension Code Output: Sliced list is: [(2, 'Volvo'), (3, 'Mercedes')] Explanation In the above code, create a list using list comprehension called sliced_list. Then, it iterates over each tuple in tuples_list. For each tuple, it checks whether the index of that tuple in tuples_list matches the condition 1 <= index < 3. In this case, only the tuples at indices 1 and 2 are satisfies the condition in the sliced_list. Dictionaries:A dictionary is a versatile data structure that stores values in key:value pairs. Unlike lists or tuples, where elements are indexed by position, dictionaries allow you to access values using their associated keys. Here are some key points about dictionaries: A dictionary is created using curly braces {}. Each key is associated with a value, separated by a colon (:). The general syntax for creating a dictionary is: Syntax Example Output: Candidate Details: {'name': 'Niraj', 'age': 30} Explanation In the above code, we created a candidate dictionary and included the data in the key:value pair format. Next, we used the print() function to display the candidate details. Characteristics
Accessing the Values Code Output: java java Explanation In the above code, we created an empty dictionary named empty_dict. An empty dictionary has no key-value pairs and is represented by {}. Meanwhile, the dictionary my_dict contains three key-value pairs. Creating a Dictionary using dict() You can create dictionaries using the dict() constructor: Code Output: {1: 'java', 2: 'T', 3: 'point'} {1: 'java', 2: 'T'} Explanation The above code creates dictionaries using different methods. dict_from_constructor uses a dictionary constructor with key-value pairs provided within curly braces. dict_from_tuples uses a dictionary constructor with a list of tuples, each representing a key-value pair. Nested Dictionaries: Dictionaries can be nested, allowing multiple levels of key-value pairs: Code Output: {'Name': 'Mark', 'Details': {'Age': 23, 'Location': 'Python World'}} Explanation In the above example, we created a nested_dict which is an outer dictionary. It contains two key-value pair elements. Next, another dictionary, called Dictionary, was created. The value associated with the key 'Details' is another dictionary. This inner dictionary contains two key-value pairs. Adding Items to a Dictionary: Assign a value to a new key to add an item. Here is an example: Code Output: {'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'} {'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London', 'France': 'Paris'} Explanation In the above example, we created a dictionary named country_capitals with key-value pairs representing countries and their capitals. Then, add a new key-value pair in the existing dictionary. Built-in Dictionary Methods:There are three built-in dictionary methods, described below:
Code Output: dict_keys(['Germany', 'Canada', 'England', 'France']) dict_values(['Berlin', 'Ottawa', 'London', 'Paris']) dict_items([('Germany', 'Berlin'), ('Canada', 'Ottawa'), ('England', 'London'), ('France', 'Paris')]) Note: Dictionary keys must be unique, and duplicate keys overwrite previous values. Python does not allow you to use predefined functions or data types as the keys. While you can insert any data type values.Explanation
clear() Method:Python enables you to remove all the key-value pairs from a dictionary data type by going with the .clear() method. Code Output: {} Explanation In the above code, we created a dictionary called my_dict. This dictionary contains two key-value pairs. Next, we used the .clear() method that removes all key-value pairs from the given dictionary. When you call the .clear() method with the given dictionary, it empties it by removing all the values. Sets:A set is a collection of elements. It is defined using curly braces {} or the set() constructor. Sets do not allow duplicate values, it means you are allowed to keep only unique values in a set. It is iterable. The sets are unordered which means we are not allowed to access the items by using the index from a list. It is mutable, which means we can add or remove elements. It can be very useful for tasks like removing duplicates or checking membership. The major advantage of using a set instead of a list is its highly optimized method for checking whether a specific element is contained in the set. This optimization is based on a data structure known as a hash table. Creating a Set Code Output: {'banana', 'cherry', 'apple'} Explanation: The above line of code represents a list containing three string values. As we know, sets don't allow duplicate items; if you include the same fruit name by mistake multiple times, it will only be stored once in the set. Adding Elements to the Set:We can add elements to a set using the add() method: Code Output: {'banana', 'cherry', 'apple', 'orange'} Explanation In the above line of code; we have used the .add() method that adds a new value to the existing set. As a result, a new value will be added to the set named myset. Operations on SetCode Output: Set 1: {'cherry', 'banana', 'apple'} Set 2: {1, 3, 5, 7, 9} Set 3: {False, True} Updated Set 1: {'cherry', 'banana', 'apple', 'grape'} Explanation In the above section of program, we created the three sets named set1, set2 and set3 which have different types of data such as strings, integer and boolean. After that, we added 1 another element in set1. Frozen Sets:Frozen sets are immutable in Python. The frozen data set remains fixed after creating the same as a dictionary. It means you cannot change a value in the frozen set after inserting the values. It also supports set operations such as union, intersection, etc. In addition, you can combine and compare the frozen sets with another set. Code Output: Normal Set: {'a', 'c', 'b'} Frozen Set: {'e', 'g', 'f'} Explanation The above code creates a normal set named normal_set and a frozen set named frozen_set using different constructors. Then, it prints both sets. Normal sets can be modified (addition, removal), while frozen sets cannot be modified after creation. User InputPython lets you interact with your program by providing data during runtime. You can prompt the user to enter values and then use those values in your code. Let's explore how to take user input: Using input() FunctionPython provides the input() function used to read the text entered by the user. The input () function returns the provided text from users as a string. Example Output: Enter your name: Mark Hello, Mark Explanation In the code mentioned above, we used an input field providing users to enter the name. The input() function displays the message "Enter your name: " and waits for the user to type the input. Note: The input is always treated as a string, even if the user enters a number.Type Casting User Input:If you want to use the input as a different data type, you can convert it using type casting. Example Output: Enter your age: 22 You are 22 years old. Explanation In the above-given code, the line age_str = input("Enter your age: ") prompts the users to input their age. The input is captured as a string and stored in the variable named age_str. Then, the line age = int(age_str) is used to convert the string age_str to an integer. Handling Multiple Inputs:You can split multiple inputs in a single line using the split() method. Example Output: Enter three numbers: 2 3 5 Sum of the numbers are: 10 Explanation The above-given code, provide users with an input field to enter three numbers separated by spaces. Then, it reads the input and splits it into individual numbers. Then, converts them to integers and assigns them to variables num1, num2, and num3 simultaneously. Handling User Input Safely: We must always validate and handle user input carefully to avoid errors. For this, use exception handling to handle unexpected input. Comments in PythonIn Python, comments are essential for making code more readable and for providing hints to other developers so they can understand the written code easily. Let's dive into the different types of comments along with examples: Single-line Comments:We use the hash (#) symbol to write single-line comments. The Python interpreter ignores these comments during code execution. Example Explanation In the above example, the lines starting with # are comments. They help other coders or programmers explain what the code does. Multiline Comments:Unlike other programming languages, Python doesn't have a syntax dedicated to multiline comments. However, we achieve the same effect by using the # symbol at the beginning of each line. Example In addition, we can also use multiline strings as comments. The unassigned multiline strings are ignored during execution. For example: Docstring Comments:Docstring is an abbreviation of Documentation string which is a special method of comment used to comment document functions, classes, or modules. They are enclosed in triple quotes (''' or """) and provide information about the purpose, usage, and parameters of the code. Example: Operators in PythonIn general, Operators are used to execute various operations on values and variables. We can also call them expressions, which create a result by combining operators and values. Basically, we use operators to calculate mathematical problems. Arithmetic Operators:We use arithmetic operators to perform several mathematical operations like addition, subtraction, multiplication, and division. Example Output: 13 5 36 1 6561 Explanation In the above code, we performed basic arithmetic operations on variables a and b. We performed calculations such as addition, subtraction, multiplication, modulus, and exponentiation of a and b. Comparison OperatorsWhen comparing values, relational operators are utilized. Depending on the criteria, it returns boolean values. Code Output: False True False True False True Explanation In the above code, we are comparing the values of variables a and b using relational operators, where a > b checks if a is greater than b. Next, a < b checks if a is less than b. Next, a == b checks if a is equal to b. Next, a != b checks that if a is not equal to b. Next, a >= b checks if a is greater than or equal to b. Next, a <= b checks if a is less than or equal to b. Logical Operators in PythonLogical operators are used on conditional statements. They conduct the logical AND, OR, and NOT operations. Code Output: False True False Explanation In the given example, the expression a and b checks if both a and b are True. Next, the expression a or b checks if at least one of a or b is True. Next, the expression not a deny the value of a. Bitwise Operators in PythonBitwise operators are used to do bitwise operations on integers. After converting the numbers to binary, operations are done on each bit or corresponding pair of bits, hence the name bitwise operators. Code Output: 4 5 -6 1 1 20 Explanation In the case, a & b performs a bitwise AND operation between a and b. It will give the output 4. In the second case, a | b performs a bitwise OR operation between a and b. It will give the output 5. In the third one, ~a performs a bitwise NOT operation on a. It will give the output -6. In the next, a ^ b performs a bitwise XOR operation on a and b. It gives the output 1. Next, a >> 2 shifts the bits of two positions to the right. It will result in 1. Lastly, a << 2 shifts the bits of two positions to the left. It will give an output of 20. Assignment Operators:We use assignment operators to assign a value to the variables. Below are given some examples to understand them easily. Code Output: 15 Explanation In the above example, we defined two variables named x and y. The line x += y means adding the value of y to the current value of x and storing the result back in x. Special OperatorsCode Output: True Explanation In the above code, Membership (in) checks if the string 'banana' is present in the list 'fruits', it will give the output True. Next, Identity (is) checks if the list 'x' and 'y' refer to the same object, and it will give the result True. Python's End ParameterThe end parameter in Python's print() function allows you to control how the output ends. By default, print() adds a newline character (\n) at the end of each printed line. However, you can customize this behaviour with the end parameter. Ending Character:You can specify any character or string to be printed at the end of a print() statement using the end parameter. Example Output: Welcome to javaTpoint Explanation In the above line of code, we used the print() statement with two arguments. The second argument is end=' ', which denotes that a space character should be added at the end of the printed output instead of printing the default newline character. Concatenating Strings:You can concatenate multiple print() statements into a single output line using the end parameter. In this example, we set the end to a space character " " for the first print() statement. As a result, the second one starts on the same line, separated by a space. Example Output: My name is Mark and I am 22 years old. Nice to meet you! Explanation In the above program, we declared two variables, name and age and assigned the values. In the first print() statement, we provided more than one argument separated by commas. Next, the end=" " argument specifies that a space character should be added at the end of the printed output instead of the default newline character. Using sep and end Together:The print() function also uses the sep parameter to separate arguments and ends after the last argument. Code Output: jTp 01-03-2024 Red,Green,Blue@javaTpoint Explanation In the above piece of code, the sep='' argument specifies that there should be no separator between the two strings. Next, the end='' argument ensures no newline character is added after printing these strings. The end='\n' argument shows that a newline character is added. Next, the sep=',' argument specifies that a comma should separate these strings. Here, the end='@' argument ensures that the @ symbol is added after printing the strings. Python FunctionsA function is a block of code that performs a specific task. Additionally, Python allows you to create your own functions using the def keyword. Creating and Calling a FunctionFunctions are the base of programming that allows you to encapsulate reusable pieces of code. In Python, we use def to create a function. Here is an example. Example Output: Hello javaTpoint! Explanation In the above code, we created a function named hello. Then, used the print statement to display the message and called the function to see the output. Function ArgumentsYou can pass values inside a function called arguments or parameters. Example Output: Hello Mark Explanation In the above code, hello is the function name. Inside the function, we passed a single parameter called name. Then, we called the function. Multiple Arguments:You can create a function that includes multiple arguments as well as a single argument. For example, Example Output: The addition of two numbers is: 17 Explanation In the above code, defined a function called addition and inserted two numbers as input, adds them together, and prints the result. Then, the addition function was called with arguments 9 and 8. Lambda FunctionThis function is small and is also known as an anonymous function. We define the function using the lambda keyword. Example Output: Cube of 6 is: 216 Explanation In the above code, we used the lambda function named cube that calculates the cube of a number. Then, it prints the cube of 6 using the lambda function. Recursion:When a function calls itself, it is called recursion. See the below example to understand the recursion. Code Output: Factorial of 6 is: 720 Explanation In the above code, we defined a function named fact to calculate the factorial of a number recursively. Then, check if the number is 0; it will return 1. Otherwise, it recursively multiplies the number by the factorial of (n-1). Return StatementThe return statement is used to exit a function and send a result back to the caller. If the return statement is without expression, it returns the special value None. Code Output: Square of 8 is: 64 Explanation In the above example, we defined a function named square that calculates the square of a number. Then, the square function is called with the argument 8. Range() Function:The range() function generates a sequence of numbers from a starting value up to an ending value. The step starts from 0 and increases by 1. Syntax: Code Output: 2 3 4 Explanation The code mentioned above prints numbers from 2 to 4 using a for loop with the range() function. Map() FunctionThe map() function takes two arguments. It is a function that you can apply to each element. An iterable containing the elements you want to process. You can convert it to a list or other data structures if needed. Example Output: [4, 12, 10, 14] Explanation In the above code, we defined a function named dbl to doubles a given number. It applies the dbl function to each element using the map() function and converts the result to a list. Filter() FunctionThe filter() function takes two arguments. This function tests each element of the iterable. An iterable containing the elements you want to filter. It returns an iterator with the items that pass the condition. Example Output: [4, 6, 8, 12] Explanation In the above code, we defined a function named is_even that checks if a number is even. It filters even numbers from the list of numbers using the filter() function and is_even function and converts the result to a list. Reduce() FunctionThe reduce() function takes two arguments. This function combines two elements. An iterable containing the elements you want to reduce. It repeatedly merges pairs of elements according to the specified function until only one value remains. Example Output: Sum of the numbers are: 20 Explanation In the above code, imported the functools module, which includes the reduce() function. Then, it calculates the sum of numbers in the list using reduce() and a lambda function for addition. Try and Except Statement:The try block contains the code you want to test for errors. If an error occurs within the try block, Python will raise an exception. For example, Code Output: An exception will occur Explanation In the above code, we attempted to divide 15 by 0, which is impossible. As a result, it will show an error. Except:The except block specifies what to do when an exception occurs. If an exception is raised in the try block, the code inside the except block will be executed. You can catch specific types of exceptions by specifying the exception class after except. Example Output: Division by zero error Explanation In the above-given code, we attempted to divide 15 by 0. If a ZeroDivisionError exception occurs, it prints "Division by zero error". File Handling:File handling is an important topic that enables you to work with files. The key function for opening the file is the open() function. You need to insert two parameters: first is the filename, and second one is the mode of file, like opening, reading, etc.
Example Output: here is some content Explanation In the above program, we opened a file named "example.txt" in reading mode. Then, it reads the file's contents and stores them to a variable named contents. The 'with' statement ensures proper file handling, automatically closing it after executing the block. Writing to the File:To write the content to the file, use the write() method. Here is an example. Program Output: File content: Hello, Mark! Are you a Python Developer? Explanation: We opened the file named "demo.txt" in writing mode in the above code. Then, wrote two lines of text to the file. Next, we opened the file in reading mode to verify the content was written successfully. Appending Content to a FileTo append the content to a file, use the append() method. Here is an example to help you understand it easily: Example Output: File content: Hello, Mark! Are you a Python Developer? This is additional content. Explanation: In the program mentioned above, we opened the file named "demo.txt" in append mode and added the sentence "This is additional content." to the end of the file. OOPs ConceptObject-Oriented Programming (OOP) in Python is a powerful paradigm that allows you to model real-world entities using objects and classes. Let's explore the basics of OOP concepts in Python. Classes and Objects:A class is a blueprint or template for creating objects. It defines the attributes and methods that the objects of that class will have. An object is an instance of a class. It combines data and behaviour. Example Output: My cow's name is Daisy, and it's a Holstein Friesian. Explanation In the above-provided example, we defined a class named Cow with attributes name and breed initialised through its constructor method __init__. It creates an object my_cow of the Cow class with specified attributes. Encapsulation:We use encapsulation to restrict direct access to internal data or information from outside the class. Controlling data access helps maintain the integrity of the object state. Encapsulation provides modularity by defining self-contained classes that handle their self-data and behaviour. Example Output: Account balance is: $1500 Explanation In the above code, we defined a class named BankAccount with attributes account_number and balance, where account_number is protected and balance is private. It provides a method get_balance() to access the private balance attribute. Then, we created an object my_account of the BankAccount class with specified attributes. Then, we displayed the balance using the get_balnce() method. InheritanceInheritance allows a class, generally known as a subclass or derived class, to inherit attributes and methods from another class, known as a base class or parent class. It promotes code reuse and establishes a hierarchy of classes. Example Output: "Parrot Talks" Explanation In the above program, we created a class Bird with a method speak() that prints "Bird speaks". Next, we defined a class Parrot that inherits from Bird and overrides the speak() method to print "Parrot Talks". Next, create an instance my_parrot of the Parrot class and call its speak() method. PolymorphismPolymorphism allows objects of different classes to be considered uniformly. It enables method overriding and method overloading. Example Output: Area of the circle is: 153.86 Explanation In the above code; we defined a base class Shape with the area() method. Then, we created two subclasses, Circle and Rectangle, each with its area() method. The Circle class calculates the area of the circle. While the Rectangle class calculates the area of the rectangle. Then, we created an instance of my_circle of the Circle class. Data AbstractionAbstraction hides complex implementation details and shows only essential features. Abstract classes and interfaces define a contract for derived classes. Example Output: "Car started" Explanation In the above code, we defined an abstract base class named Van inherited from ABC (Abstract Base Class) and containing an abstract method start(). The Car class inherits from Van and implements the start() method. Conclusion:A Python Cheat Sheet is an important source for beginners and experienced programmers. It includes essential Python concepts, syntax, and functions that can be more helpful and a quick guide for learning Python quickly. Whether you're a data scientist, web developer, or machine learning enthusiast, having a well-organized cheat sheet can be more useful in the context of saving time in searching for a specific topic in the quickest way. |