0% found this document useful (0 votes)
6 views

Python_unit_1_BCA_DS

This document provides an introduction to Python programming, covering essential topics such as Python keywords, identifiers, variables, data types, operators, input and output, type conversion, debugging, and control flow. It highlights Python's features, applications, and the importance of understanding its syntax and structure for effective programming. The document serves as a foundational guide for beginners to start programming in Python.

Uploaded by

sadc bvm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python_unit_1_BCA_DS

This document provides an introduction to Python programming, covering essential topics such as Python keywords, identifiers, variables, data types, operators, input and output, type conversion, debugging, and control flow. It highlights Python's features, applications, and the importance of understanding its syntax and structure for effective programming. The document serves as a foundational guide for beginners to start programming in Python.

Uploaded by

sadc bvm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python Programming

Unit – I
Getting Started with Python

Syllabus:
Getting Started with Python:
 Introduction to Python
 Python Keywords
 Identifiers
 Variables
 Comments
 Data Types
 Operators
 Input and Output
 Type Conversion
 Debugging
 Flow of Control
 Selection
 Indentation
 Repetition
 Break and Continue Statement
 Nested Loops.

 Strings- String Operations


 Traversing a String
 String handling Functions.
I. Introduction to Python:

Python Overview

 High-Level Language: Python is a high-level, interpreted programming


language. It is closer to human languages and abstracts away most of the
complex details of the computer's hardware.
 Interpreted Language: Python code is executed line by line by the
interpreter, making debugging and testing easier.
 Dynamic Typing: Variables in Python do not need an explicit declaration
to reserve memory space. The declaration happens automatically when a
value is assigned to a variable.

History of Python

 Created by Guido van Rossum: Python was developed in the late 1980s
and released in 1991. It was designed to be easy to read and simple to
implement.
 Named After Monty Python: The name "Python" is derived from the
British comedy series "Monty Python's Flying Circus," not the snake.
 Key Features of Python
 Easy to Learn and Use: Python's syntax is clear and intuitive, making it
an excellent choice for beginners.
 Expressive Language: Python can perform complex tasks with a few lines
of code.
 Cross-Platform: Python can run on various operating systems like
Windows, mac-OS, and Linux without requiring changes to the code.
 Extensive Standard Library: Python comes with a large standard library
that includes modules and packages for various tasks, such as web
development, data analysis, and machine learning.
 Community Support: Python has a large and active community, so plenty
of resources, forums, and libraries are available for support and
collaboration.
Python Applications

 Web Development: Frameworks like Django and Flask are popular for
building web applications.
 Data Science: Libraries such as Pandas, NumPy, and Matplotlib are widely
used for data analysis, visualization, and scientific computing.
 Machine Learning: Libraries like TensorFlow and scikit-learn make
Python a preferred language for machine learning and artificial intelligence
projects.
 Automation: Python is often used for scripting and automating repetitive
tasks.
 Game Development: Libraries like Pygame are used for game
development.
 Desktop Applications: Toolkits like Tkinter and PyQt allow the creation
of desktop GUI applications.

II. Python Keywords:

 False: Represents the Boolean value for false.


 None: Represents a null value or "no value at all".
 True: Represents the Boolean value for true.
 and: A logical operator that returns True if both conditions are true.
 as: Used to create an alias while importing a module.
 break: Terminates the nearest enclosing loop.
 class: Defines a new user-defined class.
 continue: Skips the rest of the code inside the loop for the current iteration
and moves to the next iteration.
 def: Defines a function or method.
 elif: Checks another condition if the previous condition is false, similar to
else if.
 else: Defines a block of code to execute if the condition in an if statement
is false.
 except: Catches and handles exceptions.
 for: Creates a for loop to iterate over a sequence (e.g., list, tuple, string).
 if: Makes a conditional statement; executes a block of code if the condition
is true.
 import: Imports modules or specific elements from a module.
 in: Checks if a value is present in a sequence (e.g., list, tuple, string).
 not: A logical operator that inverts the Boolean value; returns True if the
condition is false.
 or: A logical operator that returns True if at least one condition is true.
 return: Exits a function and optionally returns a value.
 while: Creates a while loop that executes as long as the condition is true.
These are the most essential keywords for basic Python programming, forming
the core syntax and structure of the language.

III. Identifiers:

What are Python Identifiers?


Python Identifier is the name we give to identify a variable, function, class,
module, or other object. That means whenever we want to give an entity a name,
that’s called an identifier.

Rules for Writing Identifiers:


There are some rules for writing Identifiers. But first, you must know Python is
case-sensitive. That means Name and name are two different identifiers in
Python. Here are some rules for writing Identifiers in Python.
1. Identifiers can be a combination of uppercase and lowercase letters, digits, or an
underscore(_). So myVariable, variable_1, and variable_for_print all are valid
python identifiers.
2. An Identifier can not start with a digit. So while variable 1 is valid, 1 variable is
not valid.
3. We can’t use special symbols like !,#,@,%,$ etc in our Identifier.
4. Identifiers can be of any length

IV. Variables:

Python variables are containers that store values. Python is not


“statically typed”. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first
assign a value to it. A Python variable is a name given to a memory
location. It is the basic unit of storage in a program.

Here we have stored “Python Programming” in a variable var, and


when we call its name the stored information will get printed.
Code:
Var = “Python Programming”
Print(var)
Output = Python Programming.

V. Comments:

Definition:

 Comments: Comments in Python are annotations within the code that are
ignored by the interpreter during execution. They are used to document the
code and improve its readability.

Types of Comments

1. Single-Line Comments

Syntax: Single-line comments start with the # symbol.

Example:

Python:

# This is a single-line comment

2. Multi-Line Comments

Syntax: Multi-line comments are enclosed within triple quotes ("""


or ''').

Example:

Python:

"""
This is a multi-line comment.
It can span across multiple lines.
"""

Purpose of Comments

 Documentation: Explain the purpose of code blocks, functions, or


variables.
 Clarification: Provide context or reasoning for decisions made in the code.
 TODOs and FIXMEs: Mark areas of code that need attention or
improvement.
 Disable Code: Temporarily disable code blocks without deleting them.

VI. Data types:

What are Data Types?

In Python, data types define the kind of data a variable can hold and the operations
that can be performed on it. Imagine a box - the data type determines what kind
of items you can put in the box (numbers, text, etc.) and what you can do with
those items (add numbers, combine text, etc.).

Common Data Types in Python:

 Numbers:

int: Integers (whole numbers, positive, negative, or zero).

float: Floating-point numbers (numbers with decimal places).

 Text:

str: Strings (sequences of characters, like "Hello, world!").

 Logical:

bool: Boolean values (True or False).

 Collections:

list: Ordered sequences of items (like shopping lists).

tuple: Ordered, immutable sequences of items (like coordinates).

dict: Unordered collections of key-value pairs stored in a dictionary


(like phonebooks).
VII. Operators in Python:
1. Arithmetic Operators
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulus (remainder)
**: Exponentiation (power)

2. Comparison Operators
=: Equal to
!=: Not equal to
>: Greater than
<: Less than
>: Greater than or equal to
<=: Less than or equal to

3. Assignment Operators
= : Assigns a value to a variable
+=: Adds right operand to the left operand and assigns the result to
the left operand (`a += b` is equivalent to `a = a + b`)
-=, *=, /=, %=: Subtracts, multiplies, divides or takes modulus and
assigns the result to the left operand respectively

4. Logical Operators
and: Logical AND
or: Logical OR
not: Logical NOT

5. Membership Operators
in: Checks if a value exists in a sequence
not in: Checks if a value does not exist in a sequence

6. Identity Operators
is: Checks if two variables point to the same object
is not: Checks if two variables do not point to the same object
These operators are fundamental for performing calculations,
comparisons, logical operations, and more in Python programming.
Understanding their usage and precedence helps in writing efficient and
readable code.

VIII. Input and Output:


In Python, program output is displayed using the print() function, while user input
is obtained with the input() function. Python treats all input as strings by default,
requiring explicit conversion for other data types.
Taking Input from User in Python
The programs were not too interactive as we had hard-coded values of the
variables. Sometimes, users or developers want to run the programs with their
own data in the variables for their own ease.
To execute this, we will learn to take input from the users, in which the users
themselves will define the values of the variables.
The input() statement allows us to do such things in Python.
The syntax for this function is as follows:
input('prompt ')

Displaying Output in Python


We use the widely used print() statement to display some data on the screen.
We can output the particular data on some device (screen) or even in some files.
While writing real-world programs, we have to write statements that explicitly
output numbers and strings.
Let’s take an example to display a simple text.
print("Welcome to Scaler Academy. In this article, we will learn about
Python")
IX. Type conversion:
Definition:
Type Conversion: Type conversion in Python refers to converting one data type
to another. It can be done either implicitly by the interpreter or explicitly by the
programmer.

Types of Type Conversion:


1. Implicit Type Conversion (Automatic):
- Python automatically converts one data type to another whenever required
without user intervention.
Example: Python code
x = 10 # int
y = 2.5 # float
z = x + y # z becomes float (12.5)

2. Explicit Type Conversion (Manual):


- Explicit conversion is done using predefined functions to convert data types.
Common Explicit Conversion Functions:

1. int(): Converts a value to an integer.


Example: Python code
x = int(3.14) # x becomes 3

2. float(): Converts a value to a floating-point number.


Example: Python code
x = float(10) # x becomes 10.0

3. str(): Converts a value to a string.


Example: Python code
x = str(10) # x becomes "10"

4. list(): Converts a value to a list.


Example: Python code
x = list("abc") # x becomes ['a', 'b', 'c']
y = list((1, 2, 3)) # y becomes [1, 2, 3]

5. tuple(): Converts a value to a tuple.


Example: Python code:
x = tuple([1, 2, 3]) # x becomes (1, 2, 3)
y = tuple("abc") # y becomes ('a', 'b', 'c')

6. set(): Converts a value to a set.


Example: Python code
x = set([1, 2, 3, 3]) # x becomes {1, 2, 3}
y = set("abc") # y becomes {'a', 'b', 'c'}

7. dict(): Converts a sequence of key-value pairs to a dictionary.


Example: Python Code:
x = dict([('a', 1), ('b', 2)]) # x becomes {'a': 1, 'b': 2}
y = dict(a=1, b=2) # y becomes {'a': 1, 'b': 2}

Usage of Type Conversion:


Type conversion is used to ensure data compatibility in operations.
It helps to avoid type errors and allows for the correct processing of different data
types.
Understanding type conversion is essential for handling data effectively and
ensuring the correct operation of programs in Python.

X. Debugging:

What is Debugging?

Debugging is the process of identifying and fixing errors (bugs) in your Python
code. Imagine your program as a machine - debugging helps you find the
malfunction and fix it so the machine runs smoothly.

Common Debugging Techniques:

 Print Statements: Strategically placing print statements throughout your


code can help you inspect the values of variables at different points in the
program, making it easier to pinpoint where things go wrong.
 Error Messages: The Python interpreter provides error messages when it
encounters issues in your code. These messages often point to the line
number where the error occurs and can offer clues about the problem.
 Debuggers: Python offers built-in debuggers like pdb that allow you to
step through your code line by line, examining variables and the program's
state at each step. This can be particularly helpful for more complex errors.

Tips for Effective Debugging:

 Start simple
 Read error messages carefully
 Use print statements strategically
 Break down complex problems:
 Don't be afraid to experiment:
 Search online resources

XI. Flow of control:

Program execution happens sequentially in Python - the Python


interpreter reads a program just like you are reading this page: one line
at a time, from left to right and top to bottom. The interpreter executes
operations and functions in the order that it encounters them. This is
called control flow.
Flow of control in Python refers to the order in which individual statements,
instructions, or function calls are executed or evaluated. Understanding the flow
of control is essential for writing efficient and logical programs. Python supports
various control structures to manage the flow of control:

 Sequential Statements
 Conditional Statements
 Looping Statements

1. Sequential Statements:

These are the default mode of execution where statements are executed one after
another.

2. Conditional Statements:

These statements allow for decision-making in the code. The primary conditional
statements are if, if-else, and if-elif-else.

if Statement: Executes a block of code if the condition is true.

if-else Statement: Executes one block of code if the condition is true, and another
block of code if the condition is false.

if-elif-else Statement: Executes different blocks of code for multiple conditions.

3. Looping Statements:

Loops are used to repeat a block of code multiple times. Python supports for and
while loops.

for Loop: Iterates over a sequence (like a list, tuple, or string).

while Loop: Repeats a block of code as long as a condition is true.

4. Control Flow Statements:


These are used to alter the flow of control. The primary control flow statements
are break, continue, and pass.

break Statement: Terminates the loop.

continue Statement: Skips the current iteration and proceeds to the next
iteration.

pass Statement: Does nothing and can be used as a placeholder for future code.

XII. Selection in Python:

Selection in Python refers to the use of conditional statements to make decisions


in the code. This allows the program to execute certain parts of the code based on
specific conditions. Python supports several types of conditional statements for
selection:

1. if Statement
2. if-else Statement
3. if-elif-else Statement
4. Nested Conditional Statements

1. if Statement:

The if statement is used to test a condition. If the condition evaluates to true, the
block of code inside the if statement is executed.

2. if-else Statement:

The if-else statement is used to execute one block of code if the condition is true
and another block of code if the condition is false.

3. if-elif-else Statement:

The if-elif-else statement is used to check multiple conditions. If the first


condition is true, its corresponding block of code is executed. If the first condition
is false, the next elif (else if) condition is checked, and so on. If none of the
conditions are true, the block of code in the else part is executed.
4. Nested Conditional Statements:

Nested conditional statements are if statements inside other if or else statements.


This allows for more complex decision-making processes, where multiple
conditions need to be evaluated in sequence.

XIII. Indentation:
Indentation is a very important concept of Python because without properly
indenting the Python code, you will end up seeing IndentationError and the
code will not get compiled.
Python indentation refers to adding white space before a statement to a
particular block of code. In another word, all the statements with the same
space to the right, belong to the same code block.

IX. Repetition in Python:

Repetition in Python refers to the use of loops to execute a block of code multiple
times. Python provides two main types of loops for repetition: for loops and while
loops.

1. for Loop

The for loop iterates over a sequence (like a list, tuple, or string) and executes a
block of code for each item in the sequence.
2. while Loop

The while loop repeatedly executes a block of code as long as a specified


condition is true. It is used when the number of iterations is not known beforehand
and depends on a condition.

XX. Break and Continue Statements in Python

In Python, break and continue are control flow statements used within loops (for
and while) to modify their behaviour based on specific conditions.

1. Break Statement:

The break statement is used to exit the current loop prematurely, regardless of
whether the loop condition evaluates to True. It is typically used to terminate the
loop when a certain condition is met before completing all iterations.

2. Continue Statement:

The continue statement is used to skip the rest of the code inside the loop for the
current iteration and move on to the next iteration of the loop. It is useful when
you want to skip certain iterations based on a condition without terminating the
loop entirely.

XXI. Nested Loop:

A nested loop in Python refers to a loop structure where one loop is placed inside
another loop. This allows for multiple iterations of inner loops for each iteration
of outer loops.

Nested loops are commonly used when dealing with 2D data structures such as
matrices, grids, or nested lists. They enable you to systematically access and
process elements across multiple dimensions of data.

Key Points about Nested Loops:

1. Structure: Nested loops consist of an outer loop and one or more inner loops.
2. Iteration: The inner loop executes its entire cycle for each iteration of the outer
loop.

3. Usage: They are useful for tasks that require accessing elements in a matrix or
grid-like structure, or when working with nested data structures.

Example Applications:

- Matrix Operations: Iterating over rows and columns of a matrix.

- Grid-based Algorithms: Processing each cell or element in a grid.

- Nested Data Structures: Manipulating nested lists, dictionaries, or tuples


where elements have multiple levels of nesting.

Nested loops provide a flexible and powerful way to handle complex data
structures and perform repetitive tasks across multiple dimensions in Python
programming.

XXII. Strings:

In Python, a string is a sequence of characters enclosed within single quotes (`'`)


or double quotes (`"`). Strings are immutable, meaning their contents cannot be
changed after creation.

Key Characteristics:

 Encapsulation: Strings are defined using single quotes (`'`) or double


quotes (`"`).
 Immutable: Once a string is created, its contents cannot be modified.
 Indexing and Slicing: Strings can be accessed using indices and sliced to
extract substrings.
 Built-in Methods: Python provides numerous built-in methods for string
manipulation, such as `upper()`, `lower()`, `strip()`, `split()`, `join()`, etc.
 String Formatting: Python offers various methods for formatting strings,
including `%` formatting, `str.format()`, and f-strings (formatted string
literals).

Example Applications:

 Text Processing: Manipulating and analyzing textual data.


 User Input Handling: Capturing and processing user input.
 File Operations: Reading and writing data from/to files.

XXIII. String Operations or Handling Fctions:

1. len():

- Returns the length of the string (number of characters).

2. upper() and lower():

- Convert all characters in a string to uppercase or lowercase, respectively.

3. strip():

- Removes leading and trailing whitespace (spaces, tabs, newlines) from a


string.

4. startswith(prefix) and endswith(suffix):

- Checks if a string starts or ends with a specific substring (`prefix` or `suffix`).

5. find(substring) and index(substring):

- Searches for the first occurrence of a substring within the string and returns
its index. `find()` returns `-1` if the substring is not found, while `index()` raises
an exception.

6. replace(old, new):

- Replaces all occurrences of `old` substring with `new` substring in the string.

7. split(sep):
- Splits the string into a list of substrings based on the specified separator
(`sep`). If no separator is provided, it splits by whitespace.

8. join(iterable):

- Concatenates elements of an iterable (like a list) into a single string, with the
original string used as a separator.

9 .isdigit(), isalpha(), isalnum(), isspace():

- Checks if the string consists of digits, alphabetic characters, alphanumeric


characters, or whitespace characters, respectively.

10. capitalize():

- Converts the first character of the string to uppercase and all other characters
to lowercase.

11. str() and repr():

- Convert values to string representations. `str()` is intended to produce


readable outputs for users, while `repr()` is meant to generate representations that
are useful for debugging.

These functions and methods are foundational for performing various operations
on strings in Python, from simple manipulations to more complex text processing
tasks. Understanding and using these methods will enhance your ability to work
effectively with string data in Python programming.

XXIV. Traversing a string:

To traverse a string means to sequentially access each character or element within


the string. This can be achieved using various methods such as loops or built-in
functions that iterate through the string's characters.
Methods of Traversal
1. Using a For Loop:
- Iterating over the string with a `for` loop allows you to access each character
one by one:
Python Code:
message = "Hello, World!"
for char in message:
# Perform actions with each character `char`

2. Using Indexing:
- You can also traverse a string by accessing characters using their index
positions:
Python code:
message = "Hello, World!"
length = len(message)
for i in range(length):
char = message[i]
# Process each character `char` based on index `i`

Purpose of Traversal:

 Access and Manipulation: Traversing a string allows you to access,


manipulate, or analyze each character individually or collectively.
 Iteration Control: It provides the ability to perform specific operations or
checks on each character or a subset of characters within the string.
 String Analysis: Useful for tasks such as searching, counting occurrences,
or validating patterns within the string.

Example Applications
 Searching: Looking for specific substrings or patterns within the string.
 Counting: Counting occurrences of certain characters or substrings.

Traversing a string is a foundational operation when working with textual data in


Python, essential for tasks ranging from simple character analysis to complex
string manipulations.

You might also like