When you decide to learn programming, you run into an immediate wall of jargon: compilers, memory allocation, object-oriented paradigms, and low-level system design. It is enough to make anyone close their laptop and walk away.
This is where Python changes things. Python was designed around a simple philosophy: readability counts. The syntax reads surprisingly close to plain English, letting you focus on learning how to solve problems with logic rather than wrestling with obscure symbols.
If you are just getting started, or if you already know another language and want to pick up Python without the fluff, this guide covers the core foundation you will use every day.
Why Python Syntax Feels Different
Python strips away the visual noise common in other programming languages like C++ and Java. It uses indentation (whitespace) to determine how code blocks are structured, and new lines signify the end of a statement.
Here is the classic starting point in Python:
print("Hello, World!")
That is the entire program. The print() function takes whatever data you pass inside its parentheses and displays it on your terminal screen.
Indentation Matters!
Because Python does not rely on braces to group code, spacing is not optional aesthetic formatting. Spacing is an executable part of the language.
Standard convention is to use four spaces per indentation level. Avoid mixing tabs and spaces in the same file, as Python will raise an IndentationError if the spacing is inconsistent.
Storing Data: Variables and Dynamic Typing
Programs are essentially engines that take data, transform it, and display a result. To work with data, you need a way to label and store it temporarily in your computer's memory. That is what a variable is: a named label pointing to a value.
In Python, you do not declare a variable type in advance. You simply write the variable name, use the assignment operator (=), and provide the value.
user_name = "Navas"
user_age = 28
account_balance = 200145.50
is_active = True
This behavior is called dynamic typing. Python inspects the value on the right side of the equals sign at runtime and assigns the appropriate data type automatically.
Naming Conventions
Python developers follow a style guide known as PEP 8. For variable names, the standard convention is snake_case: lowercase letters with words separated by underscores.
- Good:
total_score,first_name,max_limit - Avoid:
TotalScore,firstName,x(unlessxis a standard math variable)
Core Data Types You Will Use Daily
Everything stored in a Python variable has a type. Let us walk through the four primitive types you will interact with constantly.
1. Integers (int)
Integers represent whole numbers, positive or negative, without a decimal point.
items_in_cart = 5
temperature_change = -3
2. Floating-Point Numbers (float)
Floats represent real numbers that include a fractional part using a decimal point.
tax_rate = 0.08
item_price = 19.99
Keep in mind that computers handle floating-point arithmetic using binary approximations. If you calculate 0.1 + 0.2, you might occasionally see 0.30000000000000004 rather than an exact 0.3. For everyday scripts, this rarely causes issues, but for financial applications, Python provides a dedicated decimal module to avoid precision rounding errors.
3. Strings (str)
Strings are sequences of characters used to store text. You define them using single quotes '...' or double quotes "...".
greeting = "Welcome back!"
file_path = 'documents/notes.txt'
Both styles work identically. The common convention is to pick one style and stay consistent throughout your script, switching only when you need quotes inside the string itself (for example: "Don't forget your keys").
4. Booleans (bool)
Booleans represent binary truth values: either True or False. Notice that both start with a capital letter in Python.
logged_in = True
has_permission = False
These become essential later when you write conditional statements (if / else) to control the flow of your program based on real-time conditions.
Taking Input and Displaying Output
A program becomes truly useful when it interacts with the person using it. You have already seen print() for output. To capture data from someone using the program, Python provides the built-in input() function.
Here is how input and output work together:
name = input("What is your name? ")
print("Nice to meet you, " + name + "!")
When Python encounters input(), it pauses execution and waits for the user to type something into the console and press Enter.
The Input Type Trap
There is one critical behavior every beginner runs into with input(): it always returns user input as a string (str), even if the user enters digits.
Consider this snippet:
age = input("Enter your age: ")
next_year = age + 1 # This will trigger a TypeError!
If you enter 25, Python does not see the number 25. It sees the string "25". Trying to add an integer to a text string causes Python to throw an error: TypeError: can only concatenate str (not "int") to str.
To fix this, convert the string into a numeric type using type casting:
age = input("Enter your age: ")
age_number = int(age)
next_year = age_number + 1
print(f"Next year you will be {next_year} years old.")
The int() function converts valid text digits into an actual integer. If you expect numbers with decimal points, use float() instead.
Formatting Strings with f-Strings
In older Python tutorials, you will see string concatenation with plus signs ("Hello " + name) or the .format() method. Modern Python (version 3.6 and newer) uses f-strings (formatted string literals).
Prefix your string with the letter f, and you can place any variable or expression directly inside curly brackets {}:
product = "Mechanical Keyboard"
price = 5000
quantity = 2
print(f"Purchased {quantity} x {product} for a total of Ksh. {price * quantity:.2f}")
Notice the :.2f inside the brackets. That is a format specifier that rounds the calculated floating-point total to two decimal places. It is clean, readable, and saves you from converting values manually just to print them.
A Working Example: Tip Calculator
Let us combine variables, arithmetic operators, user input, type casting, and f-strings into a practical terminal tool.
# Simple Bill & Tip Calculator
print("=== Bill Splitter ===")
# Gather input
total_bill_str = input("Enter the total bill amount: Ksh. ")
tip_percentage_str = input("Enter tip percentage (e.g., 15, 18, 20): ")
people_count_str = input("How many people are splitting the bill? ")
# Convert input strings to appropriate numerical types
bill = float(total_bill_str)
tip_percent = float(tip_percentage_str)
people = int(people_count_str)
# Perform the calculations
tip_amount = bill * (tip_percent / 100)
final_total = bill + tip_amount
cost_per_person = final_total / people
# Display the results
print("\n--- Summary ---")
print(f"Total tip: Ksh. {tip_amount:.2f}")
print(f"Final bill: Ksh. {final_total:.2f}")
print(f"Each person pays: Ksh. {cost_per_person:.2f}")
If you run this code, you have built a complete, interactive utility using nothing more than basic variables, type conversion, and standard input/output.
Three Mistakes to Watch Out For
-
Forgetting that variable names are case-sensitive.
score,Score, andSCOREare three distinct variables in Python. If you create a variable nameduser_inputand later try to printUser_input, Python will stop and report aNameError. -
Confusing
=with==. A single equals sign (=) assigns a value to a variable. A double equals sign (==) compares two values to see if they are equal. -
Leaving out type conversion after
input(). If you plan on doing any math with user-provided information, cast it toint()orfloat()immediately.
Key Takeaways
- Python prioritizes clean, readable syntax and uses indentation rather than curly braces to define scope.
- Variables do not require explicit type definitions; Python handles typing dynamically at assignment.
- The core primitive types are integers (
int), floating-point numbers (float), strings (str), and booleans (bool). -
input()always captures text as a string; useint()orfloat()when you need numbers. - Formatted string literals (
f"...") are the cleanest and most efficient way to embed variables inside strings.
My Take
Writing code is less about memorizing syntax rules and more about building a habit of breaking problems into small, logical steps. With variables, types, and input/output under your belt, you have the groundwork needed to start exploring decision logic, loops, and custom functions. Fire up a terminal, experiment with the tip calculator, tweak the formulas, and see what happens. And don't forget to practice, practice, practice and practice!
Top comments (0)