Introduction to Python Programming Language

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 TypeDescriptionExampleMemory Usage
intInteger values10, -5Depends on value (unbounded)
floatFloating-point numbers3.14, -0.0124 bytes (approx.)
complexComplex numbers3+4j, -5+2j32 bytes (approx.)
strStrings'Hello', "Python"49 bytes + length of string
listOrdered, mutable collections[1, 2, 3]64 bytes + elements’ size
tupleOrdered, immutable collections(1, 2, 3)48 bytes + elements’ size
setUnordered unique collections{1, 2, 3}224 bytes + elements’ size
frozensetImmutable setsfrozenset([1, 2])Similar to set
dictKey-value pairs{"key": "value"}240 bytes + keys/values’ size
boolBoolean valuesTrue, False28 bytes
bytesImmutable byte sequencesb"data"33 bytes + data length
bytearrayMutable byte sequencesbytearray(4)Similar to bytes
memoryviewMemory view of bytesmemoryview(b"abc")Depends on the source object
NoneRepresents no valueNone16 bytes

Operators in Python

CategoryOperatorDescriptionExample
Arithmetic+Addition3 + 25
-Subtraction3 - 21
*Multiplication3 * 26
/Division (float result)3 / 21.5
//Floor division (integer result)3 // 21
%Modulus (remainder of division)3 % 21
**Exponentiation (power)3 ** 29
Comparison==Equal to3 == 3True
!=Not equal to3 != 2True
>Greater than3 > 2True
<Less than3 < 2False
>=Greater than or equal to3 >= 2True
<=Less than or equal to3 <= 2False
LogicalandLogical AND (both must be True)True and FalseFalse
orLogical OR (at least one must be True)True or FalseTrue
notLogical NOT (negates the value)not TrueFalse
IdentityisChecks if two variables point to the same object in memorya is bTrue or False
is notChecks if two variables do not point to the same objecta is not bTrue or False
MembershipinChecks if a value exists in a sequence (list, string, etc.)'a' in 'apple'True
not inChecks 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 += 5x = x + 5
-=Subtract and assign (decrement by a value)x -= 5x = x - 5
*=Multiply and assign (multiply by a value)x *= 5x = x * 5
/=Divide and assign (divide by a value)x /= 5x = x / 5
//=Floor divide and assign (integer division)x //= 5x = x // 5
%=Modulus and assign (assign remainder)x %= 5x = x % 5
**=Exponentiate and assign (raise to a power)x **= 5x = x ** 5
&=Bitwise AND and assignx &= 3x = x & 3
`=`Bitwise OR and assign
^=Bitwise XOR and assignx ^= 3x = x ^ 3
<<=Left shift and assignx <<= 3x = x << 3
>>=Right shift and assignx >>= 3x = x >> 3
Bitwise&Bitwise AND (bit by bit AND)5 & 31
``Bitwise OR (bit by bit OR)
^Bitwise XOR (bit by bit XOR)5 ^ 36
~Bitwise NOT (inverts all the bits)~5-6
<<Bitwise left shift5 << 110
>>Bitwise right shift5 >> 12

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:

KeywordDescriptionKeywordDescription
FalseRepresents the Boolean value falseNoneRepresents the absence of value
TrueRepresents the Boolean value trueandLogical AND operator
asUsed to create an aliasassertUsed for debugging
asyncDefines an asynchronous functionawaitAwaits the result of an async call
breakExits a loop prematurelyclassUsed to define a class
continueSkips the current loop iterationdefDefines a function
delDeletes an objectelifElse if condition
elseDefines the else blockexceptHandles exceptions
finallyExecutes code after a try blockforStarts a for loop
fromImports specific parts of a moduleglobalDeclares a global variable
ifStarts a conditional blockimportImports a module
inChecks for membershipisChecks for object identity
lambdaDefines an anonymous functionnonlocalDeclares a non-local variable
notLogical NOT operatororLogical OR operator
passDoes nothing (placeholder)raiseRaises an exception
returnExits a function and returns a valuetryStarts a try block
whileStarts a while loopwithUsed for resource management
yieldPauses and resumes a generatorsum

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

  1. Variable names must start with a letter or an underscore (_).
  2. They can only contain alphanumeric characters and underscores.
  3. They are case-sensitive.
  4. 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 datatype

my_tuple = (1, 2, 3) #Tuple immutable datatype

my_set = {1, 2, 3} #Set datatype an unordered collection of unique itm

my_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

FunctionDescription
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

  1. Serialization:
    • Python object → JSON.
    • Example: Sending data to an API client.
  2. 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top