0% found this document useful (0 votes)
22 views131 pages

Chapter - 1

This document serves as an introduction to Python programming, covering key concepts such as procedural programming, data types, variables, user input, conditional statements, loops, functions, and lists. It emphasizes Python's readability and versatility, along with practical examples like basic programs and string manipulation techniques. The document also discusses best practices for identifiers and keywords, as well as the differences between various collection data types like tuples, lists, and dictionaries.

Uploaded by

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

Chapter - 1

This document serves as an introduction to Python programming, covering key concepts such as procedural programming, data types, variables, user input, conditional statements, loops, functions, and lists. It emphasizes Python's readability and versatility, along with practical examples like basic programs and string manipulation techniques. The document also discusses best practices for identifiers and keywords, as well as the differences between various collection data types like tuples, lists, and dictionaries.

Uploaded by

anelesikhondze28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 131

CHAPTER - 1

INTRODUCTION
TO PYTHON
1.1 RAPID
INTRODUCTION TO
PROCEDURAL
PROGRAMMING
INTRODUCTION TO
PYTHON
 Python is a high-level programming language known for its simplicity and
readability.
 It is versatile and used in various fields like web development, data
analysis, artificial intelligence, and more.
 Python's indentation-based syntax is unique and emphasizes code
readability.
PROCEDURAL
PROGRAMMING
 Procedural programming is a programming paradigm that emphasizes
functions or procedures.
 It breaks down a program into reusable functions, making it easier to
manage and understand.
 Python supports both procedural and object-oriented programming.
FIRST PYTHON PROGRAM
 A Python program starts with a simple "Hello World" example.
 Use the ‘print()’ function to display text on the screen.
 Emphasize the importance of proper indentation.
VARIABLES AND DATA
TYPES
 Variables are used to store data temporarily.
 Python is dynamically typed, meaning you don't need to declare data types
explicitly.
 Common data types include integers (‘int’) , floating-point numbers (‘float’)
, strings (‘str’), and and Booleans (‘bool’)
USER INPUT
 Use the ‘input()’ function to get user input.
 You may need to convert input to the appropriate data type.
CONDITIONAL
STATEMENTS
(IF-ELIF-ELSE)
 Conditional statements allow you to make decisions in your code.
 The ‘if’, ‘elif’, and ‘else’ keywords are used for branching logic.
LOOPS (FOR AND WHILE)
 Loops help you execute a block of code repeatedly.
 The ‘for’ loop is used for iterating over a sequence (e.g., a range of
numbers).
 The ‘while’ loop continues as long as a condition is true.
FUNCTIONS
 Functions are reusable blocks of code.
 Define functions using the ‘def’ keyword.
 Encourage students to break down complex tasks into functions.
LISTS
 Lists are ordered collections of items.
 Elements can be of different data types.
 Show how to create and access elements in a list.
WORKING WITH LISTS
 To modify lists using methods like ‘append()’, ‘insert()’, ‘remove()’, and
‘pop()’.
 Emphasize list mutability.
RAPID
INTRODUCTION
TO
PROCEDURAL
PROGRAMMING
BASIC
PROGRAMS
VARIABLES AND DATA
TYPES:
USER INPUT:
WORKING WITH LISTS
SIMPLE CALCULATOR
TO FIND EVEN OR ODD
CALCULATE THE SQUARE OF
A NUMBER USING A
FUNCTION
CALCULATE THE AREA OF A
TRIANGLE
PYTHON PROGRAM TO
CONVERT KILOMETRES TO
MILES
PYTHON PROGRAM TO
CONVERT CELSIUS TO
FAHRENHEIT
PYTHON PROGRAM FOR SUM
OF SQUARES OF FIRST N
NATURAL NUMBERS
PROGRAM TO FIND THE MAXIMUM AND
MINIMUM VALUES FROM A SET OF
NUMBERS
PYTHON PROGRAM TO
CALCULATE THE FACTORIAL
OF A NUMBER.
PYTHON PROGRAM TO
CALCULATE THE SQUARE
ROOT OF A NUMBER.
DATA TYPES,
IDENTIFIERS, AND
KEYWORDS
DATA TYPES IN PYTHON
 Data types are fundamental building blocks in programming languages,
including Python.
 They define the kind of data that a variable can hold and determine what
operations can be performed on that data.
 Python has several built-in data types, which can be broadly categorized
into the following:
DATA TYPES IN PYTHON
1.Numeric Types:
•Integral Types: These are whole numbers and include int and bool.
•Floating-Point Types: These represent numbers with decimal points and include float.

2.Sequence Types:
•Strings (str): Used to store textual data, such as words, sentences, or characters.
•Lists (list): Ordered collections of items that can be of different data types.
•Tuples (tuple): Similar to lists but immutable, meaning their elements cannot be changed once defined.

3.Mapping Type:
•Dictionaries (dict): Key-value pairs used to store data in a structured manner.

4.Set Types:
•Sets (set): Unordered collections of unique elements.
•Frozen Sets (frozenset): Immutable sets.

5.Other Types:
•NoneType (None): Represents the absence of a value or a null value.
•Bytes (bytes): Immutable sequences of bytes.
•Bytearray (bytearray): Mutable sequences of bytes.
•Complex (complex): Used to represent complex numbers (real and imaginary parts).
IDENTIFIERS AND
KEYWORDS
In Python, identifiers are used to name variables, functions, classes, and other
objects. Identifiers follow these rules:

•They must start with a letter (a-z, A-Z) or an underscore (_).

•The rest of the identifier can contain letters, digits (0-9), or underscores.

•Identifiers are case-sensitive, so myVar and myvar are different.

Python keywords are reserved words with predefined meanings. You cannot use
them as identifiers.
Some common keywords include if, else, while, for, import, def, and more.
BEST PRACTICES FOR
IDENTIFIERS
1.Descriptive Names:
Choose meaningful and descriptive names for your variables and functions to make your code readable and self-
explanatory.

2.Use Underscores: For multi-word identifiers, use underscores (snake_case) rather than spaces or other special
characters.
For example, student_name instead of studentName or studentName123.

3.Avoid Single Letters: Avoid using single-letter variable names (e.g., x, y) except in simple cases like loop counters.

4.Be Consistent: Stick to a consistent naming convention throughout your codebase. This improves code maintainability.

5.Avoid Reserved Words: Never use Python keywords as identifiers.


If you're unsure whether a word is a keyword, you can check using the keyword module.
SUMMARY
Understanding data types, identifiers, and keywords is fundamental when
learning Python:
 Data Types: Determine the type of data a variable can hold and the
operations it supports.
 Identifiers: Are used to name variables, functions, classes, etc., and must
follow specific naming rules.
 Keywords: Are reserved words with predefined meanings in Python and
cannot be used as identifiers.
WORKING WITH
LISTS
Append(), Insert(), remove(), POP()
CREATE A LIST:
PROGRAM TO ACCESS
LIST ELEMENTS:
PROGRAM TO APPEND
TO A LIST:
PROGRAM TO REMOVE
AN ITEM FROM A LIST
PROGRAM TO CALCULATE
THE LENGTH OF A LIST
PROGRAM TO SORT A
LIST:
PROGRAM TO SLICE A
LIST
PROGRAM TO CHECK IF
AN ITEM EXISTS IN A
LIST
2.2 STRINGS
WHAT IS A STRING?
 A string is a sequence of
characters.

 It can contain letters,


numbers, symbols, and
spaces.

 Strings are enclosed in


single(‘ ’ ‘ ‘),double(‘ ” “ ’), or
triple (‘ ‘’’ ‘’’ ‘) or (‘ “ “ “ ‘’ ‘’
‘’ ‘) quotes.
STRING BASICS
String Length
 You can find the length of a
string using the ‘len()’
function
Accessing Characters

 Individual characters within a


string can be accessed using
indexing.

 Python uses zero-based


indexing, so the first character
is at index 0.
STRING CONCATENATION
Strings can be combined using
the ‘+’ operator.
STRING METHODS
Strings have built-in methods to
perform various operations.

Changing Case:

 ‘str.upper()’: Converts a string to


uppercase.

 ‘str.lower()’: Converts a string to


lowercase.
Removing Whitespace
 ‘str.strip()’: Removes leading and trailing
whitespace.

Replacing Text
 ‘str.replace(old,new)’: Replaces
occurrences of ‘old’ with ‘new’

Splitting Strings
 ‘str.split(separator)’: Splits a string into a
list using the specified ‘separator.
STRING FORMATTING
‘str.format()’: Used to
format strings with
placeholders ‘{}’
STRING SLICING
 Slicing allows you to extract
substrings from a string.

 Syntax: ‘string[start:end]’ (inclusive


of ‘start’, exclusive of ‘end’).

 You can also use a step value for


striding:
Syntax: ‘string[start:end:step]’
STRING COMPARISON
 Strings can be compared
using comparison operators
(‘==‘, ‘!=’, ‘<’, ‘>’, ‘<=’,
‘>=’).

 Comparison is case-
sensitive.
INDEXING AND NEGATIVE
INDEXING
You can access characters
from the end of a string using
negative indexing.
COMPARING
STRINGS IN
PYTHON
• compare strings to determine their order or equality.
• String comparisons are case-sensitive, meaning uppercase and lowercase letters are
considered different.
COMPARISON
OPERATORS
1. Equality(‘==’)
Checks if two strings are equal.

2. Inequality(‘!=‘)
Checks if two strings are not
equal.
3. Greater Than (‘>’) and Less
Than (‘<’)
Compares strings based on their
lexicographic (dictionary) order.

4. Greater Than or Equal To (‘>=’)


and Less Than or Equal To (‘<=’)
Checks if one string is greater or less
than or equal to another.
STRING COMPARISON
EXAMPLES
 When comparing strings, Python
checks each character's ASCII value
from left to right.

 The first character that differs


determines the result.
For strings with different
lengths, the shorter string is
considered less than the longer
one.
USING COMPARISON IN
CONDITIONAL
STATEMENTS
String comparisons are often
used in conditional statements
(if-else) to make decisions in
your code.
Remember to account for case
differences if needed, using
‘str.lower()’ or ‘str.upper()’
SLICING AND
STRIDING
STRINGS
Slicing and striding are techniques used to extract specific portions of a
string in Python.
Slicing Strings
 Slicing allows you to extract a portion (substring) of a string by specifying
a start and end index.
 The result includes all characters from the start index (inclusive) up to, but
not including, the end index (exclusive).
 If you omit the start index, it defaults to 0.
 If you omit the end index, it defaults to the length of the string.

 Negative indices can also be used for slicing. ‘-1’ refers to the last
character.
STRIDING STRINGS

 Striding (also called slicing with a


step) allows you to extract characters
from a string with a specified step size.
 Syntax: ‘string[start:end:step]’

 The ‘step’ value determines how many


characters to skip between each
extraction.
 A positive ‘step’ moves from left to right,
while a negative ‘step’ moves from right
to left.
STRIDING WITH
NEGATIVE INDICES
Combining negative indices
with striding allows for
reverse extraction.
SUMMARY
 Slicing and striding are commonly used for parsing text and extracting specific
information from strings.
 Useful for working with data like dates, URLs, or file paths.
 Slicing extracts a substring by specifying start and end indices.
 Striding extracts characters with a specified step size.
 Use negative indices for reverse extraction.
 These techniques are essential for manipulating and analyzing text data in
Python.
STRING
OPERATORS
AND
METHODS
In Python, strings are a fundamental data type, and
they come with various operators and methods for
performing operations and transformations.
COMMON STRING
OPERATORS
1.Concatenation (‘+’)
The (‘+’) operator is used to
concatenate (combine) two or more
strings.

2. Repetition (‘*’)
The (‘*’) operator allows you to
repeat a string multiple times.
COMMON STRING
METHODS
1. Changing Case
 ‘str.upper()’: Converts a string to
uppercase.

‘str.lower()’: Converts a string to
lowercase.

2. Removing Whitespace
 ‘str.strip()’: Removes leading and
trailing whitespace (spaces, tabs,
newlines).
3. Replacing Text
 ‘str.replace(old,new)’: Replaces
occurrences of ‘old’ with ‘new’.

4. Splitting Strings
 ‘str.split(separator)’: Splits a
string into a list using the
specified ‘separator.
5. Finding Substrings
 ‘str.find(substring)’: Searches for
‘substring’ and returns its index or ‘-
1’ if not found.

6. Checking Prefix and Suffix


 ‘str.startswith(prefix)’: Checks if the
string starts with the specified
‘prefix’.
 ‘str.startswith(suffix)’: Checks if the
string starts with the specified
SUMMARY
 Python provides several operators (‘+’, ‘*’) for working with
strings.
 String methods allow you to manipulate and transform strings
in various ways, such as changing case, removing whitespace,
replacing text, and splitting strings.
 Understanding these operators and methods is essential for
effective string manipulation in Python.
STRING
FORMATTING
WITH
‘STR.FORMAT
• String formatting is a technique for constructing

()’
strings by inserting values into predefined
placeholders within a string.
• Python provides the ‘str.format()’ method for this
purpose
USING ‘STR.FORMAT()’
 ‘str.format()’ is a method that
allows you to create formatted
strings with placeholders ‘{}’.

 In this example, ‘{}’ acts as a


placeholder for values that will be
inserted.
POSITIONAL ARGUMENTS
 ‘str.format()’ inserts values
based on their position

 The first ‘{}’ is replaced


with ‘name’ , and the
second ‘{}’ is replaced with
‘age’
NAMED ARGUMENTS
 You can also use named
placeholders to specify which
value to insert into each
placeholder.

 Using named placeholders makes


the code more readable and
maintainable.
ACCESSING VARIABLES
AND EXPRESSIONS
You can insert variables and
expressions within
placeholders
FORMATTING OPTIONS
 You can apply formatting
options to control how
values are displayed.

 In this example, ‘:.2f’


formats the ‘pi’ value as a
floating-point number with
two decimal places.
SUMMARY
 ‘str.format()’ is a versatile method for creating formatted
strings in Python.
 Placeholders ‘{}’ are used to specify where values
should be inserted.
 Positional and named arguments can be used for value
insertion.
 Formatting options can be applied to control the display
of values.
PYTHON
PROGRAMS
USING STRINGS
SIMPLE QUIZ GAME
STRING REVERSAL
PALINDROME CHECKER
CHARACTER COUNT
WORD COUNT
TEXT ALIGNMENT
STRING SEARCH AND
REPLACE
STRING VALIDATION WITH A
QUESTION
STRING COMPARISON
2.3
COLLECTIONS
DATA TYPES
TYPES OF COLLECTIONS
DATA TYPES
Tuples
Lists
Sets
Dictionaries
Iterating and copying collections
TUPLES
• A tuple is a collection data type in Python.
• Similar to lists, tuples can store multiple items.
• Unlike lists, tuples are immutable, meaning their
contents cannot be changed once defined.
CREATING TUPLES
 Tuples are defined using parentheses ‘()’
 You can create an empty tuple or initialize it with values.
ACCESSING ELEMENTS:
 Elements in a tuple are accessed by their index, just like in lists (0-based
indexing).
TUPLE PACKING AND
UNPACKING
 Tuple packing is when you group multiple values into a single tuple.
 Tuple unpacking is when you assign the values of a tuple to individual
variables.
IMMUTABILITY
 Once a tuple is created, you cannot modify its elements.
 You can, however, create a new tuple with modifications.
COMMON OPERATIONS
 You can use various operators on tuples, like concatenation (‘+’) and repetition
(‘*’)
ITERATING THROUGH
TUPLES
 You can iterate through a tuple using a ‘for’ loop
Use Cases for Tuples:
 Tuples are often used for situations where you want to store a fixed collection of items
that should not be changed.
 They can be used as keys in dictionaries due to their immutability.

When to Use Tuples vs. Lists:


 Use tuples when the data should not change (e.g., coordinates).
 Use lists when you need to modify the data (e.g., a list of tasks).

Tuple Methods:
 Tuples have a limited number of methods compared to lists because of their immutability.
LISTS
• A list is a collection data type in Python.
• Lists are used to store multiple items in a single variable.
• Lists are ordered, mutable, and can contain elements of
different data types.
CREATING LISTS
 Lists are defined using square brackets ‘[]’
 You can create an empty list or initialize it with values.
ACCESSING ELEMENTS
Elements in a list are accessed by their index, starting from 0
(0-based indexing).
MODIFYING LISTS
Lists are mutable, which means you can change their contents.
LIST SLICING
 You can extract a portion of a list using slicing.
 Slicing uses a colon ‘:’ to specify a range of indices.
COMMON LIST
OPERATIONS
Lists support operations like concatenation (‘+’) and repetition (‘*’)
ITERATING THROUGH
LISTS
You can iterate through a list using a ‘for’ loop.
LIST COMPREHENSIONS
List comprehensions provide a concise way to create lists based on
existing lists.
Use Cases for Lists:
 Lists are versatile and used for various purposes.
 They are suitable for collections of items where the order and modification of data
are important.

List Methods:
 Lists have many built-in methods for common operations like sorting, reversing,
and more.
SETS
• A set is a collection data type in Python.
• Sets are used to store multiple unique items in a single
variable.
• Sets are unordered and mutable, but their elements are
unique.
CREATING SETS
 Sets are defined using curly braces ‘{}’ or the ‘set()’ constructor.
 You can create an empty set or initialize it with values.
ADDING AND REMOVING
ELEMENTS
 You can add elements to a set using the ‘add()’ method.
 You can remove elements using the ‘remove()’ method.
SET OPERATIONS
Sets support various operations such as union (‘|’), intersection (‘&’), and
difference (‘-’)
ITERATING THROUGH
SETS
You can iterate through a set using a ‘for’ loop.
Use Cases for Sets:
 Sets are used when you need to store a collection of unique items.
 They are useful for removing duplicate values from a list or checking for
membership.

Frozensets:
 A frozenset is an immutable version of a set.
 Frozensets can be used as dictionary keys because they are hashable.
SET METHODS
Sets have various built-in methods for common operations like clearing,
copying, and checking for membership.
SET COMPREHENSIONS
Set comprehensions provide a concise way to create sets based on
existing iterables.
DICTIONARIE
S
• A dictionary is a collection data type in Python.
• Dictionaries are used to store data in the form of key-value
pairs.
• Dictionaries are unordered, mutable, and each key in a
dictionary is unique.
CREATING DICTIONARIES
Dictionaries are defined using curly braces ‘{}’ with key-value pairs
separated by colons ‘:’
ACCESSING ELEMENTS
Dictionary elements are accessed by their keys.
MODIFYING
DICTIONARIES
Dictionaries are mutable, meaning you can change their contents.
COMMON DICTIONARY
OPERATIONS
Dictionaries support operations like copying, getting keys and values,
and checking for key existence.
ITERATING THROUGH
DICTIONARIES
You can iterate through dictionaries using ‘for’ loops to access keys, values,
or key-value pairs.
DICTIONARY
COMPREHENSIONS
Dictionary comprehensions provide a concise way to create
dictionaries based on existing iterables.
Use Cases for Dictionaries:
 Dictionaries are used when you need to store and retrieve data efficiently using
meaningful keys.
 They are useful for tasks like mapping, configuration settings, and data
aggregation.

Nested Dictionaries:
 Dictionaries can contain other dictionaries as values, creating nested data
structures.
ITERATING
AND COPYING
COLLECTIONS
ITERATING THROUGH
COLLECTIONS
Using ‘for’ Loops
 Python provides a simple way to iterate through collections using ‘for’ loops.

Example - Iterating through a List:


ITERATING THROUGH
COLLECTIONS
Example - Iterating through a Set:

Example - Iterating through a Dictionary (Keys):


ITERATING THROUGH
COLLECTIONS
Example - Iterating through a Dictionary (Values)

Example - Iterating through a Dictionary (Key-Value Pairs):


ITERATING THROUGH
COLLECTIONS
Using List Comprehensions:
 List comprehensions are a concise way to create lists while iterating through
collections.

Example - List Comprehension:


COPYING COLLECTIONS
Shallow Copy:
 A shallow copy creates a new collection, but it still references the same objects inside
the collection (changes in nested objects affect both).

Example - Shallow Copy of a List:

Example - Shallow Copy of a Dictionary:


COPYING COLLECTIONS
Deep Copy:
 A deep copy creates a completely independent copy of a collection, including nested
objects (changes don't affect the original).

Example - Deep Copy of a List:

Example - Deep Copy of a Dictionary:

You might also like