0% found this document useful (0 votes)
3 views13 pages

Python

Uploaded by

Chess Holic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Python

Uploaded by

Chess Holic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

Python

🐍 Lesson 0: What is Python?


✅ Python is:

A programming language (like Hindi or English, but for computers!)

Used to make websites, apps, games, and even robots!

Very easy to learn (perfect for beginners like you)

How do we write Python?

You write Python code in a tool called a code editor.

There are many types:

Online: Replit, Google Colab

Offline: Install Python on your computer and use IDLE or VS Code

To keep it simple, you can start on https://replit.com (but you can also use Google
Colab)

✅ First Python Program:


Type this code into the editor:

python
print("Hello, Aradhya!")
This means: Print this sentence on the screen.

🐍 Python Lesson 1: Variables and Data Types


What is a variable?
A variable is like a box where you store information (like numbers or words) to use
later.

Example:

python
name = "Aradhya"
age = 13
height = 5.08

Here:

name stores the word "Aradhya" (a string)

age stores the number 13 (an integer)

height stores the decimal number 5.08 (a float)

Data Types You Should Know:


DataType Example Description
str "Hello" Text or words (strings)
int 10 Whole numbers
float 3.14 Decimal numbers
bool True or False True or False values

Try This Code in Google Colab:


python
name = "Aradhya"
age = 13
height = 5.08
is_student = True

print(name)
print(age)
print(height)
print(is_student)
Run it by pressing Shift + Enter and see the results!

| Term | Example | Description |


| ---------------- | ---------------- | ------------------------------ |
| String Constant | `"Hello"` | Fixed text in quotes |
| String Variable | `name = "Hello"` | Variable holding string value |
| Numeric Constant | `10` or `3.14` | Fixed number |
| Numeric Variable | `age = 13` | Variable holding numeric value |

✅ f-string stands for formatted string.


It’s a way to include variables and expressions inside a string without using + or
commas.

📌 Syntax:
python
f"your text {variable_or_expression}"
Just put an f before the quotes, and write variables inside { }.

🧪 Example:
python
name = "Aradhya"
age = 13
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Aradhya and I am 13 years old.
✅ Data Types You Can Use in f-strings
You can include any data type:

Type Example inside f-string


str {name}
int {age}
float {height}
bool {is_student}
list {my_list}
math {5 + 3} or {age * 2}

🔥 Bonus: Expressions inside f-string


python
a = 10
b = 5
print(f"The sum of a and b is {a + b}")
Output:
The sum of a and b is 15

🧠 Why use f-strings?


✅ Clean and easy
✅ No need for + or str()
✅ Looks good and works fast
🐍 Lesson 2: Operators in Python
In Python, operators are symbols that tell the computer to do something with values
(called operands).

✅ 1. Arithmetic Operators
Used for math operations:
| Operator | Meaning | Example | Result |
| -------- | -------------- | -------- | ------ |
| `+` | Addition | `5 + 2` | `7` |
| `-` | Subtraction | `5 - 2` | `3` |
| `*` | Multiplication | `5 * 2` | `10` |
| `/` | Division | `5 / 2` | `2.5` |
| `//` | Floor Division | `5 // 2` | `2` |
| `%` | Modulus | `5 % 2` | `1` |
| `**` | Exponentiation | `2 ** 3` | `8` |

✅ 2. Assignment Operators
Used to assign values to variables.
| Operator | Example | Meaning |
| -------- | -------- | ------------- |
| `=` | `x = 5` | Assign 5 to x |
| `+=` | `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.
| Operator | Meaning | Example | Result |
| -------- | ------------------- | -------- | ------ |
| `==` | Equal to | `5 == 5` | True |
| `!=` | Not equal to | `5 != 3` | True |
| `>` | Greater than | `5 > 3` | True |
| `<` | Less than | `5 < 3` | False |
| `>=` | Greater or equal to | `5 >= 5` | True |
| `<=` | Less or equal to | `5 <= 3` | False |

🧪 Try this example:


python
x = 10
y = 3
print("Addition:", x + y)
print("Division:", x / y)
print("Remainder:", x % y)
print("Is x greater than y?", x > y)

Reminder-
| Math | Python Code |
| -------- | ----------- |
| 2³ | `2 ** 3` ✅ |
| Not this | `2 ^ 3` ❌ |

✅ What is Floor Division?


Floor Division means:

Divide the number and remove the decimal part — even if the result is not a whole
number.
🔹 Symbol: //
🧮 Example:
python
7 // 2

👉 Normal division: 7 / 2 = 3.5


👉 Floor division: 7 // 2 = 3 (it cuts off the .5 part, not round)

More Examples:
python
9 // 4 → 2
10 // 3 → 3
5 // 5 → 1

Even with negative numbers:

python
-7 // 2 → -4

Because it goes to the lower number, not just cuts decimal.

🎯 Quick trick:
/ → gives decimal

// → gives only whole number (floor)

Where is it useful?
When you only care how many full groups fit in (like dividing students into teams)

Or when you don’t want decimals (like pages, chairs, steps)

✅ What is Modulus (%) in Python?


The modulus operator % gives you the remainder after division.

📘 Example:
python
7 % 2

➡️ 7 divided by 2 = 3 remainder 1
👉 So: 7 % 2 = 1 ✅

💡 More Examples:
python
10 % 3 = 1 (10 ÷ 3 = 3, remainder 1)
9 % 3 = 0 (9 ÷ 3 = 3, no remainder)
5 % 5 = 0 (5 ÷ 5 = 1, no remainder)
8 % 5 = 3 (8 ÷ 5 = 1, remainder 3)

🧁 Real-Life Use:
You can use % to check:

If a number is even or odd:

python
if number % 2 == 0:
print("Even")
else:
print("Odd")
If one number perfectly divides another:

python
if a % b == 0:
print("Yes, divisible")

| Operator | Meaning | Example | Result |


| -------- | ------------------- | -------- | ------ |
| `/` | Division | `7 / 2` | `3.5` |
| `//` | Floor Division | `7 // 2` | `3` |
| `%` | Remainder (Modulus) | `7 % 2` | `1` 9 |

🧠 x = x - 2 — What’s going on here?


This isn’t like math class — it’s Python code, not an algebra equation.

🔍 In coding:
x = x - 2 means:

Take the current value of x, subtract 2 from it, then store the new value back in
x.

🧮 Example:
python
x = 10
x = x - 2
print(x)

➡️ First, x is 10
➡️ Then, x - 2 = 8
➡️ Now x becomes 8
➡️ Output: 8

Not Algebra, It’s Assignment


In math, we can’t say:

x = x - 2 ❌
But in Python, it’s valid because:

Left side: Where to store

Right side: What to calculate

💡 In short:
x = x - 2 means → "decrease x by 2 and put it as x" ✅

🐍 Lesson 3: Taking Input from the User 🎤💡


So far, we've been giving data to the computer.
Now let's ask the user for data!

✅ 1. The input() Function


This function lets you take input from the user.

python
name = input("What is your name? ")
print("Hello,", name)
💬 This will show:
What is your name? Aradhya
Hello, Aradhya
The text inside " " is the message shown to the user.

✅ 2. By Default, Input is a String


If you take a number using input(), it will still be a string.

Example:

python
age = input("What is your age? ")
print(age + 1) # ❌ This gives an error!
To fix this, convert the input to a number using:

python
age = int(input("What is your age? "))
print("Next year, you'll be", age + 1)

✅ 3. Other Conversions
To Type Use this
Integer int()
Float float()
String str()

🧪 Try This Example:


python
name = input("Enter your name: ")
fav_sub = input("What's your favorite subject? ")
hours = int(input("How many hours do you study it? "))

print("Hello", name)
print("You study", fav_sub, "for", hours, "hours.")

🧠 Lesson 4: Type Conversion (Changing Data Types)


Sometimes, we need to convert one type of data into another.

For example:

If you take input using input(), it always gives a string, even if the user types a
number.

But to do math, we need integers or floats.

🔁 Common Type Conversions


| Conversion | Code Example | Result |
| ---------------- | -------------- | ------------------ |
| String → Integer | `int("5")` | `5` (int) |
| String → Float | `float("4.2")` | `4.2` (float) |
| Integer → String | `str(9)` | `"9"` (str) |
| Float → Integer | `int(3.9)` | `3` (cuts decimal) |

✨ Example Code:
python
age = input("What is your age? ") # input() gives string
age = int(age) # convert to integer

years_later = age + 5
print("You will be", years_later, "after 5 years.")
Without int(), the program would crash ❌ because you can't do math with strings!

💡 Tip:
You can also use:

bool() to convert to Boolean

type() to check the datatype

🧪 Lesson 5: The type() Function (Know Your Data Type!)


You’ve learned about:

Strings: "hello"

Integers: 5

Floats: 3.14

But how can you check what type something is?


🔍 Use type() to find out!

python
print(type("Aradhya")) # <class 'str'>
print(type(73)) # <class 'int'>
print(type(5.08)) # <class 'float'>

✨ Example:

python
name = "Aradhya"
height = 5.08
age = "14"

print(type(name)) # str
print(type(height)) # float
print(type(age)) # str (yes, even though it's a number!)

🧠 Bonus Tip:
You can combine type() with input() to see what kind of value you get from the
user:

python
value = input("Enter something: ")
print(type(value)) # Always str

Now you're officially a Data Type Detective

🧠 Lesson 6: Booleans (True/False Logic)


Booleans are the simplest data type in Python.
They answer one basic question: Is it true or false?

✅ What is a Boolean?
A Boolean only has two values:

True ✅

False ❌
(They must be capitalized!)
💡 Examples:

python
is_raining = True
is_summer = False

Here, is_raining is a variable that stores True (yes, it's raining)


is_summer is False (nope, it’s not summer)

🔍 Boolean in Real Life:

| Situation | Boolean |
| ------------------------ | ----------------- |
| Is the light on? | `True` or `False` |
| Are you in Class 9? | `True` |
| Do you hate tinde? | `True` |
| Did the top scorer fail? | `False` |

🧪 Try this in code:

python
likes_pizza = True
has_pet = False

print("Likes pizza:", likes_pizza)


print("Has a pet:", has_pet)

😂 Funny Note about Boolean and Toppers:


Sometimes, truth is stranger than fiction!
Imagine a topper scoring just 32% — that’s like saying:
Topper = True but Good Score = False!

Python would say:

python
topper_score_good = False
topper = True
print("Is the topper’s score good?", topper_score_good) # LOL, nope!

✅ Lesson 7: Booleans & If/Else


💡 What is a Boolean?
A Boolean is a data type that can have only two values:

True ✅

False ❌

They are used to make decisions in programs.

✅ Example of Boolean
python
is_sunny = True
is_raining = False

print(is_sunny) # Output: True


print(is_raining) # Output: False
🤔 Where are Booleans used?
In if/else conditions!
✅ If/Else Statement
This is used when your program needs to decide something.

📘 Syntax:
python
if condition:
# do this if condition is True
else:
# do this if condition is False
✅ Example
python
is_hungry = True

if is_hungry:
print("Let's eat something ")
else:
print("Okay, no food for now 🚫")
🧠 What happens here?
If is_hungry is True, it prints: "Let's eat something"

If is_hungry is False, it prints: "Okay, no food for now"

🔥 You can also use elif (else if):


python
mood = "bored"

if mood == "happy":
print("Yay! 😊")
elif mood == "sad":
print("Aww 💔")
else:
print("Hope your day gets better 💪")
✨ Summary:
Boolean → Only True or False

if → check a condition

else → do something when if is not true

elif → extra condition between if and else

Test fail

I wrote

Python

age = int(input("Enter your age: "))

if age <= 12:


print("You get a child ticket ") #condition 1
elif age <= 17:
print("You get a teen ticket ")
elif age <0 or age >100:
print("Invalid Age!")
else:
print("You get an adult ticket ")
but it will satify condition 1 if -5<=12

Right->

Python

age = int(input("Enter your age: "))

if age < 0 or age > 117:


print("Invalid Age! 🚫")
elif age <= 12:
print("You get a child ticket ")
elif age <= 19:
print("You get a teen ticket ")
else:
print("You get an adult ticket ")

🐍 Lesson 8: Comparison Operators


💡 What are they?
Comparison operators compare two values and give the result as either True or
False.

📊 List of Comparison Operators:


| Operator | Meaning | Example | Result |
| -------- | --------------------- | -------- | ------ |
| `==` | Equal to | `5 == 5` | `True` |
| `!=` | Not equal to | `4 != 5` | `True` |
| `>` | Greater than | `10 > 7` | `True` |
| `<` | Less than | `3 < 9` | `True` |
| `>=` | Greater than or equal | `5 >= 5` | `True` |
| `<=` | Less than or equal | `6 <= 9` | `True` |

✅ Code Example:

python

x = 10
y = 5

print(x > y) # True


print(x == y) # False
print(x != y) # True

🧠 Used in If Conditions:

python

marks = 75

if marks >= 33:


print("You passed! 🎉")
else:
print("You failed 💔")

⚠️ Common Mistake:
= → Assignment (e.g., x = 5)

== → Comparison (e.g., x == 5)
✨ Summary:
These operators compare values.

They return a Boolean (True or False).

Used in decision making with if, elif, else.

🐍Lesson 9: Logical Operators

🤔 What are Logical Operators?


They combine multiple conditions and return True or False depending on the logic.

💥 The 3 Logical Operators:


Operator Meaning Example Result
and True if both are True 5 > 3 and 10 > 2 True
or True if at least one
is True 5 > 8 or 10 > 2 True
not Reverses the condition not(5 > 3) False

✅ Examples:
python
age = 14

if age > 12 and age < 18:


print("You’re a teenager! 👦👧")

if age < 10 or age > 60:


print("You get a special ticket! 🎫")

sunny = False
if not sunny:
print("Take an umbrella! ☔")

🧠 Use in Real Life:


and = "I’ll go only if it's Sunday and my homework is done."

or = "I’ll go if it's Sunday or Saturday."

not = "I’ll not go if it’s raining."

🐍 Lesson 10: String Methods & the in Keyword


1. .lower()
✅ This changes all letters in a string to lowercase.

python
name = "Aradhya"
print(name.lower()) # Output: aradhya
Useful when comparing user input — like "YES", "yes", or "Yes" — we convert all to
lowercase to make comparison easier.

2. .capitalize()
✅ Makes only the first letter uppercase, and the rest lowercase.

python
food = "pIZza"
print(food.capitalize()) # Output: Pizza
Useful for neat display.

3. in keyword
✅ Checks if a value exists inside a list, string, or other collection.

python
day = "monday"
if day in ["monday", "tuesday", "wednesday"]:
print("It’s a weekday")

OR

python
if "a" in "Aradhya":
print("Yes, 'a' is in your name!")

✨ Practice Time:
Try this (you’ll love it 😄):

python
word = input("Type any word: ")
print("Lowercase:", word.lower())
print("Capitalized:", word.capitalize())

if "a" in word.lower():
print("It has the letter 'a' in it!")
else:
print("No 'a' found 😢")

Lesson 11: Lists in Python 🧺

🧠 What is a List?
A list is a collection of items in a specific order. You can store strings,
numbers, booleans, and even other lists inside one list.

🧪 Syntax:

python
my_list = ["apple", "banana", "cherry"]

✅ Features:
Lists are written in square brackets []

Items are separated by commas

You can access, modify, add, and remove items

🔹 Accessing Items

python
print(my_list[0]) # Output: apple
Indexing starts at 0

🔹 Changing Items

python
my_list[1] = "mango"

🔹 Adding Items

python
my_list.append("orange") # Adds to the end
🔹 Removing Items

python
my_list.remove("apple")

📌 Example:

python
fav_subjects = ["Math", "English", "History"]
print("My favorite subject is", fav_subjects[1])

You might also like