0% found this document useful (0 votes)
5 views12 pages

Lesson 1 - Python Strings, Lists, Tuples, Functions, Modules

This document serves as a study guide for Python fundamentals, covering essential concepts such as strings, lists, tuples, functions, and modules. It explains the properties, creation, and manipulation of these data types, as well as the importance of functions and modules in organizing and reusing code. Additionally, it includes a quiz and essay format questions to reinforce understanding of the material.

Uploaded by

Indu Sharma
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)
5 views12 pages

Lesson 1 - Python Strings, Lists, Tuples, Functions, Modules

This document serves as a study guide for Python fundamentals, covering essential concepts such as strings, lists, tuples, functions, and modules. It explains the properties, creation, and manipulation of these data types, as well as the importance of functions and modules in organizing and reusing code. Additionally, it includes a quiz and essay format questions to reinforce understanding of the material.

Uploaded by

Indu Sharma
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/ 12

SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY

(SCHOOL OF DIGITAL SCIENCES)


PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Python Fundamentals: Strings, Lists, Tuples, Functions, and Modules


This study guide covers fundamental concepts in Python programming: strings,
lists, tuples, functions, and modules. Understanding these building blocks is
crucial for writing e ective Python code.
Strings
 Definition: A sequence of characters.
 Creation: Can be created using single (') or double (") quotes. Multiline
strings use three quotes (''' or """).
 Properties: Python treats anything inside quotes as a string. It does not
have a separate character data type; a single character is a string of length
1. Strings are immutable (cannot be changed after creation).
 Assignment: Assigned to variables using the = operator.
 Indexing: Access individual characters using square brackets []. Positive
indexing starts from 0, and negative indexing starts from -1. An IndexError
is raised if the index is out of range.
 Looping: Iterate through characters using a for loop.
 Length: Use the len() function to get the number of characters.
 Checking Presence: Use the in keyword to check if a phrase or character
is present in a string.
 Slicing: Extract a range of characters using the slice syntax [start:end].
start is inclusive, end is exclusive. Omitting start slices from the beginning,
omitting end slices to the end. Negative indexes can also be used for
slicing.
 Concatenation: Combine strings using the + operator.
 Formatting: Use f-strings (introduced in Python 3.6) or the format()
method to combine strings with other data types (like numbers). F-strings
are prefixed with f and use curly brackets {} as placeholders.

1
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Lists
 Definition: Used to store multiple items in a single variable.
 Creation: Created using square brackets [].
 Properties: Ordered, changeable, and allow duplicate values.
 Indexing: Items are indexed starting from 0. Access items using square
brackets []. Supports negative indexing (-1 for the last item).
 Length: Use the len() function to get the number of items.
 Data Types: List items can be of any data type, including a mix of di erent
types.
 Accessing Items: Refer to the index number.
 Range of Indexes (Slicing): Specify a [start:end] range to return a new list
with specified items. start is inclusive, end is exclusive. Negative indexes
can be used for range specification.
 Checking Presence: Use the in keyword to determine if a specified item is
present.
 Changing Items:Change a specific item: Refer to the index number and
assign a new value.
 Change a range of items: Define a list with new values and refer to the
range of index numbers.
 Adding Items:append(): Adds an item to the end of the list.
 insert(index, item): Inserts an item at a specified index.
 Sorting:sort(): Sorts the list alphanumerically in ascending order by
default.
 sort(reverse=True): Sorts in descending order.
 Reversing: reverse(): Reverses the current sorting order of the elements.
 List Slicing Syntax: list_name[start : end : step]. start is inclusive, end is
exclusive, and step is the interval (defaults to 1). Omitting start or end
defaults to the beginning or end of the list respectively.

2
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

 List Methods: Python provides built-in methods like append(), clear(),


copy(), count(), extend(), index(), insert(), pop(), remove(), reverse(), and
sort().
Tuples
 Definition: Used to store multiple items in a single variable.
 Creation: Created using round brackets ().
 Properties: Ordered, unchangeable, and allow duplicate values.
 Unchangeable: Cannot change, add, or remove items after creation.
 Indexing: Items are indexed starting from 0. Supports duplicate values.
 Length: Use the len() function to get the number of items.
 Single Item Tuple: To create a tuple with one item, a comma must be
added after the item (e.g., ("apple",)).
 Data Types: Tuple items can be of any data type.
Functions
 Definition: A block of code that runs only when called.
 Purpose: Used to perform tasks repeatedly without code duplication.
Helps divide programs into manageable parts, improving readability,
testability, and maintenance.
 Built-in Functions: Functions like print() that are available everywhere.
 Defining a Function: Starts with the def keyword, followed by the function
name, parentheses (), and a colon :. The function body is indented.
 Docstring: A text string surrounded by triple quotes ("""Docstring""")
within the function body that describes what the function does.
 Calling a Function: Write the function's name followed by parentheses ().
 Arguments: Information passed into a function. Specified inside the
parentheses when calling the function.
 Parameters: Variables listed inside the parentheses in the function
definition.

3
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

 Number of Arguments: By default, a function must be called with the


correct number of arguments.
 Arbitrary Arguments (*args): Use * before the parameter name in the
function definition if the number of arguments is unknown. The function
receives a tuple of arguments.
 Keyword Arguments (key = value): Pass arguments using key = value
syntax. The order does not matter.
 Arbitrary Keyword Arguments (**kwargs): Use ** before the parameter
name if the number of keyword arguments is unknown. The function
receives a dictionary of arguments.
 Default Parameter Value: Assign a default value to a parameter in the
function definition. This value is used if the function is called without that
argument.
 Return Statement: return is used to end function execution and send a
value back to the caller. Statements after return are not executed. A return
without an expression returns None.
 Recursion: A function calling itself directly or indirectly to solve a problem
by breaking it into smaller parts. Requires a base case to stop the
recursion.
Modules
 Definition: A file containing Python definitions and statements (functions,
classes, variables). Grouping related code into modules improves
organization and reusability.
 Creation: Write code and save it in a file with a .py extension.
 Importing: Use the import statement to use definitions from one module
in another. The interpreter searches for the module in the search path.
 Importing Specific Attributes: Use the from module import attribute1,
attribute2 statement to import specific attributes without importing the
whole module.
 Built-in Modules: Python has several built-in modules ready to be
imported (e.g., math, random, datetime, time).
4
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Packages and Directory Management


 Packages: A way to organize related modules into directories. A package
is a directory with an __init__.py file and one or more modules. Useful for
larger projects and code distribution.
 Key Components: Module (single .py file), Package (directory with
__init__.py and modules), Sub-Packages (nested packages).
 Directory Management: Handling and interacting with directories using
Python.
 os Module: Provides functions for interacting with the operating system
(directories, files, processes, environment variables). Cross-platform.
 os.mkdir(path): Creates a single directory. Raises error if directory exists.
 os.makedirs(path): Creates a directory and necessary parent directories.
 os.getcwd(): Returns the absolute path of the current working directory as
a string.
 os.getcwdb(): Returns the absolute path of the current working directory
as a byte string.
 os.rename(src, dst): Renames a directory (or file). src must exist, dst
should not.
 os.renames(old, new): Renames a directory and any necessary parent
directories.
 os.chdir(path): Changes the current working directory. Raises OSError if
path doesn't exist.
 os.listdir(path): Returns a list of files and directories in the specified
directory. Not recursive.
 os.rmdir(path): Removes an empty directory. Raises error if not empty.
 shutil Module: Provides higher-level file operations.
 shutil.rmtree(path): Removes a directory and its contents recursively. Use
with caution.
 os.path Module: Provides functions for path manipulation.

5
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

 os.path.isdir(path): Returns True if the path is a directory, False otherwise.


 os.path.getsize(path): Returns the size of a file in bytes. Can be used with
os.walk() to calculate directory size.

6
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Quiz
Answer the following questions in 2-3 sentences each.
1. What is a Python string, and how can you create one?
2. Explain the di erence between positive and negative indexing in Python
strings.
3. How do you find the length of a string or a list in Python?
4. What is string slicing, and how is the end index treated in a slice?
5. Describe the purpose of string concatenation and the operator used for it.
6. What are Python lists, and what are their key properties?
7. How do you access specific items in a Python list?
8. Explain how to change the value of an item in a Python list.
9. What are Python tuples, and how do they di er from lists?
10.What is a Python function, and why are functions useful?
Answer Key
1. A Python string is a sequence of characters. You can create a string by
enclosing characters within either single quotes (') or double quotes (").
2. Positive indexing in Python strings starts from the beginning, with the first
character at index 0, the second at index 1, and so on. Negative indexing
starts from the end, with the last character at index -1, the second to last
at index -2, and so forth.
3. To find the length of a string or a list in Python, you use the built-in len()
function. You pass the string or list as an argument to this function, and it
returns the number of characters or items, respectively.
4. String slicing in Python allows you to extract a part of a string by specifying
a range of indexes. In a slice [start:end], the character at the start index is
included, but the character at the end index is not included in the resulting
slice.

7
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

5. String concatenation is the process of combining two or more strings into


a single string. The + operator is used in Python to perform string
concatenation.
6. Python lists are used to store multiple items in a single variable. Their key
properties are that they are ordered, meaning items have a defined and
unchanging position; they are changeable, allowing modification after
creation; and they allow duplicate values.
7. You access specific items in a Python list by referring to their index number
within square brackets [] after the list variable name. Positive indexes start
from 0 for the first item, and negative indexes start from -1 for the last item.
8. To change the value of an item in a Python list, you refer to the item's index
number and assign a new value using the assignment operator =. For
example, my_list[index] = new_value. You can also change a range of item
values by assigning a new list to a slice of the original list.
9. Python tuples are also used to store multiple items in a single variable,
similar to lists. The key di erence is that tuples are unchangeable,
meaning you cannot modify, add, or remove items after the tuple has been
created, while lists are changeable.
10.A Python function is a defined block of reusable code that performs a
specific task and only runs when it is called. Functions are useful because
they help organize code, prevent repetition by allowing you to call the
same code block multiple times, and make programs easier to read, test,
and maintain.

8
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Essay Format Questions


1. Compare and contrast Python lists and tuples, highlighting their
similarities, key di erences, and typical use cases.
2. Explain the concept of indexing and slicing in both Python strings and lists,
providing examples of how they are used to access and extract elements.
3. Discuss the benefits of using functions in Python programming and
describe the essential components of a Python function definition.
4. Describe how arguments are passed to Python functions, including
positional arguments, keyword arguments, arbitrary positional arguments
(*args), and arbitrary keyword arguments (**kwargs).
5. Explain the concept of Python modules and packages, and discuss how
they contribute to code organization and reusability.

9
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Glossary of Key Terms


 Argument: A value passed to a function when it is called.
 Arbitrary Arguments (*args): A parameter in a function definition that
allows the function to accept an unknown number of positional
arguments, which are received as a tuple.
 Arbitrary Keyword Arguments (**kwargs): A parameter in a function
definition that allows the function to accept an unknown number of
keyword arguments, which are received as a dictionary.
 Built-in Module: Modules that are pre-installed with Python and available
for import without needing external installation.
 Changeable: A data structure whose contents can be modified after it has
been created (e.g., lists).
 Concatenation: The process of joining two or more strings or sequences
end-to-end.
 Current Working Directory (CWD): The directory in a file system where a
program is currently operating.
 Default Parameter Value: A value assigned to a function parameter in the
definition, which is used if no argument is provided for that parameter
when the function is called.
 Docstring: A documentation string used to explain the purpose and usage
of a Python function, class, module, or script.
 f-string: A string literal prefixed with 'f' that allows for embedding
expressions inside string literals using curly braces {}.
 Indexing: Accessing individual elements within a sequence (like a string or
list) using their numerical position.
 in keyword: Used to check if an item exists within a sequence (string, list,
tuple, etc.).
 Insert: To add an item into a data structure at a specific position.
 List: An ordered, changeable collection of items that allows duplicate
members, created using square brackets [].

10
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

 Module: A file containing Python definitions and statements that can be


imported and used in other Python programs.
 Negative Indexing: Accessing elements from the end of a sequence,
where the last element has an index of -1.
 Ordered: A data structure where the items have a defined sequence that
does not change.
 Package: A directory containing Python modules and an __init__.py file,
used for organizing related modules into a hierarchical structure.
 Parameter: A variable listed inside the parentheses in a function definition
that serves as a placeholder for the arguments that will be passed when
the function is called.
 Positive Indexing: Accessing elements from the beginning of a sequence,
where the first element has an index of 0.
 Recursion: A programming technique where a function calls itself in its
definition to solve a problem by breaking it into smaller, self-similar
subproblems.
 return statement: Used in a function to exit the function and send a value
back to the caller.
 Reverse: To change the order of elements in a sequence to the opposite
sequence.
 Slicing: Extracting a contiguous subsequence from a sequence (string,
list, tuple) by specifying a range of indices.
 Sort: To arrange the elements in a sequence in a particular order (e.g.,
alphabetical or numerical).
 String: A sequence of characters, treated as an immutable data type in
Python.
 Tuple: An ordered, unchangeable collection of items that allows duplicate
members, created using round brackets ().
 Unchangeable: A data structure whose contents cannot be modified after
it has been created (e.g., tuples).

11
email : [email protected]
SRI JAGANNATH INSTITUTE OF MANAGEMENT & TECHNOLOGY
(SCHOOL OF DIGITAL SCIENCES)
PYTHON FUNDAMENTALS: STRINGS, LISTS, TUPLES, FUNCTIONS, AND MODULES

Notes

12
email : [email protected]

You might also like