0% found this document useful (0 votes)
11 views10 pages

Python Notes Unit 1

The document outlines the core structural elements of a Python program, including comments, import statements, variable declarations, function and class definitions, and main program logic. It emphasizes the importance of readability, indentation, and modularity in Python coding. Additionally, it covers Python's built-in data types, keywords, variable declaration rules, operators, and input/output functions.

Uploaded by

kk7852382
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)
11 views10 pages

Python Notes Unit 1

The document outlines the core structural elements of a Python program, including comments, import statements, variable declarations, function and class definitions, and main program logic. It emphasizes the importance of readability, indentation, and modularity in Python coding. Additionally, it covers Python's built-in data types, keywords, variable declaration rules, operators, and input/output functions.

Uploaded by

kk7852382
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

Python – Unit -1

Python Program Core Structural Elements


A simple Python program's structure is defined by its sequential nature and reliance on indentation to
delimit code blocks, rather than braces or semicolons. It typically follows an order from imports to main
logic.

Core Structural Elements

• Comments: Used to explain code and are ignored by the Python interpreter. Single-line comments start
with # while multi-line comments or docstrings often use triple quotes ("""...""" or '''...''').

• Import Statements: These are placed at the top to include modules or libraries, giving the program
access to external tools and functions.

• Variable Declarations (Assignments): Variables are created dynamically when a value is assigned to
them, without requiring explicit type declaration.

• Function and Class Definitions: Reusable blocks of code (functions) and blueprints for objects
(classes) are defined using the def and class keywords , respectively. These definitions form modular
components of the program.

• Main Program Logic: This is the section where the core instructions to solve the problem are written,
including control flow structures like loops (for, while) and conditionals (if, elif, else).

• Entry Point Guard: In larger scripts, the standard practice is to use an

if __name__ == "__main__":

block to define code that runs only when the file is executed directly, not when imported as a module.

Example Structure
"""
This is a simple Python [Link] calculates and prints the area of a circle.
"""
# Import the math module for the pi constant
import math
# Define a function to calculate the area
def area_of_circle(radius):
"""Calculates the area of a circle given its radius."""

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

area = [Link] * (radius ** 2)


return area

# Main program logic (entry point)


if __name__ == "__main__":
radius = 5 # Assign a value to the radius variable
my_area = area_of_circle(radius) # Call the function

# Print the result to the console


print(f"The area of a circle with radius {radius} is {my_area}")
Key Pythonic Principles

• Readability Counts: Python prioritizes code that is easy to read and understand.

• Indentation is Syntax: Consistent indentation (commonly four spaces) defines code blocks and is
essential for the program to run correctly.

• Modularity: Breaking code into functions, modules, and packages makes projects more manageable,
maintainable, and reusable.

Understanding python code blocks


In Python, a block is a group of consecutive statements with the same indentation level that are executed
together as a single unit. Unlike many other programming languages that use curly braces {} or keywords
like "begin" and "end", Python uses consistent whitespace indentation to define code blocks.

Key Characteristics

• Indentation is Mandatory: Indentation is a fundamental part of Python's syntax, not just for readability.
Incorrect or inconsistent indentation will cause an IndentationError.

• Defining Scope and Structure: Code blocks are used to define the structure and scope of control flow
statements, functions, classes, and modules.

• Visual Clarity: This design choice enhances code readability and consistency across projects, as the
visual structure directly reflects the logical structure.

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

• Standard Practice: The official Python style guide, PEP 8, recommends using four spaces per
indentation level. Mixing spaces and tabs is strongly discouraged.

Where Blocks Are Used

Code blocks are used in a variety of contexts to group related statements:

• Functions: The body of a function defined with the def keyword is an indented block.

def greet(name):

print(f"Hello, {name}!") # This line is a block

print("Welcome") # This line is part of the same block

Conditional Statements: The code that runs under if, elif, and else conditions must be in an indented
block.

x = 10

if x > 5:

print("x is greater than 5") # This is a block

else:

print("x is not greater than 5") # This is another block

Loops: The body of for and while loops is an indented block that executes repeatedly.

for i in range(3):
print(f"Loop iteration {i}") # This is the loop block
• Classes: Methods and attributes within a class definition are contained in an indented block.

• Exception Handling: The try, except, and finally clauses use indented blocks to manage error
handling.

Nested Blocks

Blocks can be nested within other blocks (e.g., a loop inside an if statement) by increasing the
indentation level further. The inner block only runs if the outer block's condition is met or its context is
active.

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

Python data types


Python has several built-in data types to classify the kind of values a variable can hold. Since
everything in Python is an object, these data types are actually classes, and variables are instances of
these classes.

The main built-in data types can be grouped into several categories:

Numeric Types

These types are used to store numeric values.

• int (Integer): Represents whole numbers (positive or negative) without a decimal point, with no limit on
length.

• float (Floating Point): Represents real numbers with a decimal point and is accurate up to 15 decimal
places.

• complex (Complex Number): Represents numbers with a real and an imaginary part, expressed as

a + bj where j denotes the imaginary unit.

Sequence Types

These are ordered collections of items that can be accessed by indexing.

• str (String): A sequence of Unicode characters used for textual data, enclosed in single, double, or
triple quotes. Strings are immutable.

• list (List): A mutable (changeable), ordered collection of items. Lists can contain elements of different
data types and are defined using square brackets[ ] .

• tuple (Tuple): An immutable (unchangeable), ordered collection of items. Tuples are defined using
parentheses ( ) and are useful for fixed collections of data.

• range (Range): An immutable sequence of numbers, often used for looping a specific number of times.

Mapping Type

• dict (Dictionary): An unordered collection of data stored in key-value pairs. Dictionaries are mutable and
keys must be unique and immutable. They are defined using curly braces {} with colons separating keys and
values (e.g., {"name": "Alice", "age": 25})

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

Set Types

These are unordered collections of unique elements.

• set (Set): A mutable collection of unique, hashable items. Duplicates are automatically removed. Sets
are created using curly braces { } or set( ) function.

• frozenset (Frozen Set): An immutable version of a set. Once created, elements cannot be added or
removed.

Boolean Type

• bool (Boolean): Represents truth values, with only two possible constant values:True and False .

• True is considered 1 and False is 0 when used in arithmetic operations.

Binary Types
These types handle raw binary data.

• bytes: An immutable sequence of bytes.

• bytearray: A mutable version of bytes.

• memoryview: Provides a way to access the internal data of an object without copying it, useful for
performance-critical applications

None Type

• None : Represents the absence of a value or a null value. It has a single value None .

Python keywords
Python keywords are predefined, reserved words that have special meanings and purposes in the
language, and therefore cannot be used as variable, function, or class names. As of Python 3.11, there are
35 standard keywords and a few "soft" keywords like match, case, and _, which only act as keywords in
specific contexts.

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

List of Python Keywords

Category Keywords

Value True, False, None

Operator and, or, not, is, in

Control Flow if, elif, else, for, while, break, continue, pass

Function/Class def, class, lambda, return, yield

Exception Handling try, except, raise, finally, assert

Variable Scope del, global, nonlocal

Module Management import, from, as

Asynchronous async, await

Context Management with

Pattern Matching match, case, _ (soft keywords)

Declaring and Using Variables


Python variables are symbolic names that act as references (or pointers) to data objects stored in
memory. Unlike some other programming languages, Python variables are created automatically the
moment you first assign a value to them using the assignment operator (=), without requiring an explicit
declaration or type keyword.

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

Naming Rules and Conventions

Variable names must adhere to the following rules to avoid syntax errors:

• Must begin with a letter (a-z, A-Z) or an underscore (_).

• Cannot start with a number (0-9).

• Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).

• Are case-sensitive (age, Age, and AGE are different variables).

• Cannot be Python reserved keywords (e.g., if, for, while).

[Link]
• The basic syntax for creating (or "declaring" in a non-explicit sense) a variable is:
Syntax : variable_name = value

Examples:

age = 30 # Assigning an integer

user_name = "John" # Assigning a string

is_active = True # Assigning a boolean

height = 1.75 # Assigning a float

[Link] Variables
Once assigned, you can use the variable name to access and manipulate the stored value throughout your
code.

Examples:

# Printing a variable's value

print(age)

# Output: 30

# Using variables in expressions

future_age = age + 5

print(f"In five years, {user_name} will be {future_age} years old.") # Using an f-string for clear output

# Output: In five years, John will be 35 years old.

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

3. Multiple Assignments
Python allows assigning values to multiple variables in a single line:

• Multiple variables, multiple value

x, y, z = 1, 2, 3

• Multiple variables, one value


x = y = z = 100

Python operators
Python operators are special symbols or keywords that perform operations on variables and values. They are
categorized into several functional groups:

• Arithmetic Operators: Perform mathematical tasks such as addition (+), subtraction (-), multiplication
(*), division (/), modulus (%), exponentiation (**), and floor division (//).

• Assignment Operators: Used to assign values, including compound operations like =,+=, -=, and *=.

• Comparison Operators: Compare values and return Boolean results (==, !=, >, <, >=, <=).

• Logical Operators: Combine conditions using and, or, and not.

• Identity Operators: is and is not check if variables point to the same object.

• Membership Operators: in and not in check for value presence in sequences.

• Bitwise Operators: Perform operations at the binary level (&, |, ^, ~, <<, >>).

Python input and output functions


Python's primary built-in functions for standard input and output are input() and print().

The input() function

The input() function is used to take input from the user via the keyboard during program execution.

• Syntax: variable_name = input("Optional prompt message:")

• Behavior:

o It pauses the program and waits for the user to type something and press the Enter key.

o It always returns the user's input as a string, regardless of what is typed (e.g., numbers
are returned as strings).

o An optional prompt message can be included to guide the user on what to enter.

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

Type Conversion: To perform mathematical operations or work with other data types, you must
explicitly convert (typecast) the input using functions like int() or float()

name = input("Enter your name: ") # input is a string

age = int(input("Enter your age: ")) # input is converted to an integer

Multiple Inputs: You can take multiple inputs on a single line using the split() method, often
combined with map() for typecasting.

# For integer inputs separated by spaces:

num1, num2 = map(int, input("Enter two numbers separated by a space: ").split())

The print() function

The print() function is used to display output to the standard output device (usually the
console/screen).

• Syntax: print(value(s), sep='separator', end='end', file=file, flush=flush)

• Behavior:

o It can display strings, variables, and expressions.

o Multiple items separated by commas are printed with a space between them by default.

o By default, it adds a newline character (\n) at the end of the output.

• Key optional parameters:

o sep: Specifies the separator between multiple objects. The default is a single space (' ').

o end: Specifies what to print at the end of the line instead of the default newline (\n).

Output Formatting: Advanced formatting can be achieved using formatted string literals (f-
strings) or the [Link]() method.

Examples:

print("Hello, World!") # Simple message

print("My age is:", 25) # Multiple items with a default space separator

print("G", "F", "G", sep="#") # Output: G#F#G

print("Same line", end=" ")

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)


Python – Unit -1

print("output.") # Output: Same line output.

# Using an f-string for formatting

item = "laptop"

price = 999.99

print(f"The {item} costs ${price:.2f}.") # Output: The laptop costs $999.99.

*************End of Unit 1***************

KANPUR INSTITUTE OF TECHNOLOGY PROFESSOR -ASHISH TRIPATHI ( Dept. CSE)

You might also like