Think of a variable as a labeled box where you store a piece of data. You give the box a name (the label), and Python remembers what's inside. Whenever you need that data, you just refer to the label.
In Python, creating a variable is as simple as picking a name and using the assignment operator =:
name = "Alice" # String variable
age = 15 # Integer variable
height = 1.68 # Float variable
is_student = True # Boolean variable
The = sign doesn't mean "equals" like in math. It means "assign the value on the right to the name on the left". Read it as: "name gets the value 'Alice'".
favourite_game and assign it a string value of your favourite computer game. Then create a variable hours_played and assign it an integer (how many hours you've played it).price and assign it the float value 29.99. Then create a variable is_on_sale and assign it False.Every value in Python has a type. Python has four fundamental data types that you'll use all the time:
str)Strings hold text. They're created by wrapping characters in quotes β either single ' ' or double " ".
greeting = "Hello, World!"
name = 'Alice'
empty_string = ""
"it's"), using double quotes on the outside avoids errors.
int)Integers are whole numbers β positive, negative, or zero. No decimal point allowed!
score = 95
temperature = -3
population = 8_000_000_000 # Underscores make large numbers readable!
_ to separate groups of digits in large numbers. Python ignores them: 1_000_000 is the same as 1000000.
float)Floats represent decimal numbers. Use them when you need precision, like measurements or money.
pi = 3.14159
gpa = 3.75
price = 19.99
temperature = 36.6
bool)Booleans have only two possible values: True or False. They're perfect for yes/no questions.
is_raining = True
has_passed = False
is_enrolled = True
Note: In Python, True and False must be capitalized!
str, int, float, bool. Use meaningful names and values related to a school subject you enjoy.true (lowercase) instead of True? Try it mentally β would Python understand it?type()Python provides a built-in function called type() that tells you the data type of any value. This is extremely useful when you're debugging or unsure what type a variable holds:
name = "Alice"
age = 15
gpa = 3.8
passed = True
print(type(name)) #
print(type(age)) #
print(type(gpa)) #
print(type(passed)) #
type() as a scanner β hold it up to any value and it prints a label saying what kind of data it is, like scanning a barcode at the supermarket.
type("42") return? (Think carefully β the quotes make a difference!)type(3.0) return? Is 3.0 an integer or a float?Python has strict rules about what makes a valid variable name. Follow these to avoid errors:
These words have special meanings in Python and can't be used as variable names:
and as assert break class continue def
del elif else except finally for from
global if import in is lambda not
or pass raise return try while with
yield
Python programmers follow a naming convention called snake_case β all lowercase letters with underscores between words:
student_name # β
Good: clear and readable
age_of_student # β
Good: descriptive
total_score # β
Good: follows convention
a # β Too vague β what does it mean?
x1y2 # β Meaningless β no context
studentName # β οΈ camelCase β JavaScript style, not Python!
temperature_in_celsius is better than t or temp.
2fast, fast_2, my-name, my_name, class, Class, _private, total$m, StudentGrade, numberofstudentsinclassUnlike many other programming languages, Python is dynamically typed. This means:
x = 10 # x is an integer
print(type(x)) #
x = "Hello" # Now x is a string!
print(type(x)) #
x = 3.14 # Now x is a float!
print(type(x)) #
value = 100
print(type(value))
value = "one hundred"
print(type(value))
value = 100.0
print(type(value)) Explain what happens at each step.Sometimes you need to convert a value from one type to another. Python provides built-in functions for this:
# Convert to string
age = 15
message = "You are " + str(age) + " years old"
print(message) # You are 15 years old
# Convert to integer
price_str = "29"
price_int = int(price_str)
print(price_int + 1) # 30
# Convert to float
whole = 10
decimal = float(whole)
print(decimal) # 10.0
# Boolean conversion
print(bool(1)) # True (any non-zero number is True)
print(bool(0)) # False (zero is False)
print(bool("")) # False (empty string is False)
print(bool("Hi")) # True (non-empty string is True)
int("hello") will cause an error β Python can't turn the word "hello" into a number!
"3.14159" to a float, then multiplies it by 2, and prints the result.int("3.9")? Will it round up to 4, cause an error, or truncate to 3?99 to a string, then concatenate it with " percent" and print the result.type() to check any value's typeIn Python, a string is a sequence of characters enclosed in quotes. Strings are everywhere in programming β names, messages, passwords, file paths, and even the HTML code of websites.
"Hello" = H-e-l-l-o beads on a string!
Python treats both identically. The key is consistency β pick one style and stick with it!
# Single quotes
name = 'Alice'
greeting = 'Hello, World!'
# Double quotes
name = "Alice"
greeting = "Hello, World!"
# Choosing quotes to avoid escaping:
sentence1 = "It's a beautiful day" # β
Double quotes = no escape needed for '
sentence2 = 'He said "Python is fun"' # β
Single quotes = no escape needed for "
For strings that span multiple lines, use triple quotes (''' or """):
poem = '''Roses are red,
Violets are blue,
Python is awesome,
And so are you!'''
print(poem)
# Output:
# Roses are red,
# Violets are blue,
# Python is awesome,
# And so are you!
favourite_quote that holds a famous quote containing an apostrophe (like "Python's readability is its strength"). Choose your quotes wisely to avoid escaping!+The + operator joins strings together. This is called concatenation:
first = "Python"
second = "Rocks"
result = first + " " + second
print(result) # Python Rocks
# Concatenating multiple strings
full_name = "Alice" + " " + "Smith"
print(full_name) # Alice Smith
"Age: " + 15 causes an error. Use str(15) to convert first: "Age: " + str(15).
*The * operator repeats a string a given number of times:
print("Ha" * 3) # HaHaHa
print("-" * 20) # --------------------
print("π" * 5) # πππππ
# Great for creating visual separators!
separator = "=" * 30
print(separator)
print("WELCOME TO PYTHON")
print(separator)
email variable by concatenating "alice", "@", "example", ".", and "com". Print the result.* and " " creatively):
*
**
***
****
*****
Hint: You'll need a separate print for each line.Python strings come with many built-in methods that let you manipulate text. Here are the most important ones for beginners:
text = " Hello, Python! "
print(text.upper()) # " HELLO, PYTHON! "
print(text.lower()) # " hello, python! "
print(text.strip()) # "Hello, Python!"
print(len(text)) # 19 (counts ALL characters including spaces)
print(text.replace("Python", "World")) # " Hello, World! "
print(text.find("Python")) # 8 (starts at index 8)
print(text.count("o")) # 3 ('o' appears 3 times)
print("python".capitalize()) # "Python"
You can chain multiple methods together β each operates on the result of the previous one:
message = " Hello, World! "
print(message.strip().upper()) # "HELLO, WORLD!"
print(message.strip().replace("World", "Python").upper()) # "HELLO, PYTHON!"
username = " Captain Python ". Use method chaining to produce "CAPTAIN PYTHON" (all caps, no spaces).sentence = "The quick brown fox jumps over the lazy dog", find:
.find()
.count()
len()f-strings (formatted string literals) are the cleanest way to insert variables into text. Just put an f before the opening quote and use {} as placeholders:
name = "Bob"
age = 16
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Bob and I am 16 years old.
{} are the blank spaces, and Python fills them in with the variable values. The f prefix says "this string has blanks to fill!"
{}You can put any Python expression inside the curly braces, not just variable names:
a = 10
b = 20
print(f"{a} + {b} = {a + b}")
# Output: 10 + 20 = 30
print(f"Temperature: {36.6}Β°C")
# Output: Temperature: 36.6Β°C
score = 85
print(f"You scored {score}% β {'Pass' if score >= 50 else 'Fail'}")
# Output: You scored 85% β Pass
You can control how numbers are displayed:
pi = 3.1415926535
print(f"Pi to 2 decimals: {pi:.2f}") # Pi to 2 decimals: 3.14
print(f"Pi to 4 decimals: {pi:.4f}") # Pi to 4 decimals: 3.1416
big_number = 1000000
print(f"Formatted: {big_number:,}") # Formatted: 1,000,000
percentage = 0.875
print(f"Percentage: {percentage:.1%}") # Percentage: 87.5%
subject = "Computer Science" and grade = "A". Use an f-string to print: "I got an A in Computer Science!"print() Function β Beyond the BasicsThe print() function is your window to the outside world β it sends text to the console. Let's explore its hidden powers:
You can pass multiple values separated by commas. print() automatically adds a space between them:
print("Apple", "Banana", "Cherry")
# Output: Apple Banana Cherry
print(1, 2, 3, "Go!")
# Output: 1 2 3 Go!
sep)The sep parameter changes what goes between items:
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry
print("10", "20", "30", sep=" | ")
# Output: 10 | 20 | 30
print("hello", "world", sep="")
# Output: helloworld (no space at all!)
end)By default, print() ends with a newline (\n). You can change this with end:
print("Hello", end=" ")
print("World")
# Output: Hello World (both on the same line!)
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")
# Output: Loading....
sep and endprint("a", "b", "c", sep=" - ", end="!!!\n")
# Output: a - b - c!!!
sep="" and end="" together to build output piece by piece β perfect for progress indicators, ASCII art, and formatting tables.
print() with custom sep to display a CSV-like row: Alice,15,Computer Science,Aprint() with end to print the numbers 1 through 5 all on the same line, separated by spaces. Output should look like: 1 2 3 4 5Escape sequences let you include special characters inside strings. They start with a backslash \ followed by a character code:
# New line
print("Line 1\nLine 2\nLine 3")
# Output:
# Line 1
# Line 2
# Line 3
# Tab for alignment
print("Name\tAge\tGrade")
print("Alice\t15\tA")
print("Bob\t16\tB")
# Output:
# Name Age Grade
# Alice 15 A
# Bob 16 B
# Including quotes inside strings
print("She said, \"Python is amazing!\"")
# Output: She said, "Python is amazing!"
# Backslash in file paths
path = "C:\\Users\\Student\\Documents"
print(path)
# Output: C:\Users\Student\Documents
\ as a "magic switch" β it tells Python: "The next character doesn't mean what it normally means!" \n isn't a backslash and an 'n' β it's the "newline magic spell."
*
***
*****
Use escape characters (\n and maybe \t) to create the pattern β all in ONE print statement.Name, Score, Result and two rows of data (Alice: 85/Pass, Bob: 42/Fail). Use tabs (\t) to align the columns neatly.+) and repeat (*) strings=type() to check a value's type+) and repeat (*) strings