Python Core Concepts

Back

Loading concept...

🐍 Python Core Concepts: Your Journey Begins!

Imagine Python as your friendly robot assistant. You give it simple instructions, and it does exactly what you ask. Just like teaching a pet new tricks, you’ll teach Python to do amazing things!


🌟 Python Basics: Meeting Your New Friend

Think of Python like a super-smart calculator that can also talk, remember things, and make decisions!

What is Python?

Python is a language that computers understand. Just like you speak English to talk to friends, you write Python to talk to computers.

Why is it called Python? 🐍 Not because of the snake! The creator loved a comedy show called β€œMonty Python’s Flying Circus”!

Your First Python Command

print("Hello, World!")

What happens? The computer shows: Hello, World!

It’s like telling your robot friend: β€œSay hello to everyone!”


πŸ“¦ Variables and Data Types: Labeled Boxes

What are Variables?

Imagine you have labeled boxes in your room:

  • πŸ“¦ Box labeled β€œage” β†’ holds the number 10
  • πŸ“¦ Box labeled β€œname” β†’ holds β€œAlex”
  • πŸ“¦ Box labeled β€œis_happy” β†’ holds True or False

Variables are just named containers that store information!

age = 10
name = "Alex"
is_happy = True

Data Types: What Goes in the Boxes?

Type What It Holds Example
int Whole numbers 42, -5, 0
float Decimal numbers 3.14, -0.5
str Text (strings) "Hello", 'Python'
bool True or False True, False
my_age = 25          # int (integer)
my_height = 5.8      # float (decimal)
my_name = "Sam"      # str (string)
is_student = True    # bool (boolean)

Quick Tip:

  • Use quotes " " or ' ' for text
  • No quotes for numbers

βž• Python Operators: The Action Heroes

Operators are like magic wands that make things happen!

Arithmetic Operators (Math Magic)

Operator What It Does Example Result
+ Adds 5 + 3 8
- Subtracts 10 - 4 6
* Multiplies 3 * 4 12
/ Divides 15 / 3 5.0
// Floor divide 17 // 5 3
% Remainder 17 % 5 2
** Power 2 ** 3 8
cookies = 10
friends = 3
each_gets = cookies // friends  # 3
leftover = cookies % friends     # 1

Comparison Operators (True or False?)

Operator Meaning Example
== Equal to 5 == 5 β†’ True
!= Not equal 5 != 3 β†’ True
< Less than 3 < 5 β†’ True
> Greater than 5 > 3 β†’ True
<= Less or equal 5 <= 5 β†’ True
>= Greater or equal 6 >= 5 β†’ True

Logical Operators (Combining Conditions)

Operator Meaning Example
and Both must be True True and True β†’ True
or One must be True True or False β†’ True
not Flips the value not True β†’ False

πŸ“ Strings in Python: Playing with Text

Strings are like beads on a necklace – each letter is one bead!

Creating Strings

greeting = "Hello"
name = 'Python'
message = """This is a
multi-line string!"""

String Superpowers

word = "Python"

# Length (how many letters?)
len(word)          # 6

# Grab one letter (counting from 0!)
word[0]            # 'P'
word[-1]           # 'n' (last letter)

# Slice (grab a piece)
word[0:3]          # 'Pyt'

String Methods (Special Tricks)

text = "hello world"

text.upper()       # "HELLO WORLD"
text.lower()       # "hello world"
text.title()       # "Hello World"
text.replace("hello", "hi")  # "hi world"
text.split(" ")    # ["hello", "world"]

Joining Strings Together

first = "Hello"
second = "World"

# Using +
result = first + " " + second  # "Hello World"

# Using f-strings (the cool way!)
name = "Alex"
age = 10
intro = f"I'm {name}, age {age}"
# "I'm Alex, age 10"

πŸ“‹ Lists and Tuples: Collections of Things

Lists: The Shopping Basket πŸ›’

A list is like a shopping basket – you can add, remove, and change items!

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

List Actions:

fruits = ["apple", "banana"]

# Add to end
fruits.append("cherry")
# ["apple", "banana", "cherry"]

# Remove item
fruits.remove("banana")
# ["apple", "cherry"]

# Access by position (starts at 0!)
fruits[0]    # "apple"
fruits[-1]   # "cherry" (last one)

# Change an item
fruits[0] = "mango"
# ["mango", "cherry"]

# How many items?
len(fruits)  # 2

Tuples: The Sealed Box πŸ“¦πŸ”’

A tuple is like a sealed box – once packed, you can’t change what’s inside!

coordinates = (10, 20)
colors = ("red", "green", "blue")

# Access works the same
colors[0]    # "red"
colors[-1]   # "blue"

# But you CAN'T change them!
# colors[0] = "yellow"  ← ERROR!

Why use tuples? When you want data to stay safe and unchanged!

graph TD A["Collections"] --> B["List"] A --> C["Tuple"] B --> D["βœ… Can change&lt;br/&gt;βœ… Can add/remove&lt;br/&gt;πŸ“ Use [ ]"] C --> E["πŸ”’ Cannot change&lt;br/&gt;❌ Fixed size&lt;br/&gt;πŸ“ Use &#35;40; &#35;41;"]

πŸ“š Dictionaries and Sets: Smart Storage

Dictionaries: The Contact Book πŸ“‡

A dictionary stores pairs: a name (key) and its information (value).

student = {
    "name": "Alex",
    "age": 10,
    "grade": "5th"
}

# Get a value using its key
student["name"]      # "Alex"
student["age"]       # 10

# Add new pair
student["school"] = "Sunny Elementary"

# Change a value
student["age"] = 11

# Remove a pair
del student["grade"]

Dictionary Methods:

person = {"name": "Sam", "age": 25}

person.keys()    # ["name", "age"]
person.values()  # ["Sam", 25]
person.items()   # [("name","Sam"), ("age",25)]
person.get("name")  # "Sam"

Sets: The Unique Collection 🎯

A set only keeps unique items – no duplicates allowed!

colors = {"red", "blue", "green"}
numbers = {1, 2, 2, 3, 3, 3}  # becomes {1, 2, 3}

# Add item
colors.add("yellow")

# Remove item
colors.remove("red")

# Check if exists
"blue" in colors  # True

Set Magic: Finding Common Things

set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

set_a & set_b   # {3, 4} - in both
set_a | set_b   # {1,2,3,4,5,6} - all unique
set_a - set_b   # {1, 2} - only in A

🚦 Conditional Statements: Making Decisions

Conditionals are like traffic lights – they tell Python which way to go!

The IF Statement

age = 10

if age >= 18:
    print("You can vote!")
else:
    print("You're too young to vote")

Adding More Options: elif

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Your grade: {grade}")  # "Your grade: B"

Flow Diagram:

graph TD A["Start"] --> B{score >= 90?} B -->|Yes| C["grade = A"] B -->|No| D{score >= 80?} D -->|Yes| E["grade = B"] D -->|No| F{score >= 70?} F -->|Yes| G["grade = C"] F -->|No| H["grade = F"]

Combining Conditions

age = 15
has_ticket = True

if age >= 12 and has_ticket:
    print("Enjoy the movie!")
elif age < 12 and has_ticket:
    print("Need parent with you")
else:
    print("Please buy a ticket")

πŸ”„ Loops in Python: Repeat, Repeat, Repeat!

Loops are like a music player on repeat – they do the same thing over and over!

FOR Loop: When You Know How Many Times

# Print numbers 1 to 5
for i in range(1, 6):
    print(i)
# Output: 1, 2, 3, 4, 5

# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I love {fruit}!")

WHILE Loop: Until Something Changes

count = 0
while count < 5:
    print(count)
    count = count + 1
# Output: 0, 1, 2, 3, 4

⚠️ Warning: Always make sure the loop can end, or it runs forever!

Loop Controls

Command What It Does
break Exit the loop immediately
continue Skip to next iteration
# Find first even number
for num in [1, 3, 4, 7, 8]:
    if num % 2 == 0:
        print(f"Found: {num}")
        break
# Output: Found: 4

# Skip odd numbers
for num in range(1, 6):
    if num % 2 != 0:
        continue
    print(num)
# Output: 2, 4

Nested Loops (Loop Inside Loop)

# Multiplication table (1-3)
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
...

🎯 Quick Summary: Your Python Toolkit

Concept Think of it as… Key Symbol
Variables Labeled boxes =
Strings Text in quotes " " or ' '
Lists Shopping basket [ ]
Tuples Sealed box ( )
Dictionaries Contact book { key: value }
Sets Unique collection { }
If/Else Traffic light if: elif: else:
For Loop Counting repeat for x in range():
While Loop Until done while condition:

🌈 You Did It!

You’ve just learned the building blocks of Python! Remember:

  • Variables store things
  • Strings handle text
  • Lists and Tuples collect items
  • Dictionaries pair keys with values
  • If/Else makes decisions
  • Loops repeat actions

Now go practice and build something amazing! πŸš€

β€œThe best way to learn Python is by writing Python!”

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.