0% found this document useful (0 votes)
10 views9 pages

Introduction to Python Programming

The document provides an introduction to Python, highlighting its features, advantages, and limitations. It covers mutable and immutable objects, various operators, string manipulation, and includes simple Python program examples. Overall, it serves as a comprehensive guide for beginners to understand the basics of Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Introduction to Python Programming

The document provides an introduction to Python, highlighting its features, advantages, and limitations. It covers mutable and immutable objects, various operators, string manipulation, and includes simple Python program examples. Overall, it serves as a comprehensive guide for beginners to understand the basics of Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🌟 1.

Introduction to Python
Python is a high-level, interpreted, and easy-to-learn programming language.
It was developed by Guido van Rossum in 1991.
It is used for web development, data science, machine learning, automation, and many more
areas.

✨ Features of Python

1. Simple syntax – looks like English.


2. Interpreted – runs line by line, no need to compile.
3. Portable – runs on Windows, Mac, and Linux.
4. Dynamically typed – no need to mention variable type.
5. Object-oriented – supports classes and objects.
6. Free and open-source.
7. Large library support.

✅ 2. Advantages of Python
1. Easy to learn and understand.
2. Portable (run anywhere).
3. Free and open-source.
4. Huge library support.
5. Short and readable code.
6. Used in many applications (AI, Web, ML, Data Science).

⚠️3. Limitations of Python


1. Slower than C/C++ (because it is interpreted).
2. Not suitable for mobile app development.
3. Uses more memory.
4. Runtime errors may occur (no compile-time checking).
5. Doesn’t support real multithreading (due to GIL).

💻 4. Ways to Write Python Programs


Mode Description Example
Interactive Mode Type and run line by line in Python shell >>> print("Hello")
Script Mode Write full program in .py file and run python [Link]

🔁 5. Mutable and Immutable Objects in Python

💡 Basic Idea
Every variable in Python stores a reference (memory address) to an object in memory.

When you change the value of a variable:

 If the object can be changed → it is mutable.


 If the object cannot be changed → it is immutable.

🔷 1. Mutable Objects
👉 Mutable objects can be changed or modified after they are created.
When you modify them, the same memory location (id) is used.

✅ Examples:

 list
 dictionary
 set

🔹 Example 1: Mutable List


numbers = [10, 20, 30]
print("Before:", numbers)
print("Memory id before:", id(numbers))

[Link](40) # modify list


print("After:", numbers)
print("Memory id after:", id(numbers))

Output:
Before: [10, 20, 30]
Memory id before: 140210194493888
After: [10, 20, 30, 40]
Memory id after: 140210194493888

✅ The memory id is the same, which means the list changed in place — that’s why it’s
mutable.

🔹 Example 2: Mutable Dictionary


person = {"name": "Riya", "age": 20}
print(id(person))

person["age"] = 21 # change value


print(person)
print(id(person))

✅ Same id → object updated inside same memory block.

🔷 2. Immutable Objects
👉 Immutable objects cannot be changed after they are created.
If you try to modify them, Python creates a new object in a new memory location.

✅ Examples:

 int
 float
 string
 tuple

🔹 Example 1: Immutable String


name = "Riya"
print("Before:", name)
print("Memory id before:", id(name))

name = name + " Sharma" # modify string


print("After:", name)
print("Memory id after:", id(name))

Output:
Before: Riya
After: Riya Sharma
Memory id before: 140206283493296
Memory id after: 140206283496784

⚠️The memory id changed, meaning the old object was replaced by a new one → strings are
immutable.

🔹 Example 2: Immutable Tuple


t = (1, 2, 3)
print(id(t))

t = t + (4,)
print(id(t))

⚠️The id changes because tuples cannot be changed, so Python makes a new tuple.

🔁 Comparison Summary
Property Mutable Immutable

Can value be changed? ✅ Yes ❌ No

Memory location after modification Same Changes

Examples list, dict, set int, float, str, tuple

Used when You want editable data You want constant or fixed data

➕ 6. Operators in Python
Operators are symbols used to perform operations on values or variables.

🧮 A. Arithmetic Operators

Operator Meaning Example Output


+ Addition 10 + 5 15
Operator Meaning Example Output
- Subtraction 10 - 5 5
* Multiplication 4*3 12
/ Division 10 / 4 2.5
// Floor Division 10 // 4 2
% Modulus (remainder) 10 % 3 1
** Power 2 ** 3 8

📝 B. Assignment Operators

Operator Meaning Example


= Assign value x = 10
+= Add and assign x += 5 (x = x + 5)
-= Subtract and assign x -= 2
*= Multiply and assign x *= 3
/= Divide and assign x /= 2
%= Modulus and assign x %= 2
**= Power and assign x **= 2

⚖️C. Comparison Operators

Operator Meaning Example Output


== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 2<5 True
>= Greater or equal 5 >= 5 True
<= Less or equal 3 <= 5 True

🧠 D. Logical Operators

Operator Meaning Example Output


and True if both true (5 > 3) and (6 > 4) True
or True if one true (5 > 3) or (6 < 4) True
not Reverse result not(5 > 3) False

⚙️E. Identity Operators


Operator Meaning Example Output
is Same object x is y True/False
is not Not same object x is not y True/False

📚 F. Membership Operators

Operator Meaning Example Output


in Value present 3 in [1,2,3] True
not in Value not present 4 not in [1,2,3] True

🔤 7. Strings in Python
A string is a collection of characters inside quotes.
Example:

name = "Python"

Strings are immutable (cannot change characters).

✂️String Slicing
s = "Python"
print(s[0:3]) # Pyt
print(s[:]) # Python
print(s[::-1]) # Reverse → nohtyP

🧰 String Functions

Function Description Example Output


upper() Convert to uppercase "hi".upper() HI
lower() Convert to lowercase "HI".lower() hi
title() First letter capital "hello world".title() Hello World
capitalize() First letter capital only "python".capitalize() Python
strip() Remove spaces " hello ".strip() hello
replace(a,b) Replace substring "good".replace("g","f") food
split() Split string into list "a,b,c".split(",") ['a','b','c']
join() Join list to string " ".join(['Hi','All']) Hi All

find(x)
Find first position of "banana".find("a") 1
substring
rfind(x) Find last position "banana".rfind("a") 5
Function Description Example Output
index(x)
Same as find(), error if not "banana".index("a") 1
found
rindex(x)
Same as rfind(), error if not "banana".rindex("a") 5
found
count(x) Count substring "banana".count("a") 3
startswith(x) Check start "python".startswith("py") True
endswith(x) Check end "[Link]".endswith(".txt") True
isdigit() Check all digits "123".isdigit() True
isalpha() Check all letters "abc".isalpha() True
isalnum() Check letters & numbers "abc123".isalnum() True

💬 String Formatting

1️⃣ Using format()

name = "Tina"
age = 21
print("My name is {} and I am {} years old.".format(name, age))

2️⃣ Using f-string

name = "Tina"
age = 21
print(f"My name is {name} and I am {age} years old.")

🧾 8. Simple Python Programs


✅ 1. Input a Digit and Print in Words
digit = int(input("Enter a digit (0-9): "))

if digit == 0:
print("Zero")
elif digit == 1:
print("One")
elif digit == 2:
print("Two")
elif digit == 3:
print("Three")
elif digit == 4:
print("Four")
elif digit == 5:
print("Five")
elif digit == 6:
print("Six")
elif digit == 7:
print("Seven")
elif digit == 8:
print("Eight")
elif digit == 9:
print("Nine")
else:
print("Invalid input")

✅ 2. List Comprehension Example


# Squares of numbers
squares = [x**2 for x in range(1, 6)]
print(squares)

# Even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens)

# Cube divided by 3
x = [int(i**3/3) for i in range(0,5,2)]
print(x)

✅ 3. Display ASCII Code and Character


for i in range(65, 91):
print(i, "->", chr(i))

✅ 4. Alphabet Pattern Program


A
A B
A B C
A B C D
n = 4
for i in range(1, n+1):
for j in range(65, 65+i):
print(chr(j), end=' ')
print()

✅ 5. Star Pattern Program


*
**
***
****
n = 4
for i in range(1, n+1):
print('*' * i)

Common questions

Powered by AI

Python might be less suitable in scenarios requiring high performance because it is generally slower than C/C++ due to being an interpreted language. It is also not ideal for mobile app development and may cause runtime errors because it lacks compile-time checking. Furthermore, Python does not support true multithreading due to the Global Interpreter Lock (GIL).

As an interpreted language, Python executes code line-by-line, which can slow down performance compared to compiled languages like C++. However, this feature allows for more flexibility in development and easier debugging. The lack of compile-time error detection means more runtime errors may occur, requiring thorough testing to ensure code reliability .

Python is considered portable because it can run on various operating systems like Windows, Mac, and Linux without requiring any special modifications to the code .

F-strings in Python allow for straightforward and intuitive string formatting by embedding expressions directly within string literals, making the code more readable and concise. They evaluate code at runtime, enhancing performance and reducing the likelihood of errors compared to other formatting methods like format().

List comprehensions streamline the process of creating lists by embedding a compact syntax for constructing a list in place. They offer a more concise and readable way to apply operations to sequence elements, reducing the amount of code and enhancing performance through optimization behind the scenes .

Python's dynamic typing allows for more flexibility, as variable types do not need to be declared explicitly, enabling faster prototyping and development. However, it can lead to unexpected behavior and bugs due to type-related errors being only caught at runtime, increasing the need for comprehensive testing and documentation .

Python's string immutability prevents modifications to existing string objects, leading to the creation of new objects whenever a string is altered. This can simplify reasoning about code behavior since strings remain unchanged and reliable throughout their lifecycle, but it may also lead to increased memory usage when dealing with large-scale string operations .

Mutable objects, like lists and dictionaries, can be changed in place using the same memory location, which can be efficient for memory management when modifying data. Immutable objects, such as strings and tuples, create a new object with a new memory address whenever a change is made, which can lead to increased memory usage as new objects are created for each modification .

Python is highly suitable for automation and data science because of its simple syntax and extensive support in terms of libraries and frameworks like NumPy, Pandas, and TensorFlow, which handle complex computations efficiently. These features reduce the need for verbose code, allowing developers to focus on the logic and application of data analysis rather than mundane coding tasks .

Python's arithmetic operators (e.g., +, -, *, /) are straightforward and behave in an expected manner consistent with standard mathematical operations, aiding readability. Logical operators like 'and', 'or', and 'not' allow for concise expression of complex conditions, enhancing both readability and efficiency by enabling short-circuit evaluation .

You might also like