0% found this document useful (0 votes)
13 views22 pages

Python Programming Basics Explained

The document outlines key features of Python, emphasizing its simplicity, interpreted nature, dynamic typing, and extensive libraries. It covers essential programming concepts such as variables, identifiers, primary data types, case sensitivity, and operators, including their precedence and usage. Additionally, it discusses type casting and the ternary operator, providing examples for clarity.

Uploaded by

U Tarun Raju
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views22 pages

Python Programming Basics Explained

The document outlines key features of Python, emphasizing its simplicity, interpreted nature, dynamic typing, and extensive libraries. It covers essential programming concepts such as variables, identifiers, primary data types, case sensitivity, and operators, including their precedence and usage. Additionally, it discusses type casting and the ternary operator, providing examples for clarity.

Uploaded by

U Tarun Raju
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

‭‬ F

● ‭ eatures:‬
‭1.‬ ‭Simple and Easy to Learn: Python has a syntax that is easy to read and write, making it‬
‭a great language for beginners.‬
‭2.‬ ‭Interpreted: Python is an interpreted language, which means that code is executed line‬
‭by line, making it easier to test and debug.‬
‭3.‬ ‭High-level: Python is a high-level language, meaning it abstracts away many low-level‬
‭details, making it more user-friendly.‬
‭4.‬ ‭Dynamic Typing: Python uses dynamic typing, which means you don't need to explicitly‬
‭declare the data type of a variable.‬
‭5.‬ ‭Multi-paradigm: Python supports multiple programming paradigms, including procedural,‬
‭object-oriented, and functional programming.‬
‭6.‬ ‭Extensive Standard Library: Python comes with a large standard library that provides‬
‭support for many common tasks and functionalities, reducing the need to write code‬
‭from scratch.‬
‭7.‬ ‭Third-party Libraries: Python has a vast ecosystem of third-party libraries and‬
‭frameworks that extend its functionality for specific purposes, such as web development,‬
‭data analysis, and machine learning.‬
‭8.‬ ‭Platform Independent: Python code can run on any platform that has a Python‬
‭interpreter, including Windows, macOS, and Linux.‬
‭9.‬ ‭Open Source: Python is open-source, which means that its source code is freely‬
‭available and can be modified and distributed by anyone.‬
‭10.‬‭Community Support: Python has a large and active community of developers who‬
‭contribute to its development, provide support, and create libraries and frameworks.‬

‭ ‬ ‭Variables:‬

‭In Python, a variable is a named location in memory that is used to store data. You can think of‬
‭a variable as a container that holds a value. Variables in Python are created using the‬
‭assignment operator =. Here's a basic example:‬

‭ ython code‬
p
‭x = 5‬

I‭n this example, x is a variable that holds the value 5. You can then use this variable in your‬
‭code, for example:‬

‭ ython code‬
p
‭y = x + 3‬

‭Now, y will be 8, because it's assigned the value of x plus 3.‬

‭ ython is dynamically typed, so you don't need to explicitly declare the type of a variable when‬
P
‭you create it. The type of a variable is determined by the value it holds. For example, in the‬
‭above examples, x is an integer (int) because it holds the value 5, and y will also be an integer‬
‭because it holds the result of an integer operation.‬
‭ ariables in Python can hold various types of data, including numbers, strings, lists, dictionaries,‬
V
‭and more. You can also change the value of a variable after it has been created, like so:‬

‭ ython code‬
p
‭x = 5‬
‭x = 10 # Now x is 10‬

‭ ariables are an essential part of programming in Python and are used extensively to store and‬
V
‭manipulate data in your programs.‬

‭ ‬ ‭Identifiers:‬

‭In Python, identifiers are names given to various elements in the code, such as variables,‬
‭functions, classes, etc. Here are the rules for identifiers in Python:‬

‭1.‬ V ‭ alid Characters: Identifiers can contain letters (both uppercase and lowercase), digits,‬
‭and underscores (_). They must start with a letter or an underscore and can not start‬
‭from numbers (1_function is not valid).‬
‭2.‬ ‭Case Sensitivity: Python is case-sensitive, so myVar, MyVar, and MYVAR are all different‬
‭identifiers.‬
‭3.‬ ‭Reserved Words: You cannot use reserved words (keywords) as identifiers. For‬
‭example, you cannot use if, else, for, while, etc., as variable names.‬
‭4.‬ ‭Length: There is no limit on the length of an identifier in Python, but it's a good practice‬
‭to keep them short and meaningful.‬
‭5.‬ ‭Convention: It's a convention in Python to use lowercase letters for variable names and‬
‭underscores to separate words (e.g., my_variable). For class names, capitalize the first‬
‭letter of each word (e.g., MyClass), and for constants, use all uppercase letters with‬
‭underscores separating words (e.g., MY_CONSTANT).‬
‭6.‬ ‭Special Characters: Identifiers cannot contain special characters such as !, @, #, $, %,‬
‭etc.‬

‭●‬ ‭A good programmer should always have his identifiers‬‭Simple‬‭,‬‭Short‬‭,‬‭Meaningful‬‭.‬

‭ ‬ ‭Primary DataTypes:‬

‭In Python, the primary data types are the basic or fundamental data types that are built into the‬
‭language. These include:‬

‭ . Integer (`int`): Represents whole numbers, positive or negative, without any decimal‬
1
‭point. Example: `10`, `-3`, `1000`.‬

‭ . Float (`float`): Represents floating-point numbers, which are numbers that have a‬
2
‭decimal point or use exponential notation. Example: `3.14`, `2.0`, `-0.5`.‬

‭3. Boolean (`bool`): Represents a Boolean value, which can be either `True` or `False`.‬
‭ . String (`str`): Represents a sequence of characters enclosed in single quotes, double‬
4
‭quotes, or triple quotes. Example: `'hello'`, `"Python"`.‬

‭ . NoneType (`None`): Represents the absence of a value or a null value. Used to‬
5
‭indicate that a variable or expression has no value assigned to it.‬

‭ hese primary data types are used to represent and manipulate different kinds of data in‬
T
‭Python programs.‬

‭ ‬ ‭Python is Case Sensitive:‬



‭Case sensitivity means that the language distinguishes between uppercase and lowercase‬
‭letters. In a case-sensitive language like Python, `variable`, `Variable`, and `VARIABLE` would‬
‭be considered three different identifiers. This is in contrast to case-insensitive languages, where‬
‭the case of letters does not affect the interpretation of identifiers.‬

‭‬
● ‭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‬

‭ ‬ ‭Punctuators in python‬

‭In Python, punctuators are special characters that are used to structure code and provide‬
‭syntax. Some common punctuators in Python include:‬

‭ . Parentheses: `(` and `)` are used for grouping and calling functions.‬
1
‭2. Brackets: `[` and `]` are used for creating lists and indexing.‬
‭3. Braces: `{` and `}` are used for creating dictionaries and sets, and for defining code blocks.‬
‭4. Comma: `,` is used for separating items in lists, tuples, and function arguments.‬
‭5. Colon: `:` is used to start a block of code (e.g., in if statements, loops, and function‬
‭definitions).‬
‭6. Period: `.` is used for accessing attributes and methods of objects.‬
‭7. Semicolon: `;` is used to separate statements on the same line, although its use is not‬
‭common in Python.‬

‭These punctuators play a crucial role in defining the structure and syntax of Python code.‬
‭ ‬ ‭Python is Implicitly Typed Language:‬

‭Implicitly typed languages are those where the type of a variable is inferred by the compiler or‬
‭interpreter based on the value assigned to it. This is in contrast to explicitly typed languages‬
‭where the type must be explicitly declared.‬

‭ ython code‬
p
‭x = 5 # x is implicitly an integer‬
‭y = "hello" # y is implicitly a string‬

‭●‬ ‭Operator in python:‬


I‭n Python, operators are special symbols or keywords used to perform operations on operands.‬
‭Python operators can be classified into several categories based on their functionality. Here are‬
‭the main types of operators in Python:‬

‭ . **Arithmetic Operators:** Used for performing arithmetic operations such as addition,‬


1
‭subtraction, multiplication, division, etc.‬
‭̀``python‬
‭1.‬ ‭+ # Addition‬
‭2.‬ ‭- # Subtraction‬
‭3.‬ ‭* # Multiplication‬
‭4.‬ ‭/ # Division‬
‭5.‬ ‭% # Modulus (remainder of the division)‬
‭6.‬ ‭** # Exponentiation (raise to the power)‬
‭7.‬ ‭// # Floor division (divide and round down to the nearest integer)‬
‭̀``‬

‭2. **Comparison (Relational) Operators:** Used to compare values and return True or False.‬
‭̀``python‬
‭1.‬ ‭== # Equal to‬
‭2.‬ ‭!= # Not equal to‬
‭3.‬ ‭< # Less than‬
‭4.‬ ‭> # Greater than‬
‭5.‬ ‭<= # Less than or equal to‬
‭6.‬ ‭>= # Greater than or equal to‬
‭̀``‬

‭3. **Assignment Operators:** Used to assign values to variables.‬


‭̀``python‬
‭1.‬ ‭= # Assign value‬
‭2.‬ ‭+= # Add and assign‬
‭3.‬ ‭-= # Subtract and assign‬
‭4.‬ ‭*= # Multiply and assign‬
‭5.‬ ‭/= # Divide and assign‬
‭6.‬ ‭%= # Modulus and assign‬
‭ .‬
7 *‭ *= # Exponentiate and assign‬
‭8.‬ ‭//= # Floor divide and assign‬
‭̀``‬

‭4. **Logical Operators:** Used for logical operations (and, or, not).‬
‭̀``python‬
‭1.‬ ‭and # Logical AND‬
‭2.‬ ‭or # Logical OR‬
‭3.‬ ‭not # Logical NOT‬
‭̀``‬

‭5. **Bitwise Operators:** Used to perform bitwise operations on integers.‬


‭̀``python‬
‭1.‬ ‭& # Bitwise AND‬
‭2.‬ ‭| # Bitwise OR‬
‭3.‬ ‭^ # Bitwise XOR (exclusive OR)‬
‭4.‬ ‭~ # Bitwise NOT (invert bits)‬
‭5.‬ ‭<< # Left shift‬
‭6.‬ ‭>> # Right shift‬
‭̀``‬

‭ . **Membership Operators:** Used to test if a value is a member of a sequence (e.g., list, tuple,‬
6
‭string).‬
‭̀``python‬
‭1.‬ ‭in # True if value is in sequence‬
‭2.‬ ‭not in # True if value is not in sequence‬
‭̀``‬

‭7. **Identity Operators:** Used to compare the memory location of two objects.‬
‭̀``python‬
‭1.‬ ‭is # True if both operands are the same object‬
‭2.‬ ‭is not # True if both operands are not the same object‬
‭̀``‬

‭ hese operators are fundamental to Python programming and are used extensively in writing‬
T
‭expressions and statements to perform various operations.‬

‭●‬ ‭Operator precedence in Python:‬


‭ perator precedence in Python determines the order in which operators are evaluated in an‬
O
‭expression. Operators with higher precedence are evaluated before operators with lower‬
‭precedence. If operators have the same precedence, they are evaluated from left to right. Here‬
‭is a general overview of operator precedence in Python (from highest to lowest precedence):‬

‭1. **Parentheses:** `()`, used to group expressions or override precedence.‬


‭ . **Exponentiation:** `**`, raises the left operand to the power of the right operand.‬
2
‭3. **Unary Operators:** `-` (negation), `+` (unary plus), `~` (bitwise NOT).‬
‭4. **Multiplication, Division, Modulus, and Floor Division:** `*`, `/`, `//`, `%`.‬
‭5. **Addition and Subtraction:** `+`, `-`.‬
‭6. **Bitwise Shifts:** `<<`, `>>`.‬
‭7. **Bitwise AND:** `&`.‬
‭8. **Bitwise XOR:** `^`.‬
‭9. **Bitwise OR:** `|`.‬
‭10. **Comparison Operators:** `==`, `!=`, `>`, `<`, `>=`, `<=`, `is`, `is not`, `in`, `not in`.‬
‭11. **Logical NOT:** `not`.‬
‭12. **Logical AND:** `and`.‬
‭13. **Logical OR:** `or`.‬

I‭t's important to note that when in doubt, using parentheses to explicitly specify the order of‬
‭operations is a good practice, as it can make the code more readable and prevent unexpected‬
‭behavior due to precedence rules.‬

‭ ‬ ‭Ternary Operator:‬

‭Type 1:‬‭<var>‬‭=‬‭<val1>‬‭if‬‭<condition>‬‭else‬‭<val2>‬
‭Type 2:‬‭<stt1>‬‭if‬‭<condition>‬‭else‬‭<stt2>‬
‭Type 2: (‬‭<false_val>‬‭,‬‭<true_val>‬‭) [‬‭<condition>‬‭]‬

‭ ‬ ‭Type Casting:‬

‭Type conversion in Python refers to the process of converting one data type into another.‬
‭Python provides several built-in functions for this purpose. Here are some common type‬
‭conversion functions:‬

‭1. **int()**: Converts a number or a string to an integer.‬

‭̀``python‬
‭num_str = "10"‬
‭num_int = int(num_str)‬
‭print(num_int) # Output: 10‬
‭̀``‬

‭2. **float()**: Converts a number or a string to a floating-point number.‬

‭̀``python‬
‭num_str = "3.14"‬
‭num_float = float(num_str)‬
‭print(num_float) # Output: 3.14‬
‭̀``‬

‭3. **str()**: Converts an object into a string.‬


‭̀``python‬
‭num = 100‬
‭num_str = str(num)‬
‭print(num_str) # Output: "100"‬
‭̀``‬

‭4. **list()**: Converts an iterable (like a tuple or a string) into a list.‬

‭̀``python‬
‭tuple_data = (1, 2, 3)‬
‭list_data = list(tuple_data)‬
‭print(list_data) # Output: [1, 2, 3]‬
‭̀``‬

‭5. **tuple()**: Converts an iterable (like a list or a string) into a tuple.‬

‭̀``python‬
‭list_data = [1, 2, 3]‬
‭tuple_data = tuple(list_data)‬
‭print(tuple_data) # Output: (1, 2, 3)‬
‭̀``‬

‭ . **bool()**: Converts a value to a boolean. Most values are considered `True` in Python,‬
6
‭except for `False`, `None`, `0`, `0.0`, `""` (empty string), `[]` (empty list), `()` (empty tuple), `{}`‬
‭(empty dictionary), and `set()` (empty set), which are considered `False`.‬

‭̀``python‬
‭bool_value = bool("Hello")‬
‭print(bool_value) # Output: True‬
‭̀``‬

‭ hese functions are useful for converting data types to perform different operations or to ensure‬
T
‭compatibility in your code.‬

‭ ‬ ‭Strings:‬

‭Indexing:‬‭You can get the character present in a string‬‭at a specific index.‬

‭̀``python‬
‭str1 = "Hello World"‬
‭str2=str1[6]‬
‭print(str2) # Output: W‬
‭̀``‬
‭ licing‬‭:In Python, string slicing is a way to extract a substring (a portion of a string) by specifying‬
S
‭a start and end index. The syntax for string slicing is as follows:‬

‭̀``python‬
‭string[start:end:step]‬
‭̀``‬

-‭ `start`: The starting index of the slice (inclusive). If omitted, the slice starts from the beginning‬
‭of the string.‬
‭- `end`: The ending index of the slice (exclusive). If omitted, the slice goes to the end of the‬
‭string.‬
‭- `step`: The step size used to select items from the string. If omitted, the default value is `1`.‬

‭Here are some examples of string slicing:‬

‭̀``python‬
‭string = "Hello, World!"‬
‭print(string[0:5]) # Output: Hello‬
‭print(string[7:12]) # Output: World‬
‭print(string[:5]) # Output: Hello (start is omitted, so it starts from the beginning)‬
‭print(string[7:]) # Output: World! (end is omitted, so it goes to the end)‬
‭print(string[::2]) # Output: Hlo ol! (step is 2, so every second character is selected)‬
‭print(string[::-1]) # Output: !dlroW ,olleH (reverse the string)‬
‭̀``‬

‭ tring slicing is a very powerful feature in Python and is commonly used to extract substrings or‬
S
‭manipulate strings.‬

‭String Functions:‬
‭1.‬ ‭capitalize()‬ ‭Converts the first character to upper case‬
‭2.‬ ‭casefold()‬ ‭Converts string into lower case‬
‭3.‬ ‭center()‬ ‭Returns a centered string‬
‭4.‬ ‭count()‬ ‭Returns the number of times a specified value occurs in a string‬
‭5.‬ ‭encode()‬ ‭Returns an encoded version of the string‬
‭6.‬ ‭endswith()‬ ‭Returns true if the string ends with the specified value‬
‭7.‬ ‭expandtabs()‬ ‭Sets the tab size of the string‬
‭8.‬ ‭find()‬ ‭Searches the string for a specified value and returns the position of where‬
‭it was found‬
‭9.‬ ‭format()‬ ‭Formats specified values in a string‬
‭10.‬‭format_map()‬ ‭Formats specified values in a string‬
‭11.‬‭index()‬ ‭Searches the string for a specified value and returns the position of where‬
‭it was found‬
‭12.‬‭isalnum()‬ ‭Returns True if all characters in the string are alphanumeric‬
‭13.‬‭isalpha()‬ ‭Returns True if all characters in the string are in the alphabet‬
‭ 4.‬‭isascii()‬
1 ‭Returns True if all characters in the string are ascii characters‬
‭15.‬‭isdecimal()‬ ‭Returns True if all characters in the string are decimals‬
‭16.‬‭isdigit()‬ ‭Returns True if all characters in the string are digits‬
‭17.‬‭isidentifier()‬ ‭Returns True if the string is an identifier‬
‭18.‬‭islower()‬ ‭Returns True if all characters in the string are lower case‬
‭19.‬‭isnumeric()‬ ‭Returns True if all characters in the string are numeric‬
‭20.‬‭isprintable()‬ ‭Returns True if all characters in the string are printable‬
‭21.‬‭isspace()‬ ‭Returns True if all characters in the string are whitespaces‬
‭22.‬‭istitle()‬ ‭Returns True if the string follows the rules of a title‬
‭23.‬‭isupper()‬ ‭Returns True if all characters in the string are upper case‬
‭24.‬‭join()‬ ‭Converts the elements of an iterable into a string‬
‭25.‬‭ljust()‬ ‭Returns a left justified version of the string‬
‭26.‬‭lower()‬ ‭Converts a string into lower case‬
‭27.‬‭lstrip()‬ ‭Returns a left trim version of the string‬
‭28.‬‭maketrans()‬ ‭Returns a translation table to be used in translations‬
‭29.‬‭partition()‬ ‭Returns a tuple where the string is parted into three parts‬
‭30.‬‭replace()‬ ‭Returns a string where a specified value is replaced with a specified value‬
‭31.‬‭rfind()‬ ‭Searches the string for a specified value and returns the last position of‬
‭where it was found‬
‭32.‬‭rindex()‬ ‭Searches the string for a specified value and returns the last position of‬
‭where it was found‬
‭33.‬‭rjust()‬ ‭Returns a right justified version of the string‬
‭34.‬‭rpartition()‬ ‭Returns a tuple where the string is parted into three parts‬
‭35.‬‭rsplit()‬ ‭Splits the string at the specified separator, and returns a list‬
‭36.‬‭rstrip()‬ ‭Returns a right trim version of the string‬
‭37.‬‭split()‬ ‭Splits the string at the specified separator, and returns a list‬
‭38.‬‭splitlines()‬ ‭Splits the string at line breaks and returns a list‬
‭39.‬‭startswith()‬ ‭Returns true if the string starts with the specified value‬
‭40.‬‭strip()‬ ‭Returns a trimmed version of the string‬
‭41.‬‭swapcase()‬ ‭Swaps cases, lower case becomes upper case and vice versa‬
‭42.‬‭title() Converts the first character of each word to upper case‬
‭43.‬‭translate()‬ ‭Returns a translated string‬
‭44.‬‭upper()‬ ‭Converts a string into upper case‬
‭45.‬‭zfill()‬ ‭Fills the string with a specified number of 0 values at the beginning‬

‭ ote‬‭:‬
n
‭we can use single quotes( ‘ ’ ) and double quotes( “ ” ) in a string by using‬
‭triple quotes( “““ ””” ) while creating strings.‬

‭●‬ ‭Lists:‬
I‭n Python, a list is a collection of items that are ordered and mutable (changeable). Lists are‬
‭created by placing the items inside square brackets `[]`, separated by commas. Here's a basic‬
‭example:‬
‭̀``python‬
‭my_list = [1, 2, 3, 4, “Mango”]‬
‭print(my_list) # Output: [1, 2, 3, 4, ‘Mango’]‬
‭̀``‬

‭ ists can contain items of different data types, including other lists. Here's an example of a‬
L
‭nested list:‬

‭̀``python‬
‭nested_list = ["apple", ["banana", "orange"], "grape"]‬
‭print(nested_list) # Output: ["apple", ["banana", "orange"], "grape"]‬
‭̀``‬

‭ ython provides many built-in functions and methods to work with lists. Here are some common‬
P
‭operations:‬

‭ ccessing Elements‬‭: Elements in a list can be accessed‬‭by their index, starting from 0.‬
A
‭Negative indexing can also be used to access elements from the end of the list.‬

‭̀``python‬
‭my_list = [1, 2, 3, 4, 5]‬
‭my_list[2]=-7‬
‭print(my_list[0]) # Output: 1‬
‭print(my_list[-1]) # Output: 5‬
‭print(my_list[2]) # Output: -7‬
‭̀``‬

‭ licing‬‭: Slicing is used to access a range of elements‬‭in a list. The syntax for slicing is‬
S
‭̀list[start:stop:step]`.‬

‭̀``python‬
‭my_list = [1, 2, 3, 4, 5]‬
‭print(my_list[1:3]) # Output: [2, 3]‬
‭print(my_list[::2]) # Output: [1, 3, 5]‬
‭̀``‬
‭Sorting and Reversing‬‭: Lists can be sorted using the‬‭̀sort()` method (in-place) or the `sorted()`‬
‭function (returns a new sorted list). The `reverse()` method reverses the order of the list.‬

‭̀``python‬
‭my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]‬
‭my_list.sort()‬
‭print(my_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]‬
‭ y_list.reverse()‬
m
‭print(my_list) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]‬

‭ y_list2 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]‬


m
‭my_list2.sort(reverse=True)‬
‭print(my_list2) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]‬
‭̀``‬
‭Functions and Methods of list‬
‭1.‬ ‭append()‬ ‭Adds an element at the end of the list‬
‭2.‬ ‭clear()‬ ‭Removes all the elements from the list‬
‭3.‬ ‭copy()‬ ‭Returns a copy of the list‬
‭4.‬ ‭count()‬ ‭Returns the number of elements with the specified value‬
‭5.‬ ‭extend()‬ ‭Add the elements of a list (or any iterable), to the end of the current list‬
‭6.‬ ‭index()‬ ‭Returns the index of the first element with the specified value‬
‭7.‬ ‭insert()‬ ‭Adds an element at the specified position‬
‭8.‬ ‭pop()‬ ‭Removes the element at the specified position‬
‭9.‬ ‭remove()‬ ‭Removes the first item with the specified value‬
‭10.‬‭reverse()‬ ‭Reverses the order of the list‬
‭11.‬‭sort()‬ ‭Sorts the list‬

‭●‬ ‭Tuples:‬
I‭n Python, a tuple is a collection of items that are ordered and immutable (unchangeable).‬
‭Tuples are created by placing the items inside parentheses `()`, separated by commas. Here's a‬
‭basic example:‬

‭̀``python‬
‭my_tuple = (1, 2, 3, 4, 5)‬
‭print(my_tuple) # Output: (1, 2, 3, 4, 5)‬
‭̀``‬

‭ uples can contain items of different data types, including other tuples. Here's an example of a‬
T
‭nested tuple:‬

‭̀``python‬
‭nested_tuple = ("apple", ("banana", "orange"), "grape")‬
‭print(nested_tuple) # Output: ("apple", ("banana", "orange"), "grape")‬
‭̀``‬

‭ ython provides many built-in functions and methods to work with tuples. Here are some‬
P
‭common operations:‬

‭1. **Accessing Elements**: Elements in a tuple can be accessed by their index, similar to lists.‬

‭̀``python‬
‭ y_tuple = (1, 2, 3, 4, 5)‬
m
‭print(my_tuple[0]) # Output: 1‬
‭print(my_tuple[-1]) # Output: 5‬
‭̀``‬

‭2. **Slicing**: Slicing is used to access a range of elements in a tuple, similar to lists.‬

‭̀``python‬
‭my_tuple = (1, 2, 3, 4, 5)‬
‭print(my_tuple[1:3]) # Output: (2, 3)‬
‭print(my_tuple[::-1]) # Output: (5, 4, 3, 2, 1)‬
‭̀``‬

‭ . **Unpacking**: Tuple unpacking allows you to assign the elements of a tuple to multiple‬
3
‭variables in a single statement.‬

‭̀``python‬
‭my_tuple = (1, 2, 3)‬
‭a, b, c = my_tuple‬
‭print(a, b, c) # Output: 1 2 3‬
‭̀``‬

‭4. **Concatenating Tuples**: Tuples can be concatenated using the `+` operator.‬

‭̀``python‬
‭tuple1 = (1, 2, 3)‬
‭tuple2 = (4, 5, 6)‬
‭combined_tuple = tuple1 + tuple2‬
‭print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)‬
‭̀``‬

‭5. **Repeating Tuples**: Tuples can be repeated using the `*` operator.‬

‭̀``python‬
‭my_tuple = (1, 2, 3)‬
‭repeated_tuple = my_tuple * 3‬
‭print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)‬
‭̀``‬
‭Functions and Methods of list‬
‭1.‬ ‭count()‬ ‭Returns the number of times a specified value occurs in a tuple‬
‭2.‬ ‭index()‬ ‭Searches the tuple for a specified value and returns the position of where‬
‭it was found‬
‭ ote:‬
N
‭Tuples are often used to store data that should not be changed, such as coordinates, database‬
‭records, or function arguments. While tuples are immutable, they can contain mutable objects‬
‭like lists, which can be changed.‬

‭ ‬ ‭Dictionary:‬

‭In Python, a dictionary is a collection of key-value pairs. It is a mutable, unordered collection‬
‭that is often used to store data in a way that is easy to retrieve and manipulate. Each key in a‬
‭dictionary must be unique, and the keys are typically immutable types (such as strings,‬
‭numbers, or tuples).‬

‭Here's a basic example of creating and using a dictionary:‬

‭̀``python‬
‭# Creating a dictionary‬
‭my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}‬

‭ Accessing values in a dictionary‬


#
‭print(my_dict['name']) # Output: Alice‬
‭print(my_dict['age']) # Output: 30‬

‭ Modifying values in a dictionary‬


#
‭my_dict['age'] = 31‬
‭print(my_dict['age']) # Output: 31‬

‭ Adding a new key-value pair‬


#
‭my_dict['gender'] = 'Female'‬
‭print(my_dict['gender']) # Output: Female‬

‭ Removing a key-value pair‬


#
‭del my_dict['city']‬
‭print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'gender': 'Female'}‬

‭ Checking if a key exists‬


#
‭if 'name' in my_dict:‬
‭print('Name:', my_dict['name']) # Output: Name: Alice‬

‭ Iterating over keys in a dictionary‬


#
‭for key in my_dict:‬
‭print(key, ':', my_dict[key])‬
‭̀``‬

‭ ictionaries are very versatile and are used in various situations where you need to map keys to‬
D
‭values efficiently‬
‭ ethods and functions in Dictionaries:‬
M
‭clear()‬ ‭Removes all the elements from the dictionary‬
‭copy()‬ ‭Returns a copy of the dictionary‬
‭fromkeys()‬ ‭Returns a dictionary with the specified keys and value‬
‭get()‬ ‭Returns the value of the specified key, returns none if key is not present‬
‭items()‬ ‭Returns a list containing a tuple for each key value pair‬
‭keys()‬ ‭Returns a list containing the dictionary's keys‬
‭pop()‬ ‭Removes the element with the specified key‬
‭popitem()‬ ‭Removes the last inserted key-value pair‬
‭setdefault()‬ ‭Returns the value of the specified key. If the key does not exist: insert the key,‬
‭with the specified value‬
‭update()‬ ‭Updates the dictionary with the specified key-value pairs‬
‭values()‬ ‭Returns a list of all the values in the dictionary‬

‭ ets:‬
S
‭In Python, a set is an‬‭unordered collection of unique‬‭elements and each element must be‬
‭immutable‬‭. It is a mutable data type, meaning that‬‭you can add or remove elements from it.‬
‭Sets are particularly useful for operations that require checking for membership, removing‬
‭duplicates from a sequence, and performing mathematical operations like union, intersection,‬
‭difference, and symmetric difference.‬

‭- Creating a set:‬

‭- Creating a Empty_set:‬

‭̀``python‬
‭my_set = set()‬
‭print(my_set) #set()‬
‭̀``‬

‭̀``python‬
‭my_set = {1, 2, 3, 4, 5}‬
‭print(my_set) # Output: {1, 2, 3, 4, 5}‬
‭̀``‬

‭- Adding elements to a set:‬

‭̀``python‬
‭my_set.add(6)‬
‭print(my_set) # Output: {1, 2, 3, 4, 5, 6}‬
‭̀``‬

‭- Removing elements from a set:‬


‭̀``python‬
‭my_set.remove(3)‬
‭print(my_set) # Output: {1, 2, 4, 5, 6}‬
‭̀``‬

‭- Checking membership:‬

‭̀``python‬
‭print(2 in my_set) # Output: True‬
‭print(3 in my_set) # Output: False‬
‭̀``‬

‭- Set operations:‬

‭̀``python‬
‭set1 = {1, 2, 3, 4, 5}‬
‭set2 = {4, 5, 6, 7, 8}‬

‭ Union‬
#
‭print([Link](set2)) # Output: {1, 2, 3, 4, 5, 6, 7, 8}‬

‭ Intersection‬
#
‭print([Link](set2)) # Output: {4, 5}‬

‭ Difference‬
#
‭print([Link](set2)) # Output: {1, 2, 3}‬

‭ Symmetric difference‬
#
‭print(set1.symmetric_difference(set2)) # Output: {1, 2, 3, 6, 7, 8}‬
‭̀``‬

‭ ets are very efficient for membership testing and eliminating duplicate entries from a‬
S
‭sequence. They also support a variety of mathematical operations that make them useful in‬
‭many programming scenarios.‬

‭ et methods:‬
S
‭add()‬ ‭Adds an element to the set‬
‭clear()‬ ‭Removes all the elements from the set‬
‭copy()‬ ‭Returns a copy of the set‬
‭difference()‬ ‭Returns a set containing the difference between two or more sets‬
‭difference_update()‬ ‭Removes the items in this set that are also included in another, specified‬
‭set‬
‭discard()‬ ‭Remove the specified item‬
‭intersection()‬ ‭Returns a set, that is the intersection of two or more sets‬
i‭ntersection_update()‬ ‭Removes the items in this set that are not present in other, specified‬
‭set(s)‬
‭isdisjoint()‬ ‭Returns whether two sets have a intersection or not‬
‭issubset()‬ ‭Returns whether another set contains this set or not‬
‭issuperset()‬ ‭Returns whether this set contains another set or not‬
‭pop()‬ ‭Removes an element from the set‬
‭remove()‬ ‭Removes the specified element‬
‭symmetric_difference()‬ ‭Returns a set with the symmetric differences of two sets‬
‭symmetric_difference_update()‬ ‭inserts the symmetric differences from this set and another‬
‭union()‬ ‭Return a set containing the union of sets‬
‭update()‬ ‭Update the set with another set, or any other iterable‬

‭●‬ ‭loop:‬
‭ hile loop:‬
w
‭In Python, a `while` loop is used to repeatedly execute a block of code as long as a specified‬
‭condition is true. The syntax of a `while` loop is as follows:‬

‭̀``python‬
‭while condition:‬
‭# Code block to be executed‬
‭̀``‬

‭ he `condition` is evaluated before each iteration. If the `condition` evaluates to `True`, the code‬
T
‭block inside the `while` loop is executed. Once the `condition` becomes `False`, the loop stops‬
‭and the program continues with the next section of code after the `while` loop.‬

‭Here's a simple example of a `while` loop that counts from 1 to 5:‬

‭̀``python‬
‭count = 1‬
‭while count <= 5:‬
‭print(count)‬
‭count += 1‬
‭̀``‬

I‭n this example, the `count` variable is initially set to 1. The `while` loop continues to execute as‬
‭long as `count` is less than or equal to 5. Inside the loop, the current value of `count` is printed,‬
‭and then `count` is incremented by 1 using `count += 1`. The loop stops when `count` becomes‬
‭6 (i.e., when the condition `count <= 5` is no longer `True`).‬

I‭t's important to ensure that the condition in a `while` loop will eventually become `False`,‬
‭otherwise, the loop will run indefinitely, resulting in what is known as an infinite loop.‬
f‭or loop:‬
‭In Python, a `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range)‬
‭or any iterable object. The syntax of a `for` loop is as follows:‬

‭̀``python‬
‭for item in sequence:‬
‭# Code block to be executed for each item‬
‭̀``‬

I‭n each iteration of the loop, the variable `item` is assigned the next value from the `sequence`,‬
‭and the code block inside the `for` loop is executed with this value. The loop continues until all‬
‭items in the `sequence` have been processed.‬

‭ ere's a simple example of a `for` loop that iterates over a list of numbers and calculates their‬
H
‭sum:‬

‭̀``python‬
‭numbers = [1, 2, 3, 4, 5]‬
‭sum = 0‬
‭for number in numbers:‬
‭sum += number‬
‭print("Sum:", sum)‬
‭̀``‬

I‭n this example, the `for` loop iterates over each number in the `numbers` list, and the variable‬
‭̀number` takes on each value in the list in turn. The `sum` variable is used to accumulate the‬
‭total sum of all numbers in the list.‬

‭ ython `for` loop can also be used with the `range()` function to iterate over a sequence of‬
P
‭numbers. For example, to print numbers from 0 to 4:‬

‭̀``python‬
‭for i in range(5):‬
‭print(i)‬
‭̀``‬

‭This will output:‬

‭̀``‬
‭0‬
‭1‬
‭2‬
‭3‬
‭4‬
‭̀``‬

I‭n this example, `range(5)` generates a sequence of numbers from 0 to 4, and the `for` loop‬
‭iterates over each number in this sequence, assigning it to the variable `i` in each iteration.‬

‭Certainly! Here are some additional details about `for` loops in Python:‬

‭1. **Iterating Over a String:** You can use a `for` loop to iterate over each character in a string:‬

‭̀``python‬
‭for char in "Hello":‬
‭print(char)‬
‭̀``‬

‭This will output each character of the string "Hello" on a new line.‬

‭ . **Iterating Over a Dictionary:** When iterating over a dictionary, the `for` loop iterates over its‬
2
‭keys by default. You can use the `items()` method to iterate over key-value pairs:‬

‭̀``python‬
‭my_dict = {'a': 1, 'b': 2, 'c': 3}‬
‭for key in my_dict:‬
‭print(key, "->", my_dict[key])‬

‭ Using items()‬
#
‭for key, value in my_dict.items():‬
‭print(key, "->", value)‬
‭̀``‬

‭ . **Using `enumerate()`:** If you need both the index and the value of each item in a sequence,‬
3
‭you can use the `enumerate()` function:‬

‭̀``python‬
‭for index, value in enumerate(["a", "b", "c"]):‬
‭print(f"Index: {index}, Value: {value}")‬
‭̀``‬

‭ . **Skipping Items with `continue`:** You can use the `continue` statement to skip the rest of‬
4
‭the code block for the current iteration and move to the next iteration:‬

‭̀``python‬
‭for i in range(10):‬
‭if i % 2 == 0:‬
‭ ontinue‬
c
‭print(i)‬
‭̀``‬

‭This will print only the odd numbers from 0 to 9.‬

‭ . **Breaking Out of a Loop with `break`:** You can use the `break` statement to exit the loop‬
5
‭prematurely:‬

‭̀``python‬
‭for i in range(10):‬
‭if i == 5:‬
‭break‬
‭print(i)‬
‭̀``‬

‭This will print numbers from 0 to 4 and then exit the loop when `i` reaches 5.‬

‭6. pass:To not do any work in the loop it acts as placeholder for future code‬
‭̀``python‬
‭for i in range(10):‬
‭pass‬
‭̀``‬
‭This will not throw any error, if pass would not be used it would have showed error‬

‭ else:use of else at the end of for loop [Link] break is executed else is not executed.‬
7
‭if the for loop is executed till the end the else is executed‬

‭̀``python‬
‭for char in "Mangow":‬
‭print(char)‬
‭if(char=="m"):‬
‭print("Character o has been found")‬
‭break‬
‭else:‬
‭print("Character o is not found")‬
‭̀``‬
‭Note:‬
‭Range(Start?,Stop,Step?)‬
‭It is a function which gives Sequence of numbers starting from 0 by default if not mentioned,‬
‭and increment by 1 if not mentioned, and stops before a specified number.‬
‭●‬ F
‭ ile Input/Output Operations‬
‭File input/output (I/O) in Python is a fundamental operation for working with files. You‬
‭can use the `open()` function to open a file and perform various operations like reading,‬
‭writing, or appending data to it. Here's a basic overview:‬

‭ ## Reading from a File‬


#
‭You can use the `open()` function with the mode `'r'` to open a file for reading:‬

‭̀``python‬
‭with open('[Link]', 'r') as file:‬
‭data = [Link]()‬
‭print(data)‬
‭̀``‬

‭ ## Writing to a File‬
#
‭To write to a file, use the mode `'w'`. This will create a new file if it doesn't exist or‬
‭truncate the file if it does exist:‬

‭̀``python‬
‭with open('[Link]', 'w') as file:‬
‭[Link]('Hello, world!')‬
‭̀``‬

‭ ## Appending to a File‬
#
‭To append data to an existing file, use the mode `'a'`:‬

‭̀``python‬
‭with open('[Link]', 'a') as file:‬
‭[Link]('Appending a new line!')‬
‭̀``‬

‭ ## Reading File Line by Line‬


#
‭You can also read a file line by line using a `for` loop:‬

‭̀``python‬
‭with open('[Link]', 'r') as file:‬
‭for line in file:‬
‭print(line)‬
‭̀``‬

‭ ## Closing Files‬
#
‭It's important to close files after you're done with them to free up system resources.‬
‭Using the `with` statement as shown above automatically closes the file when the block‬
‭is exited.‬
‭ ## Handling Exceptions‬
#
‭File operations can raise exceptions, so it's a good practice to handle them, especially‬
‭when dealing with file I/O:‬

‭̀``python‬
‭try:‬
‭with open('[Link]', 'r') as file:‬
‭data = [Link]()‬
‭print(data)‬
‭except FileNotFoundError:‬
‭print("File not found!")‬
‭except IOError:‬
‭print("An error occurred while reading the file.")‬
‭̀``‬

‭ lways remember to replace `'[Link]'` with the actual path to the file you want to‬
A
‭read from or write to.‬
‭ ote:‬
n
‭The argument mode points to a string beginning with one of the following‬
‭sequences (Additional characters may follow these sequences.):‬

‭̀`r'' Open text file for reading. The stream is positioned at the‬
‭beginning of the file.‬

‭̀`r+'' Open for reading and writing. The stream is positioned at the‬
‭beginning of the file.‬

‭̀`w'' Truncate file to zero length or create text file for writing.‬
‭The stream is positioned at the beginning of the file.‬

‭̀`w+'' Open for reading and writing. The file is created if it does not‬
‭exist, otherwise it is truncated. The stream is positioned at‬
‭the beginning of the file.‬

‭̀`a'' Open for writing. The file is created if it does not exist. The‬
‭stream is positioned at the end of the file. Subsequent writes‬
‭to the file will always end up at the then current end of file,‬
‭irrespective of any intervening fseek(3) or similar.‬

‭̀`a+'' Open for reading and writing. The file is created if it does not‬
‭exist. The stream is positioned at the end of the file. Subsequent‬
‭writes to the file will always end up at the then current‬
‭end of file, irrespective of any intervening fseek(3) or similar.‬
‭ ## Deleting a file:‬
#
‭You can delete a file in Python using the `os` module's `remove()` function. Here's an example:‬

‭̀``python‬
‭import os‬

‭ Specify the file path‬


#
‭file_path = '[Link]'‬

‭ Check if the file exists before trying to delete it‬


#
‭if [Link](file_path):‬
‭[Link](file_path)‬
‭print(f"File '{file_path}' deleted successfully.")‬
‭else:‬
‭print(f"File '{file_path}' not found.")‬
‭̀``‬

‭ ake sure to replace `'[Link]'` with the path to the file you want to delete. This code first‬
M
‭checks if the file exists using `[Link]()` and then deletes it using `[Link]()` if it does.‬

You might also like