0% found this document useful (0 votes)
25 views39 pages

class 15

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)
25 views39 pages

class 15

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
You are on page 1/ 39

Python: Introduction

 Python is an interpreted, high-level, general-purpose programming


language that
 Emphasizes readability, simplicity, and flexibility.
 It supports multiple programming paradigms, including procedural,
object-oriented, and functional programming.
 Python’s extensive standard library and its active community contribute to
its wide application in
 Fields like web development, AI, data science, machine learning,
automation, and more.
 In fact, Python occupies the number one position in the TIOBE index due
to its consistent growth and usage.
Python: Introduction
 Given its widespread adoption and versatility, understanding Python is
more important than ever.
 Python abstracts away much of the complexity involved in programming
 Enabling developers to focus on solving problems rather than
worrying about underlying technical details.
 Python is popularly used for development, scripting, and software
testing.
 Top IT companies like Google, Facebook, Instagram, Spotify and Netflix,
among others, use Python.
Python: Key Characteristics
Python's key characteristics making it a versatile language suitable for a
wide range of applications like web development, data science, and
scripting which include:
 Readability due to simple syntax,
 High-level abstraction,
 Dynamic typing,
 Interpreted execution,
 Extensive standard library,
 Cross-platform compatibility,
 Object-oriented programming capabilities,
 Beginner-friendly nature,
 Large community support, and
 Being open-source and free to use
Python: Key Characteristics
 Easy to Learn and Readable Syntax:
 To make it accessible to beginners, Python prioritizes
 Code readability with clear keywords,
 Indentation-based structure, and
 Minimal punctuation
 High-Level Language:
 Python abstracts away low-level details like memory management
 Allowing developers to focus on problem-solving with simple
commands.
 Dynamic Typing:
 Variable types are determined at runtime, eliminating the need for
explicit type declarations.
Python: Key Characteristics
 Interpreted Execution:
 Python code is executed line by line directly by the interpreter,
 Facilitates rapid development and debugging.
 Object-Oriented Programming:
 Python fully supports object-oriented paradigms, enabling developers
to create reusable classes and objects.
 Extensive Standard Library:
 Python comes with a large collection of built-in modules that provide
functionality for various tasks,
• Reducing the need for external libraries.
Python: Key Characteristics
 Cross-Platform Compatibility:
 Python code can run seamlessly across different operating systems
like Windows, macOS, and Linux.
 Large Community Support:
 Due to its popularity, Python benefits from a vast community of
developers, providing ample resources and assistance.
 Open-Source and Free:
 Python is freely available to use and distribute under an open-source
license.
Python: Strengths
 Easy to Learn and Use:
 Python’s simple syntax and readability make it
 Ideal for beginners and
 Help experienced programmers write code quickly.
 Cross-Platform:
 Python code is portable across different operating systems, such as
Windows, macOS, and Linux.
Python: Strengths
 Extensive Libraries and Frameworks:
 Python has libraries for almost any application, such as
 NumPy for scientific computing,
 Django for web development, and
 TensorFlow for machine learning.
 Versatility: It is used in various domains like web development, scientific
computing, artificial intelligence, data analysis, automation, etc.
 Strong Community Support: Python has a vast, supportive community,
which ensures extensive documentation, resources, and help for
developers.
Python: Weaknesses
 Performance: Python is slower than compiled languages like C++ and
Java because it is interpreted.

 Memory Consumption: Python’s flexibility in data types can lead to


higher memory usage,

 May not be suitable for memory-intensive applications.

 Weak in Mobile Computing: Python is less commonly used for mobile


applications compared to languages like Swift and Kotlin.

 Threading Limitations: Python’s Global Interpreter Lock (GIL) restricts


the execution of multiple threads, limiting multi-threading performance.
Python: IDLE (Integrated Development and Learning Environment)
 IDLE is Python’s default IDE (Integrated Development Environment).
 It provides a basic environment for writing, executing, and debugging
Python code, making it especially suitable for beginners.
 Key features:
 Python Shell: Allows testing code snippets interactively.
 Editor: Provides syntax highlighting, auto-completion, and indentation
support.
 Debugger: Offers a basic debugger with step-by-step execution and
breakpoints.
Python: Naming Conventions
 Specific naming conventions are followed to improve code readability

 For Variables and Functions: Use lowercase letters with words separated
by underscores (e.g., user_name, calculate_total).

 Constants: Use all uppercase letters with underscores (e.g., MAX_LIMIT).

 Classes: Use CamelCase (e.g., CustomerProfile).

 Private Variables: Start with a single underscore (e.g., _private_var).

 Avoid Reserved Keywords: Python has reserved keywords like if, else,
class, etc., which cannot be used as identifiers.
Python: Syntax
 Python syntax is designed to be clear and easy to read.
 Some key syntax rules are:
1. Statements: Each line of code is typically one statement.
2. Use a newline to indicate the end of a statement.
3. Use a semicolon (;) to combine multiple statements on one line (not
common).
 Example:
a = 10; b = 20; print(a + b) # Outputs: 30
Python: Comments
 Use # for single-line comments.
 Use triple quotes (""" or ''') for multi-line comments.
 Example:
# This is a single-line comment

"""
This is a multi-line
comment
"""
Python: Operators
 Operators in Python are special symbols or keywords used to perform
operations on variables and values.
 Types of operators in Python:
Python: Logical Operators

x=5
y = 10
print(x > 3 and y < 15) # True
print(x > 6 or y < 15) # True
print(not(x > 6)) # True
Python: Relational Operators

x=5
y = 10
print(x == y) # False
print(x != y) # True
print(x > y) # False
Python: Assignment Operators

x=5
x += 3 # x = 8
x *= 2 # x = 16
Python: Bitwise Operators

x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # 1 (Binary: 0001)
Python: Membership Operators

text = "Python"
print("P" in text) # True
print("z" not in text) # True
Python: Identity Operators

x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # False (different objects)
print(x == y) # True (same content)
Python: Special Operators
8. Special Operators:
 Ternary Operator: A shorthand for if-else.
result = "Positive" if x > 0 else "Non-Positive"
Python: Variables
 Variables are created by assignment.
 They do not require type declarations.
 Example:
x = 10 # Integer
y = "Hello" # String
Python: Dynamic Typing
 Python uses dynamic typing, meaning variables do not require a
specified type when they are declared.
 For instance, a variable can hold an integer initially,
 Then be reassigned to a string without type declarations.
 Example:
x = 10 # x is an integer
x = "Hello" # x is now a string
Python: Numeric & String Data Types
 Python supports several numeric data types:
 Integer (int): Whole numbers, positive or negative (e.g., 5, -10).
 Float (float): Numbers with a decimal point (e.g., 3.14, -2.5).
 Complex (complex): Numbers with a real and imaginary part (e.g., 3
+ 2j).
 String Values and Operations: Strings in Python are sequences of
characters enclosed in single, double, or triple quotes:
name = "Python"
sentence = 'Hello, World!'
paragraph = """This is a
multi-line string."""
Python: String
String Operations:
 Concatenation: Joining strings using +.
 Repetition: Repeating strings with *.
 Length: Finding the length of a string using len().
String Operators:
 Concatenation (+): Combines two strings into one.
 Repetition (*): Repeats a string a specified number of times.
 Membership (in): Checks if a substring is present in the string.
text = "Python"
print(text + " Programming") # Concatenation
print(text * 3) # Repetition
print("Py" in text) # Membership
Python: String Slices
 Slicing allows extraction of a portion of a string by specifying a range.
 Syntax:
string[start:end:step]
 Example:
text = "Python"
print(text[1:4]) # 'yth'
print(text[:3]) # 'Pyt'
print(text[::2]) # 'Pto'
Python: Different Data Structures
 Different data structures in Python to manage data effectively are:
Python: Mutable/Immutable Data Structures
 Difference:
Python: Ordered/Unordered Data Structures
 Differences:
Python: Non-Primitive Data Structures - Lists
 A list is an ordered, mutable collection of items.
 Lists are versatile and allow for mixed data types.
 Features:
 Allows duplicates.
 Can store mixed data types.
 Example:
# Declaration
fruits = ["apple", "banana", "cherry"]
# Removing an element
# Accessing elements fruits.remove("banana")
print(fruits[1]) # Output: banana
# Iterating through a list
# Adding an element for fruit in fruits:
fruits.append("orange") print(fruit)
Python: Non-Primitive Data Structures - Lists
 Example:
# Using square brackets #Removing elements
my_list = [1, 2, 3, 4] my_list.remove(3) #Removes the first
occurrence of 3
# Using the list() constructor my_list.pop() #Removes the last element
my_list = list((1, 2, 3, 4)) del my_list[1] #Deletes element at index 1
#Accessing elements #List slicing
print(my_list[0]) # Output: 1 sub_list = my_list[1:3] # Gets elements from
#Adding elements index 1 to 2
my_list.append(5) # Adds to the end #List comprehension
my_list.insert(2, 6) # Inserts 6 at index 2 squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Python: Non-Primitive Data Structures - Tuples
 A tuple is an ordered, immutable collection of items.
 Once a tuple is created, its elements cannot be modified.
 Tuples are often used to group related data.
 Features:
 Allows duplicates.
 Cannot be modified after creation.
 Example: # Declaration
coordinates = (10, 20, 30)
# Accessing elements
print(coordinates[0]) # Output: 10
# Unpacking
x, y, z = coordinates
print(x, y, z) # Output: 10 20 30
Python: Non-Primitive Data Structures - Tuples
 Example:
# Declaration # Accessing elements
# Using parentheses print(my_tuple[1]) # Output: 2
my_tuple = (1, 2, 3, 4)
# Unpacking tuples
# Using the tuple() constructor a, b, c = (1, 2, 3)
my_tuple = tuple([1, 2, 3, 4]) print(a, b, c) # Output: 1 2 3

# For a single-element tuple, include a trailing comma # Tuples in functions


single_element_tuple = (1,) def get_coordinates():
return (10, 20)

x, y = get_coordinates()
print(x, y) # Output: 10 20
Python: Non-Primitive Data Structures - Sets
 A set is an unordered collection of unique and immutable elements.
 It is commonly used for membership testing, removing duplicates, and
mathematical set operations like union, intersection, etc.
 Features:
 No duplicate elements.
 Used for mathematical set operations.
Python: Non-Primitive Data Structures - Sets
 Declaration  Removing elements
# Using curly braces my_set.remove(3) # Raises KeyError if the element is
not found
my_set = {1, 2, 3, 4}
my_set.discard(6) # Does not raise an error if the
# Using the set() constructor element is not found
# Duplicates are removed automatically
#Adding elements  Set operations
my_set = set([1, 2, 3, 3, 4]) set1 = {1, 2, 3}
my_set.add(5) set2 = {3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
print(set1.difference(set2)) # Output: {1, 2}
Python: Non-Primitive Data Structures - Dictionaries
 A dictionary is an unordered collection of key-value pairs.
 It is mutable, which means one can modify, add, or remove items.
 The keys in a dictionary are unique
 While the values can be duplicated.
 Features:
 Keys are unique and immutable.
 Values can be mutable and duplicated.
Python: Non-Primitive Data Structures - Dictionaries
 Example:
# Declaration
student = {"name": "Alice", "age": 25, "grade": "A"}

# Accessing values
print(student["name"]) # Output: Alice

# Removing a key-value pair


# Adding a new key-value pair
del student["age"]
student["subject"] = "Math"

# Iterating through keys and values


for key, value in student.items():
print(f"{key}: {value}")
Thank You

You might also like