Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Unit 1 Introduction on to Python Programming Language

This document provides an introduction to Python programming, covering its features, execution process, built-in data types, and basic syntax. It explains variables, strings, operators, conditional statements, loops, and functions, along with lists and tuples. The document serves as a comprehensive guide for beginners to understand the fundamentals of Python programming.

Uploaded by

Tanisha Mandhani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit 1 Introduction on to Python Programming Language

This document provides an introduction to Python programming, covering its features, execution process, built-in data types, and basic syntax. It explains variables, strings, operators, conditional statements, loops, and functions, along with lists and tuples. The document serves as a comprehensive guide for beginners to understand the fundamentals of Python programming.

Uploaded by

Tanisha Mandhani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit 1 Introduction on to Python Programming Language: Why and for What Python?

Program execu
on Process, Built- in Data Types, Variables, Strings and String methods, Numbers, Basic Input, Output
and command line input, String forma ng, Pythonliterals, Operators: Arithme c, Comparison,
Assignment, Logical, Bitwise, Membership, and Iden ty, Comments, Indenta on, First Python
program, Styling Python code. Condi onal Statements- If, If-else, Nested If-else, Itera ve Statement –
For, While, Nested Loops, Control statements – Break, Con nue, Pass.

Introduction to Python Programming

Python is a high-level, interpreted, dynamically typed, and general-purpose programming language.


It was created by Guido van Rossum and first released in 1991.

Why Python?

1. Easy to Learn & Readable – Uses simple English-like syntax.

2. Interpreted – No need for compilation, executed line by line.

3. Cross-Platform – Runs on Windows, macOS, and Linux.

4. Extensive Libraries – Includes built-in modules for data science, machine learning, web
development, etc.

5. Open Source & Free – No licensing costs.

6. Dynamically Typed – No need to declare variable types.

7. Object-Oriented – Supports OOP principles.

Python Program Execution Process

Steps:

1. Write the Python script (.py file).

2. Interpretation by Python Interpreter:

o Converts the source code into bytecode.

o Bytecode is sent to the Python Virtual Machine (PVM).

o PVM executes the code.

📌 Example:

python

CopyEdit

print("Hello, World!")

💡 Run using:

nginx
CopyEdit

python filename.py

Built-in Data Types in Python

1. Numeric Types

 int (Integer) → 10, -5

 float (Decimal) → 3.14, -2.5

 complex (Imaginary) → 2 + 3j

📌 Example:

python

CopyEdit

a = 10 # int

b = 3.14 # float

c = 2 + 3j # complex

print(type(a), type(b), type(c))

2. Sequence Types

 str (String) → "Hello"

 list (Ordered, Mutable) → [1, 2, 3]

 tuple (Ordered, Immutable) → (1, 2, 3)

📌 Example:

python

CopyEdit

s = "Python"

l = [1, 2, 3]

t = (4, 5, 6)

print(type(s), type(l), type(t))

3. Set Types

 set (Unordered, Unique) → {1, 2, 3}

 frozenset (Immutable Set) → frozenset({1, 2, 3})

4. Mapping Type

 dict (Key-Value pairs) → {"name": "Alice", "age": 25}


Variables in Python

 No need to declare type.

 Variable names are case-sensitive.

📌 Example:

python

CopyEdit

name = "Alice"

age = 25

print(name, age)

Strings and String Methods

String Methods:

Method Description

upper() Converts to uppercase

lower() Converts to lowercase

strip() Removes whitespace

replace(a, b) Replaces a with b

split() Splits string into a list

📌 Example:

python

CopyEdit

text = " Hello Python "

print(text.upper()) # " HELLO PYTHON "

print(text.strip()) # "Hello Python"

Numbers

Basic Arithmetic Operations

📌 Example:

python

CopyEdit
a, b = 10, 3

print(a + b) # Addition

print(a - b) # Subtraction

print(a * b) # Multiplication

print(a / b) # Division

print(a // b) # Floor division

print(a % b) # Modulus

print(a ** b) # Exponentiation

Basic Input & Output

Taking User Input

📌 Example:

python

CopyEdit

name = input("Enter your name: ")

print("Hello", name)

Command-Line Input

Run a Python file from the terminal:

nginx

CopyEdit

python script.py arg1 arg2

Use sys.argv to access arguments.

String Formatting

Different Formatting Methods

📌 Example:

python

CopyEdit

name = "Alice"

age = 25

print(f"My name is {name} and I am {age} years old.") # f-string


Python Literals

 Numeric Literals: 10, 3.14

 String Literals: "Hello"

 Boolean Literals: True, False

 Special Literal: None

📌 Example:

python

CopyEdit

x = None

print(type(x)) # <class 'NoneType'>

Operators in Python

Type Operators

Arithmetic + - * / // % **

Comparison == != > < >= <=

Assignment = += -= *= /=

Logical and or not

Bitwise `&

Membership in, not in

Identity is, is not

📌 Example:

python

CopyEdit

x = 10

y = 20

print(x > y and y > 5) # False

print(x in [10, 20, 30]) # True

Comments and Indentation


Comments

 Single-line comment: # This is a comment

 Multi-line comment:

python

CopyEdit

"""

This is a

multi-line comment

"""

Indentation

Python uses indentation instead of {}.

📌 Example:

python

CopyEdit

if True:

print("Indented block")

First Python Program

📌 Example:

python

CopyEdit

print("Hello, World!")

Styling Python Code

Follow PEP 8 guidelines:

 Use snake_case for variable names.

 Indentation: 4 spaces per level.

 Keep line length ≤79 characters.

Conditional Statements

📌 Example:
python

CopyEdit

x = 10

if x > 5:

print("x is greater than 5")

elif x == 5:

print("x is 5")

else:

print("x is less than 5")

Loops in Python

For Loop

📌 Example:

python

CopyEdit

for i in range(5):

print(i)

While Loop

📌 Example:

python

CopyEdit

x=5

while x > 0:

print(x)

x -= 1

Nested Loops

📌 Example:

python

CopyEdit

for i in range(3):

for j in range(3):
print(i, j)

Control Statements

Break Statement

📌 Example:

python

CopyEdit

for i in range(5):

if i == 3:

break

print(i)

Continue Statement

📌 Example:

python

CopyEdit

for i in range(5):

if i == 2:

continue

print(i)

Pass Statement

📌 Example:

python

CopyEdit

for i in range(5):

pass # Placeholder for future code

Func ons: How func ons communicate with their environment? Returning a result from func on,
Types of func on, func on crea on, types of func on crea on, calling, passing parameters, Func on
Scopes ,types of Arguments passed in func on, Lamda Func on. List: Basic List opera ons, Indexing,
Slicing, organizing a list, Built-in func ons of list, Working with list and a part of a list, Condi onal
Execu on, Boolean Expressions, Condi onal Statements with Lists, List Comprehension Expression,
While and For Loop,Itera ons, Documenta on Interlude. Tuple: defini on, Crea on, accessing, dele on,
Itera on, conver ng between list and tuple.

Functions in Python

A function is a reusable block of code that performs a specific task.

1. Function Communication

Functions communicate with their environment in two ways:

1. Passing arguments (input)

2. Returning values (output)

📌 Example:

python

CopyEdit

def greet(name): # Function receives input

return f"Hello, {name}!" # Function returns output

message = greet("Alice")

print(message) # Output: Hello, Alice!

2. Returning a Result from a Function

 Use return to send a result back.

 Functions without return return None.

📌 Example:

python

CopyEdit

def add(a, b):

return a + b

result = add(5, 3)

print(result) # Output: 8

📌 Returning Multiple Values:

python
CopyEdit

def get_person():

return "Alice", 25 # Returns a tuple

name, age = get_person()

print(name, age) # Output: Alice 25

3. Types of Functions

1. Built-in functions: print(), len(), sum()

2. User-defined functions: Created by the user.

3. Recursive functions: A function that calls itself.

4. Lambda functions: Anonymous functions (one-liners).

5. Higher-order functions: Functions that take other functions as arguments.

4. Function Creation & Calling

📌 Defining and Calling a Function:

python

CopyEdit

def square(n):

return n * n

print(square(4)) # Output: 16

5. Types of Arguments in Functions

a) Positional Arguments

Arguments passed in the correct order.

python

CopyEdit

def info(name, age):

print(f"{name} is {age} years old.")


info("Alice", 25)

b) Default Arguments

Default values if no argument is given.

python

CopyEdit

def greet(name="Guest"):

print(f"Hello, {name}!")

greet() # Output: Hello, Guest!

greet("Bob") # Output: Hello, Bob!

c) Keyword Arguments

Pass values using parameter names.

python

CopyEdit

def person(name, age):

print(f"Name: {name}, Age: {age}")

person(age=30, name="Alice")

d) Variable-Length Arguments

i) *args (Multiple Positional Arguments)

python

CopyEdit

def add(*numbers):

return sum(numbers)

print(add(1, 2, 3, 4)) # Output: 10

ii) **kwargs (Multiple Keyword Arguments)

python

CopyEdit

def info(**details):

for key, value in details.items():


print(f"{key}: {value}")

info(name="Alice", age=25, city="NY")

6. Function Scope

a) Local Scope

Variables inside a function.

python

CopyEdit

def example():

x = 10 # Local variable

print(x)

example()

# print(x) # Error: x is not defined outside function

b) Global Scope

Variables outside functions.

python

CopyEdit

x = 10 # Global variable

def example():

print(x) # Accessing global variable

example()

c) global Keyword

Modify global variables inside a function.

python

CopyEdit

x = 10
def modify():

global x

x += 5

modify()

print(x) # Output: 15

7. Lambda Functions (Anonymous Functions)

 A one-line function using lambda.

📌 Example:

python

CopyEdit

square = lambda x: x * x

print(square(4)) # Output: 16

📌 Multiple Arguments:

python

CopyEdit

add = lambda a, b: a + b

print(add(3, 5)) # Output: 8

Lists in Python

Lists are ordered, mutable, and can store heterogeneous elements.

📌 Creating a List:

python

CopyEdit

my_list = [1, 2, 3, "Python", 4.5]

1. Basic List Operations

python

CopyEdit

l = [10, 20, 30]

l.append(40) # Add item


l.remove(20) # Remove item

l.insert(1, 25) # Insert item at index

print(l) # Output: [10, 25, 30, 40]

2. Indexing & Slicing

📌 Accessing Elements:

python

CopyEdit

l = [10, 20, 30, 40]

print(l[1]) # Output: 20

print(l[-1]) # Output: 40

📌 Slicing:

python

CopyEdit

print(l[1:3]) # Output: [20, 30]

print(l[:2]) # Output: [10, 20]

print(l[::2]) # Output: [10, 30]

3. List Comprehension

📌 Example:

python

CopyEdit

squares = [x*x for x in range(5)]

print(squares) # Output: [0, 1, 4, 9, 16]

4. Iteration Over Lists

Using for Loop

python

CopyEdit

for item in [1, 2, 3]:

print(item)

Using while Loop


python

CopyEdit

i=0

l = [10, 20, 30]

while i < len(l):

print(l[i])

i += 1

5. Built-in List Functions

Function Description

len(l) Length of list

max(l) Maximum value

min(l) Minimum value

sum(l) Sum of elements

sorted(l) Sorts the list

📌 Example:

python

CopyEdit

l = [3, 1, 4, 2]

print(sorted(l)) # Output: [1, 2, 3, 4]

Tuples in Python

Tuples are ordered, immutable sequences.

📌 Creating a Tuple:

python

CopyEdit

t = (1, 2, 3, "Python")

print(type(t)) # Output: <class 'tuple'>

1. Accessing Tuple Elements

python

CopyEdit
print(t[1]) # Output: 2

print(t[-1]) # Output: Python

2. Iterating Through a Tuple

python

CopyEdit

for item in t:

print(item)

3. Converting Between List and Tuple

📌 Tuple → List:

python

CopyEdit

t = (1, 2, 3)

l = list(t)

📌 List → Tuple:

python

CopyEdit

l = [1, 2, 3]

t = tuple(l)

Summary

 Functions: Communication, return values, argument types, lambda functions.

 Lists: Indexing, slicing, iteration, list comprehension.

 Tuples: Immutable, accessing, iteration, conversion.

You might also like