0% found this document useful (0 votes)
1 views14 pages

Python Uint 1

This document serves as an introduction to Python programming, covering its features, installation, and basic coding practices. It explains variables, data types, operators, and provides examples of list, tuple, and string operations. Additionally, it includes practical tasks and examples for computations and logical statements using Python.

Uploaded by

sidhharthm9
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)
1 views14 pages

Python Uint 1

This document serves as an introduction to Python programming, covering its features, installation, and basic coding practices. It explains variables, data types, operators, and provides examples of list, tuple, and string operations. Additionally, it includes practical tasks and examples for computations and logical statements using Python.

Uploaded by

sidhharthm9
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/ 14

Unit 1

🔹 Introduction to Python

✅ What is Python?

Python is a high-level, interpreted, and general-purpose programming language. It was


created by Guido van Rossum and first released in 1991. Python emphasizes readability
and allows developers to express concepts in fewer lines of code compared to other languages
like C++ or Java.

✅ Key Features of Python:

Feature Description
Simple Syntax Python uses English-like commands, making it beginner-friendly.
Interpreted No need to compile code. Python runs line-by-line.
Cross-Platform Works on Windows, macOS, and Linux.
Dynamically No need to declare variable types; Python figures it out during
Typed execution.
Open Source Free to use and distribute, with a large community for support.
Versatile Can be used for web development, AI, data science, automation, etc.

✅ Why Learn Python?

 Widely used in academia and industry.


 Preferred language for data science, machine learning, web development, and
automation.
 Has a huge collection of libraries and frameworks (like Django, NumPy, Pandas,
Flask, etc.).
 It's a great first language for beginners.

✅ How Python Works:

Python is interpreted, meaning the code you write is read and executed line by line by the
Python interpreter. This is different from compiled languages like C++, where code must be
compiled before running.
✅ Installing Python:

1. Download Python:
o Go to https://www.python.org
o Download the latest version (preferably Python 3.x).
2. Install Python:
o Run the downloaded installer.
o Important: Check the box that says “Add Python to PATH” during
installation.
o Click “Install Now”.
3. Verify Installation:
o Open a terminal (Command Prompt on Windows or Terminal on Mac/Linux).
o Type:
o python --version

or

python3 --version

o You should see something like Python 3.12.0.

✅ Writing Python Code:

You can write Python code in:

 IDLE (Python’s built-in editor)


 Text Editors: VS Code, Sublime Text, Notepad++
 Online IDEs: Replit, Google Colab, Jupyter Notebook

Example program:

print("Hello, World!")

To run:

 Save it as hello.py
 Run in terminal:
 python hello.py

📝 Practice Task:

1. Install Python.
2. Open any editor or IDLE.
3. Write your first program:
4. print("Welcome to Python Programming!")
5. Run it and see the output.
🔹 Variables and Data Types in Python

✅ What is a Variable?

A variable is a name that refers to a value stored in memory. You use variables to store data
and use it later in the program.

➤ Declaring a variable:

Python does not require specifying the data type when declaring a variable.

x = 10 # Integer
name = "John" # String
pi = 3.14 # Float

Python determines the type automatically based on the assigned value. This is known as
dynamic typing.

✅ Variable Naming Rules:

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


✔ Can contain letters, digits (0–9), and underscores.
❌ Cannot begin with a digit.
❌ Cannot use reserved keywords (like if, class, for, etc.)

Examples:

_valid = 1
user_name = "Alice"
age2 = 20
🔸 Data Types in Python

Python has several built-in data types. Let’s go over the most important ones:

✅ 1. Numeric Types

Type Description Example

int Whole numbers x = 10

float Decimal numbers pi = 3.14

complex Complex numbers (a + bj) z = 2 + 3j

✅ 2. Text Type

Type Description Example

str String (text) name = "Alice"

✅ 3. Boolean Type

Type Description Example

bool True or False is_valid = True

✅ 4. Sequence Types

Type Description Example

list Ordered, mutable collection fruits = ["apple", "banana"]

tuple Ordered, immutable collection colors = ("red", "blue")

str Sequence of Unicode characters "Hello"


✅ 5. Set and Dictionary

Type Description Example

set Unordered collection of unique values s = {1, 2, 3}

dict Collection of key-value pairs d = {"name": "John", "age": 25}

✅ Checking the Data Type

Use the built-in type() function:

a=5
print(type(a)) # <class 'int'>

b = "Python"
print(type(b)) # <class 'str'>

📝 Practice Task:

Try declaring and printing the following:

x = 42
name = "Python"
marks = 85.5
is_passed = True
colors = ["red", "green", "blue"]
person = {"name": "Alice", "age": 22}

print(type(x))
print(type(name))
print(type(marks))
print(type(is_passed))
print(type(colors))
print(type(person))
🔹 Operators in Python

Operators are symbols that perform operations on variables and values. Python supports
several types of operators.

✅ 1. Arithmetic Operators

Used to perform mathematical operations.

Operator Description Example Output

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/2 2.5

// Floor Division 5 // 2 2

% Modulus (remainder) 5 % 2 1

** Exponentiation 2 ** 3 8

🔸 Example:

a = 10
b=3
print(a + b)
print(a % b)
print(a ** b)

✅ 2. Assignment Operators

Used to assign values to variables.

Operator Example Same As

= x=5 Assign 5 to x

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 2 x=x*2
Operator Example Same As

/= x /= 2 x=x/2

//= x //= 2 x = x // 2

%= x %= 2 x=x%2

**= x **= 2 x = x ** 2

✅ 3. Comparison Operators

Used to compare values; returns True or False.

Operator Description Example

== Equal to 5 == 5 → True

!= Not equal to 5 != 3 → True

> Greater than 5 > 3 → True

< Less than 5 < 3 → False

>= Greater or equal 5 >= 5 → True

<= Less or equal 3 <= 4 → True

✅ 4. Logical Operators

Used to combine conditional statements.

Operator Description Example

and True if both are true (5 > 3 and 2 < 4) → True

or True if at least one is true (5 > 3 or 2 > 4) → True

not Reverses the result not(5 > 3) → False


✅ 5. Membership Operators

Check if a value is in a sequence (list, string, etc.)

Operator Description Example

in True if present "a" in "apple" → True

not in True if not present "x" not in "apple" → True

✅ 6. Identity Operators

Check if two variables point to the same memory location.

Operator Description Example

is True if same identity x is y

is not True if not same identity x is not y

🔸 Example:

a = [1, 2]
b=a
c = [1, 2]

print(a is b) # True
print(a is c) # False (different memory location)

✅ 7. Bitwise Operators (used for binary operations)

Operator Description Example

& AND 5&3→1

` ` OR

^ XOR 5^3→6

~ NOT (invert) ~5

<< Left Shift 5 << 1 → 10

>> Right Shift 5 >> 1 → 2


📝 Practice Task:

Write a Python script using each of these operators at least once:

a = 10
b=3
print("Addition:", a + b)
print("Is a greater than b?", a > b)
print("Bitwise AND:", a & b)
print("a is b:", a is b)
print("a in [10, 20]:", a in [10, 20])

🔹 List, Tuple, and String Operations in Python

These are sequence data types in Python used to store collections of items. Each has
different properties in terms of mutability and usage.

✅ 1. List Operations

A list is an ordered, mutable (changeable) collection of items.

➤ Creating a List:

fruits = ["apple", "banana", "cherry"]

➤ Common List Operations:

Operation Example Description

Access by index fruits[0] Returns "apple"

Negative indexing fruits[-1] Returns "cherry" (last item)

Slicing fruits[0:2] Returns ["apple", "banana"]

Append item fruits.append("orange") Adds to end

Insert at index fruits.insert(1, "grape") Inserts at index 1

Remove item fruits.remove("banana") Removes specific item

Pop last item fruits.pop() Removes and returns last item


Operation Example Description

Length of list len(fruits) Returns number of items

Sort items fruits.sort() Sorts list (ascending)

Reverse list fruits.reverse() Reverses list

Check item in list "apple" in fruits Returns True if present

✅ 2. Tuple Operations

A tuple is an ordered, immutable (unchangeable) collection of items.

➤ Creating a Tuple:

colors = ("red", "green", "blue")

➤ Common Tuple Operations:

Operation Example Description

Access by index colors[1] Returns "green"

Slicing colors[0:2] Returns ("red", "green")

Length of tuple len(colors) Returns number of items

Check item in tuple "blue" in colors Returns True if present

🔸 Tuples are faster and safer than lists when you don’t need to modify the data.

✅ 3. String Operations

A string is a sequence of Unicode characters. Strings are immutable.

➤ Creating a String:

greeting = "Hello, Python!"

➤ Common String Operations:


Operation Example Description

Access by index greeting[0] Returns 'H'

Slicing greeting[0:5] Returns 'Hello'

Concatenation "Hello" + " World" Returns "Hello World"

Repetition "Ha" * 3 Returns "HaHaHa"

Length of string len(greeting) Returns number of characters

Convert to upper case greeting.upper() "HELLO, PYTHON!"

Convert to lower case greeting.lower() "hello, python!"

Replace text greeting.replace("Python", "World") "Hello, World!"

Split into list greeting.split(",") ["Hello", " Python!"]

Strip whitespace " Hello ".strip() "Hello"

Find substring "Python".find("th") 2

✅ Mutable vs Immutable Summary

Type Mutable? Example

List ✅ Yes Can be changed

Tuple ❌ No Cannot be changed

String ❌ No Cannot be changed

📝 Practice Task:

Try the following code:

# List operations
numbers = [10, 20, 30, 40]
numbers.append(50)
print(numbers)
numbers.remove(20)
print(numbers[1:3])
# Tuple operations
info = ("Alice", 21, "Student")
print(info[0])
print(len(info))

# String operations
text = " Python Programming "
print(text.strip())
print(text.upper())
print(text.replace("Python", "Java"))

🔹 Perform Computations and Create Logical Statements Using Operators

This topic focuses on combining data types, operators, and logical thinking to solve real-
world problems using Python.

✅ 1. Using Arithmetic for Computations

You can calculate everything from shopping bills to scientific values using Python's
arithmetic operators.

📌 Example 1: Calculate Area of a Circle

radius = 5
pi = 3.14
area = pi * (radius ** 2)
print("Area of circle is:", area)

📌 Example 2: Student’s Percentage

math = 85
science = 90
english = 80

total = math + science + english


percentage = total / 3

print("Total:", total)
print("Percentage:", percentage)

✅ 2. Using Logical and Comparison Operators for Decisions

These are used in if, else, and elif conditions to control program flow.

📌 Example 3: Check Eligibility to Vote


age = 18

if age >= 18:


print("Eligible to vote")
else:
print("Not eligible to vote")

📌 Example 4: Discount Calculator Using Logical Operator

price = 1200
member = True

if price > 1000 and member:


discount = 0.1 * price
print("Discount:", discount)
else:
print("No discount")

📌 Example 5: Grading System Using Comparison

marks = 75

if marks >= 90:


grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 50:
grade = "C"
else:
grade = "F"

print("Grade:", grade)

✅ 3. Using Membership and Identity in Programs

📌 Example 6: Username Check with in

users = ["admin", "teacher", "student"]

username = input("Enter your username: ")

if username in users:
print("Access granted")
else:
print("Access denied")
📌 Example 7: is vs ==

a = [1, 2]
b = [1, 2]
c=a

print(a == b) # True (same content)


print(a is b) # False (different memory)
print(a is c) # True (same object)

✅ Practice Problems

Try writing code for the following:

1. Write a program to compute the Simple Interest.


2. Ask the user to enter two numbers and check which one is greater.
3. Check if a given number is even or odd.
4. Accept marks of a student and print whether they passed or failed (pass if marks ≥
35).
5. Check if a given word exists in a list of fruits.

You might also like