Python Basics: A Beginner's Guide to Writing Your First Programs
What is Python?
Python is a general-purpose, interpreted programming language known for readable syntax that uses indentation to mark blocks of code. You write instructions in plain-text .py files or type them into an interactive prompt, and the Python interpreter runs them line by line. It is used for automation, web back ends, data analysis, scripting and teaching programming fundamentals.
Key Python terms: interpreter, script, REPL and dynamic typing
- Interpreter: the program, usually called
pythonorpython3, that reads your code and runs it. - Script: a file ending in
.pythat you run from a terminal withpython3 hello.py. - REPL (Read-Eval-Print Loop): the interactive prompt you get by running
python3with no file. It evaluates each line straight away, which makes it ideal for quick experiments. - Dynamic typing: you never declare a type. A variable is just a name that refers to a value, and the value carries its own type.
$ python3
>>> 2 + 3
5
>>> name = "Asha"
>>> f"Hello, {name}"
'Hello, Asha'
>>> exit()The >>> prompt shows that the REPL is waiting for input. The same ideas appear in every language: our guide to PHP and the JavaScript beginner guide cover variables and functions with a different syntax.
How Python stores data: variables, core types and collections
You create a variable by assigning to it with =. Python has a small set of built-in types you will use constantly, and the type() function tells you which one a value has.
count = 10 # int: whole number
price = 249.50 # float: decimal number
city = "Pune" # str: text
is_member = True # bool: True or False
discount = None # None: "no value yet"
print(type(price)) # <class 'float'>
count = "ten" # allowed: the name now refers to a strTwo collections cover most beginner needs. A list is an ordered sequence you can change, and a dict maps keys to values. Both are explained in depth in our data structures guide.
marks = [72, 88, 95]
marks.append(64)
print(marks[0], len(marks)) # 72 4
student = {"name": "Ravi", "marks": 88}
student["city"] = "Indore"
print(f"{student['name']} from {student['city']} scored {student['marks']}")
print(f"Average: {sum(marks) / len(marks):.2f}") # Average: 79.75An f-string is a string prefixed with f; anything inside braces is evaluated and inserted. The :.2f part formats a number to two decimal places. Lines starting with # are comments, which Python ignores.
Making decisions and repeating work: if, for and while
Python marks a block with a colon followed by indented lines, conventionally four spaces. There are no braces: the indentation is the structure, so inconsistent indentation causes an IndentationError.
score = 78
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"
print(grade) # B
for mark in [72, 88, 95]:
print(mark)
for i in range(1, 6): # 1, 2, 3, 4, 5 (the end is excluded)
print(i * i)
attempts = 0
while attempts < 3:
attempts += 1
print("Attempt", attempts)Use for when you are looping over a known collection or range, and while when you keep going until a condition changes. range(start, stop) stops one before stop, which is a frequent source of off-by-one errors.
Functions, user input and modules
A function packages steps under a name. You define it with def, give it parameters, and send a result back with return. A function without a return statement returns None.
import math
def average(numbers):
"""Return the mean of a non-empty list of numbers."""
return sum(numbers) / len(numbers)
def greet(name, greeting="Namaste"):
return f"{greeting}, {name}!"
print(average([72, 88, 95])) # 85.0
print(greet("Meera")) # Namaste, Meera!
print(math.sqrt(16)) # 4.0
age = int(input("Your age: "))
print(f"Next year you will be {age + 1}")input() always returns a string, so convert it with int() or float() before doing arithmetic. A module is any .py file; import math loads one from the standard library. Third-party packages are installed with pip, as shown below.
Setting up Python step by step: install, venv and pip
- Download a current Python 3 release from python.org. On Windows the
pylauncher is installed with it; on macOS and Linux you can also use your package manager. - Open a terminal and check the version with
python3 --version(orpy --versionon Windows). - Create a project folder and, inside it, a virtual environment with
python3 -m venv .venv. This keeps the project's packages separate from every other project. - Activate it:
source .venv/bin/activateon macOS and Linux, or.venv\Scripts\activateon Windows. Your prompt shows(.venv)when it is active. - Install packages with
pip install requests, then record them withpip freeze > requirements.txtso anyone can recreate the setup withpip install -r requirements.txt. - Write your code in a file such as
main.pyusing an editor with Python support, and run it withpython main.pywhile the environment is active.
Habits that keep Python code readable
| Habit | Why it helps |
|---|---|
| Four spaces per indent level, never mixed with tabs | Avoids indentation errors and matches the PEP 8 style guide |
| snake_case names such as total_price | The standard convention for variables and functions |
| Small functions that do one job | Easier to test, reuse and debug |
| Docstrings on functions | Explains intent; editors show them as help text |
| An if __name__ == "__main__": guard | Lets a file be imported without running its main code |
When a program misbehaves, read the traceback from the bottom up: the last line names the error and the lines above show where it happened. Our guide to debugging code walks through this in detail.
Practical exercise: build a tip calculator
Save this as tip.py, run it with python tip.py, and then extend it.
def calculate_tip(bill, percent, people):
tip = bill * percent / 100
total = bill + tip
return tip, total, total / people
def main():
bill = float(input("Bill amount (Rs): "))
percent = float(input("Tip percentage: "))
people = int(input("Number of people: "))
tip, total, share = calculate_tip(bill, percent, people)
print(f"Tip: Rs {tip:.2f}")
print(f"Total: Rs {total:.2f}")
print(f"Each person pays: Rs {share:.2f}")
if __name__ == "__main__":
main()- Done looks like this: entering 1200, 10 and 4 prints a tip of Rs 120.00, a total of Rs 1320.00 and Rs 330.00 per person.
- Extension one: wrap the input in a
whileloop withtryandexcept ValueErrorso typing letters asks again instead of crashing. - Extension two: reject zero people, which would otherwise raise
ZeroDivisionError. - Extension three: turn it into a grade calculator that reads five marks into a list and prints the average and an if/elif grade.
Once this feels comfortable, move on to classes and objects in Python. SkillNewton has no Python course, but the PHP Foundation course teaches the same programming fundamentals in PHP.
Common mistakes
- Mixing tabs and spaces for indentation, which leads to confusing
IndentationErrororTabErrormessages. - Doing arithmetic on the result of
input()without converting it, so"5" + 1raises aTypeError. - Using
=(assignment) where==(comparison) was meant inside anifcondition. - Installing packages globally instead of in a virtual environment, so projects end up needing conflicting versions.
- Naming your own file after a module you import, such as
random.py, which hides the standard library module.
Frequently asked questions
Should I learn Python 2 or Python 3?
Python 3. Python 2 reached end of life in January 2020 and no longer receives fixes. Every current tutorial, library and tool targets Python 3.
Is Python compiled or interpreted?
The standard implementation, CPython, compiles your source to bytecode and then runs that bytecode in its virtual machine. You never run a separate compile step yourself, so in everyday use it behaves like an interpreted language.
Do I need to learn Python before other languages?
No. The core ideas of variables, conditions, loops and functions carry over to any language. If you already know JavaScript, Python will feel familiar apart from its indentation rules.
What should I learn after Python basics?
Object-oriented programming, then the common data structures and algorithms and Big O notation. Together these let you write programs that are organised and efficient.