Python Complete notes with code and explanation in hindi english both language.

                                               

                                                         PYTHON 

Q1:- What is python programming language?

Answer:-      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 simplicity, making.

👉 it a popular choice for beginners and experienced programmers alike.


Key features of Python include:-------------------


1. **Easy-to-Read Syntax**: Python's syntax is designed to be intuitive and easy to understand, which reduces the cost of program maintenance and development.

2. **Interpreted Language**: Python is an interpreted language, meaning that code is executed line by line, rather than compiled into machine code beforehand. This makes it easy to write and test code quickly.

3. **High-Level Language**: Python provides abstractions that allow developers to focus on solving problems rather than dealing with low-level details such as memory management.

4. **Dynamically Typed**: Python is dynamically typed, which means that you don't need to declare the type of a variable before using it. The interpreter infers the type of variables at runtime.

5. **Extensive Standard Library**: Python comes with a large standard library that provides modules and packages for a wide range of tasks, such as file I/O, networking, database access, and more.

6. **Cross-Platform**: Python is available on various platforms, including Windows, macOS, and Linux, making it easy to write code that can run on different operating systems without modification.

7. **Open Source**: Python is developed under an OSI-approved open-source license, which means that anyone can contribute to its development and use it freely.

Python is widely used in various domains, including web development, data analysis, machine learning, artificial intelligence, scientific computing, and more. Its versatility and ease of use make it one of the most popular programming languages in the world. 

Q2:- What is print function in python?

Answer:-In Python, the print() function is used to display output to the console or terminal. It takes one or more arguments, which can be of various types, and prints their values to the standard output.

Here's the basic syntax of the print() function:

pytho
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • value1, value2, etc.: These are the values to be printed. You can pass multiple values separated by commas.
  • sep: This is an optional parameter that specifies the separator between the values. By default, it is a space character.
  • end: This is an optional parameter that specifies what to print at the end. By default, it is a newline character (\n), which means that the next print() statement will start on a new line. You can change it to any string you want.
  • file: This is an optional parameter that specifies the file where the output will be printed. By default, it is sys.stdout, which represents the standard output (usually the console or terminal).
  • flush: This is an optional boolean parameter that specifies whether the output buffer should be flushed after printing. By default, it is False.

Here are some examples of using the print() .

# Print a single value print("Hello, world!") # Print multiple values separated by a comma print("Hello", "world!") # Change the separator print("Hello", "world!", sep=', ') # Change the end character print("Hello", end=' ') print("world!") # Writing to a file with open('output.txt', 'w') as f: print("Hello, world!", file=f)

The print() function is commonly used for debugging(debugging means we can red after break long code in sort form), displaying program output, and providing feedback to users during program execution. It's one of the fundamental functions in Python for outputting information.

Q3:-What is Data Types in python?

Answer:- In Python, data types represent the type of data that can be stored and manipulated in a program. Python supports several built-in data types, including: 1. **Numeric Types**: - **int**: Integer numbers, e.g., 5, -3, 1000. - **float**: Floating-point numbers, e.g., 3.14, -0.001, 2.0. - **complex**: Complex numbers, in the form `a + bj`, where `a` and `b` are real numbers and `j` is the imaginary unit. 2. **Sequence Types**: - **str**: String, a sequence of characters enclosed within single quotes (`'`) or double quotes (`"`), e.g., 'hello', "world". - **list**: Ordered collection of items, mutable (modifiable), and enclosed within square brackets (`[]`), e.g., `[1, 2, 3]`. - **tuple**: Ordered collection of items, immutable (cannot be modified after creation), and enclosed within parentheses (`()`), e.g., `(1, 2, 3)`. 3. **Mapping Type**: - **dict**: Collection of key-value pairs, mutable, and enclosed within curly braces (`{}`), e.g., `{'name': 'John', 'age': 30}`. 4. **Set Types**: - **set**: Unordered collection of unique items, mutable, and enclosed within curly braces (`{}`), e.g., `{1, 2, 3}`. - **frozenset**: Similar to sets but immutable, enclosed within curly braces (`{}`). 5. **Boolean Type**: - **bool**: Represents boolean values `True` or `False`, used for logical operations and comparisons. 6. **None Type**: - **None**: Represents the absence of a value or a null value. Python also allows users to create custom data types using classes, which are part of the object-oriented programming (OOP) paradigm supported by Python. Each data type has its own set of operations and methods that can be performed on it. Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable; Python determines the data type automatically based on the value assigned to the variable. Additionally, Python supports type hinting, allowing developers to specify the expected data types for function arguments and return values, although it is optional and mainly used for documentation and static analysis purposes.

Q4:-What is python variable ?

Answer:-Python variables are fundamental components in programming that store data values. Here's a breakdown of key points regarding Python variables: 1. **Variable Declaration**: - In Python, you don't need to declare variables explicitly with their data types before using them. You simply assign a value to a variable. - Variables are created the moment you first assign a value to them. 2. **Variable Naming Rules**: - Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (_). - They must begin with a letter or an underscore. - Variable names are case-sensitive (`age` and `Age` are different variables). - Python has reserved keywords that cannot be used as variable names (e.g., `if`, `else`, `while`, `for`, `def`, `class`, etc.).Total 32 reserved keyword in python.

import keyword

s=keyword.kwlist

print(s) 3. **Assigning Values**: - Values are assigned to variables using the assignment operator `=`. - The type of a variable is determined by the value assigned to it. Python is dynamically typed, meaning the type of the variable is inferred at runtime. 4. **Data Types**: - Variables can hold values of different data types such as integers, floats, strings, lists, tuples, dictionaries, etc. 5. **Example**: ```python # Variable assignment name = "John" #String type age = 30 #integer type(python me character type nhi hota only string type hota hai) salary = 2500.50 # Float type hai. is_student = False # Boolean type hai # Printing variable values print(name) # Output: John print(age) # Output: 30 print(salary) # Output: 2500.5 print(is_student) # Output: False ``` 6. **Variable Reassignment**: - You can change the value of a variable by assigning it a new value. ```python age = 30 age = age + 1 # Increment age by 1 print(age) # Output: 31 ``` 7. **Memory Management**: - Python manages memory allocation and deallocation automatically. - Variables in Python are references to objects in memory. 8. **Variable Scope**: - The scope of a variable determines where in the code a variable can be accessed. - Variables defined inside a function have local scope, while variables defined outside functions have global scope. - Changes made to global variables inside a function require the `global` keyword. Python's flexibility with variables, along with its dynamic typing and easy syntax, makes it a popular choice for developers across various domains. Understanding how variables work is fundamental to writing Python code effectively.

Q5:- What is python comments?

Answer:-Python me comments # (hash) character se likhe jaate hain. Python interpreter comments ko program execution ke dauran ignore karta hai. Yeh kuch key points hain comments ke baare mein:

  1. Syntax:

    • Python me comments # character se shuru hote hain aur line ke ant tak chalte hain.
    • # ke baad ki sab kuch us line par comment ke roop mein consider hota hai.
  2. Ek-Line Ke Comments:

    • Ek-line ke comments ek line ke code ko explain karne ke liye istemal kiye jaate hain.
    python
    # Ye ek-line ka comment hai print("Hello, world!") # Ye bhi ek comment hai
  3. Multi-Line Comments:

    • Python me multi-line comments ke liye koi built-in syntax nahi hai.
    • Haalaanki, aap multi-line strings (''' ya """) ka istemaal kar sakte hain multi-line comments ke roop mein.
    • Yeh ek standard tareeka nahi hai lekin lambi comments ya documentation ke liye aksar istemal hota hai.
    python
    ''' Ye ek multi-line comment hai. Ye kai lines par span karta hai. '''
  4. ''' Ye ek multi-line comment hai. Ye kai lines par span karta hai. '''


  5. Udeshya:

    • Comments code ka udeshya samjhaane, complex logic ko spasht karna, function ke parameters aur return values ko document karna, aur code ke design aur implementation ke baare mein jaankari pradaan karna ke liye istemal kiye jaate hain.
    • Ye code ko padhne aur maintain karne mein madad karte hain aur code ko samajhne mein asaan banate hain.
    • Q6:- Python Keyword and Identifier .
    • Answer:-
    • In Python, keywords and identifiers play crucial roles in defining the structure and behavior of programs. Here's an overview of Python keywords and identifiers: ### 1. Keywords: Keywords are reserved words that have special meanings and purposes in Python. These words are predefined by the language and cannot be used as identifiers (variable names, function names, etc.). Python has a fixed set of keywords. Here's a list of Python keywords (as of Python 3.9): ```plaintext False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield ``` ### 2. Identifiers: Identifiers are names given to entities in a Python program. These entities can include variables, functions, classes, modules, etc. Here are the rules for naming identifiers in Python: - Identifiers can contain letters (a-z, A-Z), digits (0-9), and underscores (_). - They must begin with a letter or an underscore. - Identifiers are case-sensitive (`age` and `Age` are different identifiers). - Python keywords cannot be used as identifiers. - Identifiers cannot contain special symbols such as `!`, `@`, `#`, `$`, `%`, etc. - They should follow a descriptive naming convention to improve code readability. - Avoid using single-character identifiers, except in specific cases where their meaning is clear (e.g., loop variables). Examples of valid identifiers: ```python my_variable = 10 myFunction = lambda x: x * 2 MyClass = MyClass() ``` Examples of invalid identifiers: ```python 2nd_variable = 5 # Identifier cannot start with a digit for = 10 # 'for' is a keyword and cannot be used as an identifier my-variable = 5 # Hyphens are not allowed in identifiers ``` Understanding keywords and using appropriate identifiers is essential for writing clear, understandable, and maintainable Python code.
Q7:-How to take input with user?
Answer:-In Python, you can use the `input()` function to take input from the user through the keyboard. The `input()` function reads a line of text from the standard input (usually the keyboard) and returns it as a string. Here's a basic example: ```python # Taking input from the user name = input("Enter your name: ") # Displaying the input provided by the user print("Hello, " + name + "! Welcome!") ``` In this example: - `input("Enter your name: ")` prompts the user to enter their name, and the message "Enter your name: " is displayed. - Whatever the user types in response to the prompt is stored in the variable `name`. - The `print()` function then displays a personalized greeting message using the input provided by the user. Keep in mind that the `input()` function always returns a string, even if the user enters a number or other data type. If you need to convert the input to a different data type, you can use type casting. For example, if you want to take an integer input: ```python # Taking integer input from the user age = int(input("Enter your age: ")) # Displaying the input provided by the user print("You are", age, "years old.") ``` In this case, `int()` is used to convert the string returned by `input()` into an integer before storing it in the variable `age`. This ensures that the program can perform arithmetic operations or comparisons with the user's input as integers.
Q8:-Python type conversion?
Answer:-
  1. int(): Converts a value to an integer. If the value cannot be converted to an integer, a ValueError will be raised.

    python
    num_str = "123" num_int = int(num_str) print(num_int) # Output: 123
  2. float(): Converts a value to a floating-point number (decimal). If the value cannot be converted to a float, a ValueError will be raised.

    python
    num_str = "3.14" num_float = float(num_str) print(num_float) # Output: 3.14
  3. str(): Converts a value to a string.

    python
    num_int = 123 num_str = str(num_int) print(num_str) # Output: '123'
  4. bool(): Converts a value to a boolean. Certain values, like 0, an empty string '', an empty list [], etc., will be considered False, while others will be considered True.

    pythonode
    num_int = 0 is_true = bool(num_int) print(is_true) # Output: False
  5. list(): Converts a sequence (e.g., tuple, string, etc.) to a list.

    pythonopy code
    my_tuple = (1, 2, 3) my_list = list(my_tuple) print(my_list) # Output: [1, 2, 3]
  6. tuple(): Converts a sequence (e.g., list, string, etc.) to a tuple.

    pythonpy code
    my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # Output: (1, 2, 3)
  7. set(): Converts a sequence (e.g., list, tuple, string, etc.) to a set.

    pythonCopy code
    my_list = [1, 2, 2, 3, 3, 3] my_set = set(my_list) print(my_set) # Output: {1, 2, 3}

These are some of the basic type conversion functions available in Python. They are useful for manipulating data and performing operations based on different data types in your programs.

Q9:- What is python literals?

Answer:-In Python, literals are data values that are directly written into the source code. They represent fixed values that are not assigned to variables. Python supports various types of literals, including:

  1. Numeric Literals:

    • Integer literals: Whole numbers without any decimal point, e.g., 123, -456, 0.
    • Floating-point literals: Numbers with a decimal point or in exponential form, e.g., 3.14, -0.001, 2e3.
  2. String Literals:

    • String literals represent sequences of characters enclosed within single quotes (') or double quotes ("), e.g., 'hello', "world".
    • Triple quotes (''' or """) can be used for multiline string literals.
  3. Boolean Literals:

    • Boolean literals represent the truth values True and False.
  4. None Literal:

    • The None literal represents the absence of a value or a null value.
  5. Sequence Literals:

    • List literals: Ordered collection of items enclosed within square brackets ([]), e.g., [1, 2, 3].
    • Tuple literals: Ordered collection of items enclosed within parentheses (()), e.g., (1, 2, 3).
    • Set literals: Unordered collection of unique items enclosed within curly braces ({}), e.g., {1, 2, 3}.
    • Dictionary literals: Collection of key-value pairs enclosed within curly braces ({}), e.g., {'name': 'John', 'age': 30}.
  6. Special Literals:

    • True, False, and None are considered special literals in Python.

Example of using literals in Python:

python
# Numeric literals num_integer = 123 num_float = 3.14 # String literals str_single_quote = 'hello' str_double_quote = "world" # Boolean literals is_true = True is_false = False # None literal null_value = None # Sequence literals list_literal = [1, 2, 3] tuple_literal = (4, 5, 6) set_literal = {7, 8, 9} dict_literal = {'name': 'Alice', 'age': 25}

Literals provide a convenient way to represent fixed values directly within the source code of Python programs.


Python Operator +if+else+Loops

Q1:-


Like , Share & Subscribe my channel........

Comments

Popular posts from this blog

Overall company coding pratics with full concepts in python language.

Find the largest three distinct elements in an array