Python is a high-level, interpreted, and dynamically typed programming language. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability and simplicity, making it an excellent choice for beginners and experienced developers alike.
Features of Python
- Simple and Easy to Learn: Python has a clear and easy-to-understand syntax.
- Interpreted Language: Python code is executed line by line, which makes debugging easier.
- Dynamically Typed: No need to declare data types explicitly; the interpreter assigns types automatically.
- Platform Independent: Python code can run on different platforms like Windows, macOS, and Linux without modification.
- Extensive Libraries: Python has a rich set of libraries and frameworks, such as NumPy, Pandas, and TensorFlow, for various applications.
- Object-Oriented: Python supports object-oriented programming concepts like classes and inheritance.
- Open Source: Python is free to use and distribute.
- Scalable: Python is suitable for both small and large-scale projects.
Uses of Python
- Web Development: Frameworks like Django and Flask.
- Data Science: Libraries like Pandas, NumPy, and Matplotlib.
- Artificial Intelligence and Machine Learning: Tools like TensorFlow and Scikit-learn.
- Automation and Scripting: Automating repetitive tasks.
- Game Development: Libraries like Pygame.
- Desktop Applications: GUI development using Tkinter or PyQt.
- Networking: Building network tools and servers.
Comments in Python
- Use hashtag # in front of the comment for single line comment but there is no multiline comment in python.
- You can use triple single quote ‘ ‘ ‘ for multiline comment like ‘ ‘ ‘ Comment ‘ ‘ ‘ but it also act as data.
Using Python Compilers
Using Browser
Use online OnlineGDB “https://www.onlinegdb.com/” or any other compiler and Python as language
Installing Application
- Download and install through the Official Python3 Website: “https://www.python.org/downloads/“
- For Windows after installing Check Python Path is in Environment Variables :System: Path where address of python is located or not in. If not add the path. If you don’t have any idea please search in google or YouTube or ChatGPT.
- Use Visual Studio Code or any text editor to write and compile the python file whose extension is
.py. - You can also use Jupyter Notebook for easy compiling and data analysis.
Basic Syntax in Python
# This is a simple Python program
print("Hello World!") #Printing string Hello World!
print(5) #Printing number 5
Input Output
a = int(input("Enter any number: ")) # Input number a as integer
print(a) #Output produce any value you have entered
Data Types in Python
The following table provides details about Python’s standard data types, examples, and memory usage:
| Data Type | Description | Example | Memory Usage |
|---|---|---|---|
int | Integer values | 10, -5 | Depends on value (unbounded) |
float | Floating-point numbers | 3.14, -0.01 | 24 bytes (approx.) |
complex | Complex numbers | 3+4j, -5+2j | 32 bytes (approx.) |
str | Strings | 'Hello', "Python" | 49 bytes + length of string |
list | Ordered, mutable collections | [1, 2, 3] | 64 bytes + elements’ size |
tuple | Ordered, immutable collections | (1, 2, 3) | 48 bytes + elements’ size |
set | Unordered unique collections | {1, 2, 3} | 224 bytes + elements’ size |
frozenset | Immutable sets | frozenset([1, 2]) | Similar to set |
dict | Key-value pairs | {"key": "value"} | 240 bytes + keys/values’ size |
bool | Boolean values | True, False | 28 bytes |
bytes | Immutable byte sequences | b"data" | 33 bytes + data length |
bytearray | Mutable byte sequences | bytearray(4) | Similar to bytes |
memoryview | Memory view of bytes | memoryview(b"abc") | Depends on the source object |
None | Represents no value | None | 16 bytes |
Operators in Python
| Category | Operator | Description | Example |
|---|---|---|---|
| Arithmetic | + | Addition | 3 + 2 → 5 |
- | Subtraction | 3 - 2 → 1 | |
* | Multiplication | 3 * 2 → 6 | |
/ | Division (float result) | 3 / 2 → 1.5 | |
// | Floor division (integer result) | 3 // 2 → 1 | |
% | Modulus (remainder of division) | 3 % 2 → 1 | |
** | Exponentiation (power) | 3 ** 2 → 9 | |
| Comparison | == | Equal to | 3 == 3 → True |
!= | Not equal to | 3 != 2 → True | |
> | Greater than | 3 > 2 → True | |
< | Less than | 3 < 2 → False | |
>= | Greater than or equal to | 3 >= 2 → True | |
<= | Less than or equal to | 3 <= 2 → False | |
| Logical | and | Logical AND (both must be True) | True and False → False |
or | Logical OR (at least one must be True) | True or False → True | |
not | Logical NOT (negates the value) | not True → False | |
| Identity | is | Checks if two variables point to the same object in memory | a is b → True or False |
is not | Checks if two variables do not point to the same object | a is not b → True or False | |
| Membership | in | Checks if a value exists in a sequence (list, string, etc.) | 'a' in 'apple' → True |
not in | Checks if a value does not exist in a sequence | 'z' not in 'apple' → True | |
| Assignment | = | Assignment operator (assigns value to a variable) | x = 5 |
+= | Add and assign (increment by a value) | x += 5 → x = x + 5 | |
-= | Subtract and assign (decrement by a value) | x -= 5 → x = x - 5 | |
*= | Multiply and assign (multiply by a value) | x *= 5 → x = x * 5 | |
/= | Divide and assign (divide by a value) | x /= 5 → x = x / 5 | |
//= | Floor divide and assign (integer division) | x //= 5 → x = x // 5 | |
%= | Modulus and assign (assign remainder) | x %= 5 → x = x % 5 | |
**= | Exponentiate and assign (raise to a power) | x **= 5 → x = x ** 5 | |
&= | Bitwise AND and assign | x &= 3 → x = x & 3 | |
| ` | =` | Bitwise OR and assign | |
^= | Bitwise XOR and assign | x ^= 3 → x = x ^ 3 | |
<<= | Left shift and assign | x <<= 3 → x = x << 3 | |
>>= | Right shift and assign | x >>= 3 → x = x >> 3 | |
| Bitwise | & | Bitwise AND (bit by bit AND) | 5 & 3 → 1 |
| ` | ` | Bitwise OR (bit by bit OR) | |
^ | Bitwise XOR (bit by bit XOR) | 5 ^ 3 → 6 | |
~ | Bitwise NOT (inverts all the bits) | ~5 → -6 | |
<< | Bitwise left shift | 5 << 1 → 10 | |
>> | Bitwise right shift | 5 >> 1 → 2 |
Keywords in Python
Keywords are reserved words in Python that have predefined meanings and cannot be used as variable names. The following is a list of Python keywords arranged in four columns:
| Keyword | Description | Keyword | Description |
|---|---|---|---|
False | Represents the Boolean value false | None | Represents the absence of value |
True | Represents the Boolean value true | and | Logical AND operator |
as | Used to create an alias | assert | Used for debugging |
async | Defines an asynchronous function | await | Awaits the result of an async call |
break | Exits a loop prematurely | class | Used to define a class |
continue | Skips the current loop iteration | def | Defines a function |
del | Deletes an object | elif | Else if condition |
else | Defines the else block | except | Handles exceptions |
finally | Executes code after a try block | for | Starts a for loop |
from | Imports specific parts of a module | global | Declares a global variable |
if | Starts a conditional block | import | Imports a module |
in | Checks for membership | is | Checks for object identity |
lambda | Defines an anonymous function | nonlocal | Declares a non-local variable |
not | Logical NOT operator | or | Logical OR operator |
pass | Does nothing (placeholder) | raise | Raises an exception |
return | Exits a function and returns a value | try | Starts a try block |
while | Starts a while loop | with | Used for resource management |
yield | Pauses and resumes a generator | sum |
Variables in Python
Variables are used to store data in memory. In Python, variables are created when you assign a value to them.
Rules for Naming Variables
- Variable names must start with a letter or an underscore (_).
- They can only contain alphanumeric characters and underscores.
- They are case-sensitive.
- Reserved keywords cannot be used as variable names.
Example:
name = "John" # String
age = 25 # Integer
height = 5.9 # Float
is_student = True # Boolean
Constants in Python
Constants are fixed values that do not change during the execution of a program. Python does not have built-in constant support, but conventionally, constants are written in uppercase letters.
Example:
PI = 3.14159
GRAVITY = 9.8
Python Data Structures
Python provides several built-in data structures, each designed for specific tasks:
my_list = [1, 2, 3]#List mutable datatypemy_tuple = (1, 2, 3)#Tuple immutable datatypemy_set = {1, 2, 3}#Set datatype an unordered collection of unique itmmy_dict = {"name": "Alice", "age": 30}#Dictionary data (key:value)
my_string = "Hello, World!" #String data
Indexing
#Left to Right Indexing (0, 1, 2, 3 ... n)
a = [5,8,6,2,4]
print (a[0])# Output = 5
#______________________________________
#Right to left indexing (-1, -2, -3, ... -n)
a = [5,8,6,2,4]
print (a[-1]) #Output = 4
Finding Sum in List
a = [5,2,3]
b = sum(a)
print(b) # Expected output 10
Converting String to List
name = "apple&ball&cat&dog"
list1 = name.split("&") #Create lists using separator &
print(list1)
Finding Length
a = "Hello World"
print (len(a))
b = [5,6,7]
print (len(b))
Working on Dictionary Data Type
dict1 = {
"property": "house",
"department": "sugam",
"area": 123,
}
b = dict1["department"] # Assign value of key department
c= dict1.get("department") #Assign value of key department by get method
d = dict1.keys() # Assign all the keys of dictionary data dict1
e = dict1.values() # Assign all values in e
print(b)
print(c)
print(d)
print(e)
JSON (JavaScript Object Notation)
What is JSON?
- JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines.
- JSON is often used to exchange data between a server and a web application or between APIs.
- JSON data is structured using key-value pairs, similar to Python dictionaries.
JSON Syntax
- JSON objects are enclosed in curly braces
{}. - JSON arrays are enclosed in square brackets
[]. - Keys must be strings, and values can be strings, numbers, booleans, arrays, objects, or
null.
Example of JSON Data:
{
"name": "Alice", "age": 30, "isStudent": false,
"skills": ["Python", "JavaScript", "SQL"],
"address": {"city": "New York", "zip": "10001"}
}
JSON in Python
Python provides a built-in library called json to handle JSON data. It allows you to encode (serialize) and decode (deserialize) JSON data easily.
JSON is a vital tool for working with data in Python, especially in web development and APIs. Mastering how to handle JSON in Python ensures you’re ready to tackle real-world projects efficiently.
Key Functions in the json Module
| Function | Description |
|---|---|
json.dump() | Serializes Python object to JSON and writes it to a file. |
json.dumps() | Serializes Python object to a JSON string. |
json.load() | Deserializes JSON data from a file into a Python object. |
json.loads() | Deserializes a JSON string into a Python object. |
Serialization and Deserialization
- Serialization:
- Python object → JSON.
- Example: Sending data to an API client.
- Deserialization:
- JSON → Python object.
- Example: Receiving data from an API client.
Mutable Data Type Exercise
fruits = ['apple', 'banana', 'cherry']
num1 = [5,8,4,9,5]
# Modify the second item
fruits[1] = 'orange'
print(fruits) # Expected output: ['apple', 'orange', 'cherry']
print(num1) # Expected output: [5,8,4,9,5]
fruits.append('grape')
num1.append(7)
print(fruits) # Expected output: ['apple', 'orange', 'cherry', 'grape']
print(num1) # Expected output: [5,8,4,9,5,7]
#_____________________________________________________________
person = {'name': 'Alice', 'age': 25}
# Modify the value of the 'age' key
person['age'] = 26
print(person) # Expected output: {'name': 'Alice', 'age': 26}
person['city'] = 'New York'
print(person)
Combining Two List
name= ["ram","sita","hari"]
phone_no = [971663,456885,155665]
name_with_no_memo = zip(name,phone_no)
print(name_with_no_memo) #It gives memory address
name_with_no = list(name_with_no_memo)
print(name_with_no) # It display real list
Conditional Statements in Python
Conditional statements are used to execute code blocks based on certain conditions.
1. if Statement
The if statement is used to test a condition. If the condition is True, the block of code is executed.
Example:
x = 10
if x > 5:
print("x is greater than 5")
2. if-else Statement
The if-else statement allows you to execute one block of code if the condition is True and another if it is False.
Example:
x = 10
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
3. if-elif-else Statement
The if-elif-else statement is used to check multiple conditions.
Example:
x = 20
if x < 10:
print("x is less than 10")
elif x < 20:
print("x is between 10 and 19")
else:
print("x is 20 or greater")
4. Nested Conditional Statements
You can nest conditional statements inside one another.
Example:
x = 15
if x > 10:
if x < 20:
print("x is between 11 and 19")
Loops in Python
Python provides different types of loops to perform repetitive tasks efficiently.
1. for Loop
Used to iterate(going through each element one by one. Verbal Meaning; iteration: repetition) over a sequence (list, tuple, dictionary, etc.).
for item in iterable:
# Code to execute for each item
Example:
for i in range(5):
print(i) # Outputs numbers from 0 to 4
#________________________________
a= (9,8,6,7,5)
print(a) # Print non iterated item
for i in a:
print (i) #Print iterated item
2. while Loop
Repeats code as long as a condition is true.
while condition:
# Code to execute as long as condition is true
Example:
i = 0
while i < 5:
print(i)
i += 1 # Outputs numbers from 0 to 4
3. break and continue Statements
break: Exits the loop.continue: Skips the rest of the current iteration and moves to the next.
Example:
for i in range(10):
if i == 5:
break # Exits the loop
if i % 2 == 0:
continue # Skips even numbers
print(i)
Error Handling in Python
Python’s error handling mechanism allows you to handle exceptions and ensure smooth program execution. Here’s how it works:
try:
# Code that may raise an exception
except ExceptionType:
# Code to execute if an exception occurs
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}")
finally:
print("Execution completed.")
else: Runs if no exception occurs.finally: Runs no matter what, ensuring cleanup (e.g., closing files).
Functions in Python
Functions allow you to group code into reusable blocks. You can define a function using the def keyword.
Defining Functions
def function_name(parameters):
# Code block
return result # Optional
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Outputs: Hello, Alice!
Default Parameters
Functions can have default parameters, making them optional during function calls.
def greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # Outputs: Hello, Guest!
Lambda Functions
Short, anonymous functions defined with the lambda keyword.
add = lambda x, y: x + y
print(add(2, 3)) # Outputs: 5
Variable-Length Arguments
*args: Collects extra positional arguments as a tuple.**kwargs: Collects extra keyword arguments as a dictionary.
Example:
def print_info(*args, **kwargs):
print(args) # Tuple of positional arguments
print(kwargs) # Dictionary of keyword arguments
print_info(1, 2, 3, name="Alice", age=30)
# Outputs:
# (1, 2, 3)
# {'name': 'Alice', 'age': 30}d to iterate over a
Libraries in Python
AI Libraries
ChatGPT: pip install openai
Gemini: pip install google-generativeai
Claude: pip install anthropic
