0% found this document useful (0 votes)
2 views30 pages

Python Unit 1

The document provides an introduction to Python programming, detailing its features such as being a high-level, interpreted, and general-purpose language, as well as its support for object-oriented programming. It covers essential concepts including keywords, data types, operators, control flow, functions, classes, and exception handling. Additionally, it explains input/output operations and type conversion in Python.
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)
2 views30 pages

Python Unit 1

The document provides an introduction to Python programming, detailing its features such as being a high-level, interpreted, and general-purpose language, as well as its support for object-oriented programming. It covers essential concepts including keywords, data types, operators, control flow, functions, classes, and exception handling. Additionally, it explains input/output operations and type conversion in Python.
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/ 30

UNIT-1

PYTHON PROGRAMMING
Introduction to Python
What is Python?
-Python is a high-level, interpreted, general-
purpose programming language.
-It was created by Guido van Rossum and first
released in 1991.
Features of Python
Interpreted Language: Python runs code line by line. This
makes fixing errors faster and development quicker, as you
don't need a separate build step.
High-Level Language: It handles complex computer details
for you, letting you focus on solving your problem.
General-Purpose Language: You can use it for many
different things: building websites, analyzing data, making AI,
automating tasks, and creating games.
Dynamically Typed: You don't have to tell Python what type
of data a variable holds (like if it's a number or text); Python
figures it out as it runs.
Object-Oriented Programming (OOP) Support: It
supports OOP concepts like classes, objects, inheritance,
and polymorphism for reusable.
Open Source : Python is freely available and modifiable.
Extensive Standard Library: Comes with many ready-
made tools and functions for common tasks, so you don't
have to write everything from scratch.
Platform Independent (Portable): Your Python code can
run on different operating systems like Windows, Mac, or
Linux without needing major changes.
Python Keywords
What are Keywords?
•Keywords also known as reserved words .
•They have a predefined meaning and purpose, which
the Python interpreter understands.
•Keywords cannot be used as variable names, function
names, class names, or any other identifier. And that
lead to a SyntaxError.
•Python keywords are case-sensitive.
To get list of all keywords in your current Python version (e.g., Python 3.11 has 36
keywords).
Values & Operators:

•True: Represents the boolean true value.


•False: Represents the boolean false value.
•None: Represents the absence of a value or a
null value.
•and: Logical AND operator.
•or: Logical OR operator.
•not: Logical NOT operator.
•is: Identity operator
•in: Membership operator
Control Flow:

•if: Used for conditional execution (starts an if statement).


•elif: Short for "else if" (used for additional conditions in an if
statement).
•else: Used to execute a block of code if no if or elif conditions
are met.
•for: Used to iterate over sequences (like lists, tuples, strings,
ranges).
•while: Used to loop as long as a condition is true.
•break: Terminates the current loop prematurely.
•continue: Skips the rest of the current iteration and moves to
the next one in a loop.
•pass: A null operation; nothing happens when it executes.
Function & Class Definition:
•def: Used to define a function.
•class: Used to define a class.
•return: Used to exit a function and return a value (or None).
•lambda: Used to create small, anonymous functions.

Exception Handling:

•try: Starts a block of code that might raise an exception.


•except: Catches and handles specific exceptions raised in the try block.
•finally: Executes a block of code regardless of whether an exception
occurred.
•raise: Used to explicitly raise an exception.
•assert: Used for debugging checks if condition is true and raises an
AssertionError if false.
Module & Package Management:

•import: Used to import modules or packages.


•from: Used in conjunction with import to import specific attributes or functions from
a module.
•as: Used to create an alias (a different name) for an imported module or other
object.

Advanced / Other:

•with: Used for context management (e.g., handling files, database connections).
Ensures resources are properly acquired and released.
•as (with with): Used in conjunction with with to assign the result of the context
manager.
•del: Used to delete objects or names.
•global: Declares a variable inside a function to be a global variable.
•nonlocal: Declares a variable inside a nested function to refer to a variable in the
nearest enclosing (non-global) scope.
•async: Used to define an asynchronous function (coroutine). (Python 3.5+)
•await: Used to pause the execution of an async function until an awaitable
Identifiers
An identifier is a name given to entities like variables,
functions, classes, modules, or any other object. It's
essentially how you label and refer to different
components in your code.

Ex: name = “ram"


age = 30
score_2024 = 95
Identifier Rules

Valid Rules:
•Can contain a-z, A-Z, 0-9, _.
•Must not start with a digit.
•Case-Sensitive.

Invalid Rules:
•Cannot begin with a number.
•Cannot use @, #, $, %, etc., except for the underscore (_).
•Cannot be a Python keyword (reserved word like if, else, for).
Variables
A variable is a named storage location for data.
The information can be numbers, text, lists, or
more complex data types.
The value can change (or "vary") during the
execution of a program.
Example:
Comments
Comments are lines of text within your code that the Python
interpreter completely ignores during program execution.
Why are Comments Helpful?

-Explain Code Logic


-Enhance Readability
-Document Purpose
-Debugging (Temporary Disabling)
-Provide Context/Metadata
Data Types
Data types in Python:

Numeric - int, float, complex


Sequence Type - string, list, tuple
Mapping Type - dict
Boolean - bool
Set Type - set
Example
Operators
Operators are special symbols or keywords
that perform operations on one or more
values (called operands).
Arithmetic Operators:

•Used to perform mathematical calculations.


•+ (Addition): x + y
•- (Subtraction): x - y
•* (Multiplication): x * y
•/ (Division): x / y (always returns a float)
•% (Modulo): x % y (returns the remainder of the
division)
•** (Exponentiation): x ** y (x raised to the power of
y)
•// (Floor Division): x // y (returns the integer part of
the quotient)
•Used to assign values to variables.
•= (Assign): x = 5
•+= (Add AND assign): x += 5 (same as x = x +
5)
•-= (Subtract AND assign): x -= 5 (same as x =
x - 5)
•*= (Multiply AND assign): x *= 5 (same as x =
x * 5)
•/= (Divide AND assign): x /= 5 (same as x = x /
5)
•%= (Modulo AND assign): x %= 5 (same as x =
x % 5)
•**= (Exponent AND assign): x **= 5 (same as x
= x ** 5)
•//= (Floor Divide AND assign): x //= 5 (same as
Comparison (Relational) Operators:

•Used to compare two values and return a Boolean result (True or


False).
•== (Equal to): x == y
•!= (Not equal to): x != y
•> (Greater than): x > y
•< (Less than): x < y
•>= (Greater than or equal to): x >= y
•<= (Less than or equal to): x <= y
Logical Operators:

•Used to combine conditional statements.


•and (Logical AND): Returns True if both statements are true.
•or (Logical OR): Returns True if at least one statement is true.
•not (Logical NOT): Reverses the result; returns False if the result is
true.

Identity Operators:

•Used to compare the memory locations of two objects.


•is: Returns True if both variables point to the same object in memory.
•is not: Returns True if both variables point to different objects in memory.
Membership Operators:
•Used to test if a sequence (like a string, list, tuple) contains a specific value.
•in: Returns True if the value is found in the sequence.
•not in: Returns True if the value is not found in the sequence.

Bitwise Operators:
•Used to perform operations on individual bits of integers
•& (Bitwise AND)
•| (Bitwise OR)
•^ (Bitwise XOR)
•~ (Bitwise NOT)
•<< (Left shift)
•>> (Right shift)
Input and Output in Python

Input and Output (I/O) operations allow your program to interact with the
outside world.
•Input refers to the process of receiving data from an external source into your
program. This data can come from a user typing on a keyboard, reading from
a file, receiving data over a network, etc.
•Output refers to the process of sending data from your program to an
external destination. This data can be displayed on the screen, written to a file,
sent over a network, etc.

The most common built-in functions for basic input and output are input()
and print().
Input (input() function):

The input() function is used to get data (typically text) from the user via
the keyboard.
-Main Purpose is to pause program execution and wait for the user to
type something and press Enter.
-The input() function always returns the user's input as a string (str).

Output (print() function):

The print() function is used to display output on the console (screen).


-Main Purpose is to show information, results, or messages to the user.
-It can take one or more arguments (variables, literals, expressions)
separated by commas.
Type Conversion:
Type conversion (also known as type
casting) in Python is the process of
converting one data type into another data
type.
Implicit Type Conversion (Automatic Type Promotion):

-Python automatically converts one data type to another


without any explicit instruction from the programmer.
Example: When an integer is involved in an operation with a
float, the integer is implicitly converted to a float.

Explicit Type Conversion (Type Casting):

-The programmer manually converts the data from one type to


another using built-in functions.
-This is done when you specifically need a value to be of a
certain type, even if Python wouldn't convert it automatically.

You might also like