Running Your First Python Code
Python uses indentation to mark code blocks and short keywords for common operations. In the first examples, you can identify assignments, function calls, and conditions before learning every part of the syntax.
The same language is used in web development, data analysis, machine learning, and artificial intelligence. The first example is a small program that prints text.
When you need to check syntax or find a function in the standard library, open the official Python documentation. Choose the same Python version that you are running so the examples and feature list match your program.
Hello World Program
A common first program displays the text "Hello World!". Running it confirms that Python can execute a file and gives you a small, complete program to inspect.
print("Hello World!")The built-in print() function writes the value inside its parentheses to the output.
Three Ways to Run Python Programs
Python code can be run in three common ways. The interactive prompt is best for trying one expression at a time, a saved script file is best for a program you run again, and a notebook is best for mixing code with written notes.
Interactive Mode
Interactive mode runs Python statements directly in the terminal. Use it to check a short expression or inspect a value without creating a file.
Here's how to use interactive mode. First open a terminal or command prompt, then type python or python3 and press Enter. You'll see the >>> prompt indicating Python is ready to receive commands. Next, write Python code and press Enter to execute it.
$ python3
>>> print("Hello World!")
Hello World!
>>> 2 + 3
5
>>> name = "Alice"
>>> print(f"Hello, {name}!")
Hello, Alice!
>>>Script Mode
Script mode is a way to run saved Python files. This is suitable for more complex programs or programs you want to save for repeated use.
To run a script, create a file with the .py extension in a text editor, write the Python code, and save the file. Then open a terminal, go to the folder that contains the file, and run python3 filename.py.
# Simple program to greet users
name = input("What's your name? ")
age = input("How old are you? ")
print(f"Hello {name}!")
print(f"You are {age} years old.")
print("Happy learning Python!")To run the file above:
$ python3 greeting.py
What's your name? John
How old are you? 20
Hello John!
You are 20 years old.
Happy learning Python!Jupyter Lab and Notebooks
Jupyter is an interactive environment often used for data science and teaching. A notebook combines executable code, its output, and written explanation in one document.
Each cell can run independently, and its output appears directly below it. Because code, results, explanatory text, images, and graphs stay in one document, a notebook can record each step of an experiment or data analysis.
Cells share state in the same kernel. After restarting the kernel, run the cells from top to bottom: a cell using math or a function depends on the cell that defined that name.
Install JupyterLab in a dedicated Python environment so its packages do not interfere with unrelated projects:
These commands use macOS/Linux paths. On Windows, use py -m venv .venv, then .venv\Scripts\python -m pip install jupyterlab and .venv\Scripts\jupyter lab.
# Install JupyterLab with the selected Python interpreter
python3 -m venv .venv
.venv/bin/python -m pip install jupyterlabSecond, run Jupyter Lab:
# Run Jupyter Lab
.venv/bin/jupyter lab
# Will open browser with Jupyter interfaceThird, create a new notebook with .ipynb extension and write code in cells, then press Shift+Enter to execute.
Example usage in Jupyter:
# Cell 1: Import and setup
import math
# Cell 2: Variables and operations
radius = 5
area = math.pi * radius ** 2
print(f"Circle area with radius {radius} is {area:.2f}")
# Cell 3: Create function
def calculate_circle_area(r):
"""Function to calculate circle area"""
return math.pi * r ** 2
# Cell 4: Test function
test_radius = 7
result = calculate_circle_area(test_radius)
print(f"Circle area with radius {test_radius} is {result:.2f}")Basic Python Syntax
A first Python program reads its statements from top to bottom. A variable stores a value, a data type decides which operations that value supports, and input, output, and arithmetic turn those values into a working program.
Variables and Data Types
Python has several basic data types. A variable name refers to a value. Assigning another value makes the name point to that new value.
# Basic data types in Python
# String (text)
name = "John Doe"
message = 'Hello Python!'
# Integer (whole numbers)
age = 25
year = 2025
# Float (floating-point numbers)
height = 175.5
pi = 3.14159
# Boolean (True/False)
is_student = True
is_graduated = False
# List (list of items)
fruits = ["apple", "orange", "mango", "banana"]
numbers = [1, 2, 3, 4, 5]
# Dictionary (key-value pairs)
person = {
"name": "Alice",
"age": 22,
"major": "Computer Science"
}
# Display data types
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
print(type(fruits)) # <class 'list'>
print(type(person)) # <class 'dict'>Input and Output
A program receives user data as input and returns text or calculated values as output. Python uses input() to read text and print() to display a result.
# Input from user
user_name = input("Enter your name: ")
user_age = input("Enter your age: ")
# Data type conversion
age_number = int(user_age) # Convert string to integer
# Output with neat formatting
print(f"Hello {user_name}!")
print(f"You are {age_number} years old.")
# Mathematical operations
next_year = age_number + 1
print(f"Next year you will be {next_year} years old.")
# Output with different format
print("Name:", user_name)
print("Age:", age_number)
print("Age next year:", next_year)Basic Mathematical Operations
Python supports various mathematical operations:
# Basic mathematical operations
a = 10
b = 3
# Arithmetic operations
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.333...
floor_division = a // b # 3 (division result rounded down)
modulus = a % b # 1 (remainder)
exponent = a ** b # 1000 (10 to the power of 3)
print(f"{a} + {b} = {addition}")
print(f"{a} - {b} = {subtraction}")
print(f"{a} * {b} = {multiplication}")
print(f"{a} / {b} = {division}")
print(f"{a} // {b} = {floor_division}")
print(f"{a} % {b} = {modulus}")
print(f"{a} ** {b} = {exponent}")
# Operations with assignment
x = 5
x += 3 # x = x + 3, result is x = 8
x *= 2 # x = x * 2, result is x = 16
print(f"Current value of x: {x}")Practical Exercises
Complete these exercises to practice variables, input, output, and basic operations. Write each answer yourself before checking it, because the exercise trains the steps you take. The solutions follow the same order as the problems.
Simple Calculator
This program reads two numbers and an operator, then prints the result. It combines input, type conversion, and branching in one file.
# Simple calculator
print("=== SIMPLE CALCULATOR ===")
# Input from user
number1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
number2 = float(input("Enter second number: "))
# Calculation process
if operator == "+":
result = number1 + number2
elif operator == "-":
result = number1 - number2
elif operator == "*":
result = number1 * number2
elif operator == "/":
if number2 != 0:
result = number1 / number2
else:
print("Error: Cannot divide by zero!")
result = None
else:
print("Invalid operator!")
result = None
# Output result
if result is not None:
print(f"Result: {number1} {operator} {number2} = {result}")Temperature Conversion
This program converts a Celsius temperature into Fahrenheit and Kelvin, and it rejects a value below absolute zero.
The freezing and boiling statements approximate pure water at one atmosphere. Try 26.85: the conversion produces 80.3 °F and 300.0 K.
import math
# Temperature converter from Celsius to Fahrenheit and Kelvin
print("=== TEMPERATURE CONVERTER ===")
# Input temperature in Celsius
celsius = float(input("Enter temperature in Celsius: "))
if not math.isfinite(celsius) or celsius < -273.15:
raise ValueError("Temperature must be finite and at or above absolute zero")
# Convert to Fahrenheit and Kelvin
fahrenheit = (celsius * 9/5) + 32
kelvin = celsius + 273.15
# Output conversion results
print(f"\nConversion results from {celsius}°C:")
print(f"Fahrenheit: {fahrenheit:.1f}°F")
print(f"Kelvin: {kelvin:.1f}K")
# Bonus: Additional information
if celsius < 0:
print("This temperature is below water freezing point!")
elif celsius == 0:
print("This temperature is water freezing point!")
elif celsius == 100:
print("This temperature is water boiling point!")
elif celsius > 100:
print("This temperature is above water boiling point!")Student Profile
This program asks for a student's details, stores them in variables, and prints a short profile.
# Program to collect and display personal information
print("=== STUDENT PROFILE ===")
# Input information
name = input("Full name: ")
student_id = input("Student ID: ")
major = input("Major: ")
semester = int(input("Semester: "))
if semester < 1:
raise ValueError("Semester must be at least 1")
hobby = input("Favorite hobby: ")
current_year = int(input("Start year of the current academic year: "))
# Estimate using two semesters per academic year
entry_year = current_year - (semester - 1) // 2
estimated_graduation = entry_year + 4
# Display complete profile
print("\n" + "="*40)
print("STUDENT PROFILE")
print("="*40)
print(f"Name : {name}")
print(f"Student ID : {student_id}")
print(f"Major : {major}")
print(f"Semester : {semester}")
print(f"Hobby : {hobby}")
print(f"Entry Year : {entry_year}")
print(f"Est. Graduation: {estimated_graduation}")
print("="*40)
# Motivational message
if semester <= 2:
print("Good luck at the beginning of your studies!")
elif semester <= 6:
print("Keep up your learning spirit!")
else:
print("Good luck finishing your studies!")Check Your Work
Your practice programs are correct when:
- The calculator asks for two numbers and one operator, then displays the result of the selected operation.
- The temperature converter displays Fahrenheit and Kelvin values from the Celsius input.
- The student profile displays the entered data, entry year, estimated graduation year, and semester-based message.