Python from first program to best practices / Python basics
Your first Python program
Use input, output, variables, and functions to solve one small problem.
Estimated time: 25 minutes
Learning outcome
By the end of this lesson, you will write a small Python program that asks for your name, does a calculation, and prints a result — using input, output, variables, and a function.
Before you start
You need Python installed. Open a terminal (Command Prompt on Windows, Terminal on Mac) and type:
python --version
If you see Python 3.x.x, you are ready. If not, download Python from python.org and install it.
Your first line of code
Create a file called hello.py and write:
print("Hello, friend!")
Run it:
python hello.py
You should see Hello, friend! printed. Congratulations — you just wrote and ran a program.
Variables
A variable is a named box that holds a value. Think of it like a labelled jar:
name = "Alex"
age = 25
temperature = 36.5
is_learning = True
Python figures out the type automatically. You do not need to write String or int like in some other languages.
Input and output
Programs are more interesting when they respond to the person using them:
name = input("What is your name? ")
print("Nice to meet you,", name)
input() pauses and waits for the user to type something. print() displays text.
A worked example: temperature converter
Let us write a program that converts Fahrenheit to Celsius:
# Ask for the temperature in Fahrenheit
fahrenheit = input("Enter temperature in Fahrenheit: ")
# Convert to a number and do the math
f = float(fahrenheit)
celsius = (f - 32) * 5 / 9
# Show the result
print(fahrenheit, "F is", round(celsius, 1), "C")
Try it with 98.6 — the answer should be 37.0 C.
Functions
A function is a reusable chunk of code. You give it a name and some inputs, and it returns a result:
def greet(name):
return "Hello, " + name + "!"
message = greet("Sam")
print(message)
The def keyword defines a function. return sends a value back. Everything indented under def belongs to the function.
Common beginner mistakes
- Forgetting the colon after
defandiflines. Python uses:to know a block is coming. - Mixing tabs and spaces. Python relies on indentation to know where blocks start and end. Use 4 spaces consistently.
- Forgetting to convert input.
input()always returns a string. If you need a number, you must convert it withint()orfloat().
Practice task
Write a program that:
- Asks for your name
- Asks for your favourite number
- Prints "Hello, [name]! Your number doubled is [number * 2]."
Recap
print()displays output.input()reads keyboard input.- Variables store values. Python infers the type.
- Functions group reusable code with
def. - Convert input strings to numbers with
int()orfloat()before math.
Next step
Now that you can write a working program, the next lesson teaches you how to make your code readable, testable, and safe from common errors.