Docsity

Mastering Python – Comprehensive Handwritten Notes – Programming Fundamentals to Advanced, Cheat Sheet of Programming Languages

Partial preview of the text

Download Mastering Python – Comprehensive Handwritten Notes – Programming Fundamentals to Advanced and more Cheat Sheet Programming Languages in PDF only on Docsity!

Index Python Basic Function Modules and Packages Data Structures File Handling Object-Oriented Programming Error Handling and Exceptions Function Programming Advanced-Data Structures Database Web Development With Python Machine Learning and Data Science Concurrency and Multithreading API Integration Python Basics 1.1 Introduction Python is a well-liked high-level programming language known for its ease of use and adaptability. “Guido Van Rossum” developed Python in the late 1980s, and it has since become widely used in a variety of fields such as web development, data analysis, artificial intelligence, scientific computing, and more. .Python is known for its readable syntax, which focuses readability of the code and lowers of the cost of program maintenance. Code blocks are defined by indentation, which eliminates the need for explicit braces or keyword and improves the consistency and clarity of the code. The procedural and object-oriented programming paradigms are both supported by Python, giving developers more freedom when creating software structures. Through classes and modules, it promotes code reuse and modularity, making it simples to handle complicated projects. Python's huge standard library, which provides a variety or pre-built modules and functions that makes certain jobs easier, is one of its strengths. This library makes it easier for developers to manipulate files, communicate over networks, analyse data and more. Python's dynamic typing system promotes quick development by allowing variables to be assigned without a value. For Example: age = 20 name = “Pawan” “age” and ‘name’ are variables here, and the values “20” and “Pawan” are what they represent. Based on the value supplied to the variable, Python finds the proper data types to assign. # Integers {int), Floating-point numbers (Float), strings (str), lists (list), dictionaries (dict) and other data types include several data types of data that may be stored in variables, For Example: temperatire = 97.6 days_of week = ['Monday”, “Tuesday”, “Sunday’”] # The usage of variable sin your code enables dynamic and interactive behaviour by allowing calculations to be performed, user input to be stored, and data manipulation to be made possible. For Example: radius = float {input (Enter the radius: “)) area = 3.14 * radius ** 2 printf (The area of the circle is: “, area) Important: - Python variables must be begin with letter (a-z, A-Z) or an underscore {__), and they are case-sensitive (‘myVariable” and “myvariable”) are two separate variable. They are not Python keywords and may also have numbers (after the first character). Keep in mind that variables are pointers to places in memory where data is kept, not just simple container. Multiple variables may all refer to the same value, and unless they all point to same memory address, altering the value of one variable has no impact on the value of the others. 1.3 Data Types Python programs depend heavily on data types because they specify how data is expressed, Saved, and processed. In order to write effective and efficient code, one must first understand data types. Python is very well- liked for a variety of applications. From straightforward scripting to intricate web applications and data science projects, thanks to its dynamic typing and large built-in data types. In Python, We have 4 different Data Types. i. Numeric Data Type The numeric data type is used in Python to represent and wrok with numerical numbers. “Integers” (int) and “Floating-point numbers’ (float) are two primary categories of numeric data types. Let's examine these subtypes with some example: “integer {int)” type Integer is whole numbers without decimal points. They can be positive, negative or zero. For Example: age = 20 temperature = -12 population = 100 # Many arithmetic operations, including addition, subtraction, multiplication, and division are supported by Many programming activities, such as user input, text processing, formatting, and others frequently include text data. Example of using the text data type (str) in Python: “Creating Strings’ # By using single quotes message = ‘Hello, Pawan’ # By using double quotes name = “Pawan” # By using triple quotes quote = “Hello, am Pawan’” “Connecting String Together” age = 30 # Using the format method info = “Name : {}, Age: {}". Format (name, age) # Using F-Strings or Formatted string lateral f info =f “Name: fname}. Age:fage}” “Accessing characters in string” # Accessing the first character first_letter = name [0] # Slicing to extract a substring substring = message [7:12] “String Methods’ # getting the length of a string length = len (name) # Converting to uppercase uppercase_name = name.upper() # Converting to lowercase lowercase_name = name.lower() # capitalizing the first letter capitalized name = name.capitalize) “Checking For Substrings” #checking if a string starts with a certain substrings contains hello = message.startwith( Hello’) # Checking if a substrings is present conatins_pawan = “Pawan” in message “String Manipulation” # Removing leading and trailing whitespace trimmed_message = message.strip() “Splitting and joining strings’ #splitting a string into a list of words word list = message.split (. “) #joining a list of words into single string joined_words = “—“ .join(word_list) “String Formatting’ # Formatting a floating-point number formatted float = “{:, 2f}" format(3.14159%) food = fruit.union{vegetables) print{food) #output: {banana’ , “Spanish” , “orange”, carrot”, “pear” . broccoli”} #intersection of sets common_items = fruits.intersection(vegetables) print{common_items) #Difference of sets unique fruits = fruits.difference (vegetables) print({unique_ fruits) #Output: {‘banana’ , “grape” , “orange” , “pear’} iv. Boolean Data Type The Boolean data type, which may represent “True or false”, is a Boolean data type in python. In Python program, Boolean are mostly used for logical operations, comparisons and conditional expressions. Here is the example of using the Boolean data type in Python. “Basic Usage of Boolean in variables’ is sunny = True is raining — False print (is sunny) #Output: True print(is raining) #Output: False Here we define two Boolean variable “is sunny” and “Is_raining” and they assigned values “True” and “false” respectively. 1.4 Operators Python supports wide range of operators that help manipulate values, make decision, and control the flow of your program. Operators in python are symbols or special keywords that allow you to perform various operations on data, including arithmetic calculations, comparison, logical evaluations, and more. In Python, we have eight types’ operators. i. Arithmetic Operators: - These operators are used for mathematical calculations and operations. Symbols Names + Addition - Subtraction * Multiplication / Division % Modulus ** Fxponentiation // Floor Division ii. Comparison Operator: - These Operators compare values and return Boolean result. Symbols Names == Equal to != Not Equal to > Greater than < Less than >= Greater than or equal to *<= less than or equal to iii. Logical Operators: - These operators are used for logical operations and combine Boolean value. Symbols Work objects. “is not.” Return “true” if the variable points to different objects. vill. Ternary operators: - The Operator provides a shorthand for conditional expressions. Symbols Work “x if condition else y” Returns “x” if the condition is ‘true’, otherwise returns ‘y’. 1.5 Control Statements Programmers use control statements to change a program's execution flow based on specific condition or criteria. They provide programmers the ability to make choices, reuse code, and selectively run particular chunks of code. Control statements are essential for writing flexible and dynamic programs in Python. In python, we have three types of Control Statements i. Conditional Statements Making judgements in your code based on particular conditions is made possible via conditional statements, fundamental notion in programming with the help of these statements, your program may run various blocks of code in response to whether a particular condition is true or not. The ‘if’, ‘elif’. and “else” keywords are often used to create conditional statements in python code. “if — A conditional statements fundamental format is an “if” keywords followed by an evaluation condition. The code block positioned behind the “if” statement is executed “if” the condition is satisfied. The code block is skipped if the condition is false. Here is an Example: age=18 if age > = 18; print CAdult’) The program in this example determines if the age variable is greater than or equal to 18. The indented code block is run and the message “Adult” is printed since the condition is true (18 is in fact more than or equal to 18). “else” — you may wish to provide another option of action to perform if the condition is false. The “else” keyword useful in this situation, For Example: age = 13 if age >= 18: print(‘Adult”) else: print( No Adult’) “elif” — The “elif (else-if)” keyword can be used for more complex situations when there are many conditions to take into considerations, For Example: score = 72 if score >= 90; print(A Grade’) elif score >= 80; print( B Grade’) elif score >= 70; print( C Grade’) else: print(lmproved Yourself’) The program in this case compares the score variables to several situations. The subsequent statements are count = 0 while count < 5; print Count”, count) count += 1 As long a count is less than 5, the while loops keeps running the block of code indented. Every time the loop is executed, the count value is increased. iii. Control Flow Statements Developers can change the direction in which “loops” and “conditional” statements execute by using control flow statements. “break” and “continue” are the two primary form of control flow statements used in python. “break” — The ‘break” statement enables a quick end to a loop depending on a specific condition. This is helpful if you want to end a loop before all of iterations are complete. numbers = [1,2,3,4,5] for num in numbers; if Hum == 3: break print(num) When the value of “num” reaches 3, the break statement is met, and the loop ends. The loop continuous to cycle over the list of integers. “continue” — By using the “continue” statement. you may skip the remaining iterations of the loop and go straight to the next one. It is useful in situations where you wish to have not handled a certain item. numbers = [1,2,3,4,5] for num in numbers; if num == 3; continue print(num) The “continue” statement is met and the current iteration is ignored when the value of “numb” js 3. Printing the leftover integers on the next iterations of the loop. brackets to define a function. Within a block, the logic of the function is indented. For Example: def greet({name): "Hello, How are you..?77"" print(f"Hello, {name}!") greet("Pawan') greet("Preet") The "greet" function prints a greeting and receives a "name" input. You may reuse the code for multiple welcomes by invoking the function with different names. 2.3 Calling a Function In Python, calling a function requires entering the name of the function, followed by brackets, and optionally, arguments that correspond to the parameters of the function. The code included in a function’s block is executed when it is invoked. For Example: def add{a, b): ""'Sum of Two!" return a+b # Calling the function and storing the result result = add(3, 5) print(result) # Output: 8 The “add” function takes two arguments, adds them, and returns the result. 2.4 Returning Value The “return” statement in Python allows functions to return values. Using the return keyword, a function that has been called and has completed its code block may “return” a result to the caller. The caller code might then use this returned value for additional calculations, assignments, or other uses. For Example: def multiply{a, b): """Product of two Numbers. result =a *b return result # Calling the function and using the returned value product = multiply{4, 7) print(product) # Output: 28 # Using the returned value directly print(multiply(3, 9%) # Output: 27 The “multiply” function determines the outcome of the product of two integers. The returned value from the function call can either be utilized directly in additional operations “{print(multiply(3. 9))” or assigned to a variable “product”. 2.5 Default Arguments When a function is defined in Python, parameters can have default arguments, or predetermined values, provided to them. This enables you to use the default values when calling the function rather than individually providing values for those arguments. The flexibility and usefulness of functions are improved by default parameters. For Example: def greet({name. greeting="Hello"):"""Greet With Person Name." print(f'{greeting}, {name}!") # Calling the function with both arguments