Ways to Format Strings When Printing in Python
Python offers multiple ways to format strings:
1. Using Commas in print()
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
2. Using str.format()
name = "Alice"
age = 25
print("Name: {} Age: {}".format(name, age))
print("Name: {0} Age: {1}".format(name, age))
3. Using f-Strings (Python 3.6+) — Most Recommended
name = "Alice"
age = 25
print(f"Name: {name} Age: {age}")
4. Using % Operator (Old Style)
name = "Alice"
age = 25
print("Name: %s Age: %d" % (name, age))
What are Variables in Python?
Variables are used to store data that can be used and manipulated throughout the program. In
Python, you don't need to declare a variable with its data type—Python figures it out at runtime.
x = 10 # integer
name = "John" # string
price = 99.99 # float
Variable Naming Rules in Python
1. Can contain letters (a-z, A-Z), digits (0–9), and underscores (_).
2. Must start with a letter or underscore, but not a digit.
o name, _value, a1
o 1value, @name
3. Case-sensitive – Name, name, and NAME are all different.
4. Should not use Python keywords as variable names (e.g., if, for, while, class, etc.).