Interested in learning Python but don’t know where to start? I’ll walk you through the basics of the ever-popular programming language step-by-step. In an hour or so, you’ll go from zero to writing real code.
Set Up Your Development Environment
To start writing and running Python programs locally on your device, you must have Python installed and an IDE (Integrated Development Environment) or text editor, preferably a code editor. First, let’s install Python. Go to the official Python website. Go to Downloads. You should see a button telling you to download the latest Python version (as of writing this, it’s 3.13.3.) It will also show you different operating systems for which you want to download.
If you want to install Python on Windows, download the installer. Double-click to open it. Follow the instructions and finish the installation.
If you’re using a Linux distribution such as Ubuntu or macOS, most likely Python has come pre-installed with it. However, if it’s not installed in your distro, you can either use your distro’s package manager to install it or build it from source. For macOS, you can use the Homebrew package manager or the official macOS installer.
After installing, you’ll find a Python shell installed called IDLE on your system. You can start writing Python code on that. But for more features and flexibility, it’s better to go with a good code editor or an IDE. For this tutorial, I’ll be using Visual Studio Code. You can get it on any of the three operating systems.
If you’re using VS Code, one more thing you’ll need is an extension called Code Runner. This isn’t strictly required but will make your life easier. Go to the Extensions tab, and search for Code Runner. Install the extension. After that, you should see a run button at the top right corner of your editor.
Now, every time you want to execute your code, you can click on that run button. With that, you’re ready to write some code.
Write Your First Python Program
Create a file and name it “hello.py” without quotes. You can use other names, too, but adding the .py at the end is important. For our first program, let’s print a string or text in the console, also known as the command line interface. For that, we’ll use the print() function in Python. Write this in your code editor:
print("Hello, Python")
Now run your code. It should print “Hello, Python” without the quotes on the console.
You can write anything between the quotes inside the print() function, which will be displayed. We’ll learn more about functions later.
Comments are lines that are not executed when you run your code. You can use comments to explain code segments so that when someone else looks at your program or you come back to it after a long time, you can understand what’s going on. Another use case for comments is when you don’t want to execute a line, you can comment it out.
To comment out a line in Python, we use the # symbol. Start any line with that symbol and it will be treated as a comment.
print("Hello, Python")
The first line is a comment and won’t be picked up when executed. You can add a comment on the right side of your code as well.
print(“Hello, Python”) # This line prints the text Hello, Python into the console
You can add as many comments in multiple lines as you want.
print("Hello, Python")
Another commonly used strategy for multiline comments is using triple quotes. You can do the same as above with this code.
"""This is my first Python programI love Python
Let's print some text"""
print("Hello, Python")
Store Data in Variables
Variables are like containers. They can hold values for you, such as text, numbers, and more. To assign a value to a variable, we follow this syntax:
a = 5
Here, we’re storing the value 5 in the variable “a”. Likewise, we can store strings.
a = "Python"
A best practice for writing variable names is to be descriptive so that you can identify what value it’s storing.
age = 18
You can print a variable’s value to the console.
name = "John"print(name)
This will print “John” on the console. Notice that in the case of variables, we don’t require them to be inside quotes when printing. Variable names have some rules to follow.
- They can’t start with numbers. But you can add numbers in the middle.
- You can’t have non-alphanumeric characters in them.
- Both uppercase and lowercase letters are allowed.
- Starting with an underscore (_) is allowed.
- For longer names, you can separate each word using an underscore.
- You can’t use certain reserved words (such as class) for variable names.
Here are some valid and invalid variable name examples:
name = "Alice"
age = 30
user_name = "alice123"
number1 = 42
_total = 100
1name = "Bob"
user-name = "bob"
total$ = 50
class = "math"
Learn Python’s Data Types
In Python, everything is an object, and each object has a data type. For this tutorial, I’ll only focus on a few basic data types that cover most use cases.
Integer
This is a numeric data type. These are whole numbers without a decimal point. We use the int keyword to represent integer data.
age = 25year = 2025
Float
These are numbers with a decimal point. We represent them with the float keyword.
price = 19.99
temperature = -3.5
String
These are text enclosed in quotes (single ‘ or double ” both work.) The keyword associated with strings is str.
name = "Alice"greeting = 'Hello, world!'
Boolean
This type of variable can hold only two values: True and False.
is_logged_in = Truehas_permission = False
To see what data type a variable is of, we use the type() function.
print(type(name))print(type(price))
print(type(is_logged_in))
Convert Between Data Types (Typecasting)
Python has a way to convert one type of data to another. For example, turning a number into a string to print it, or converting user input (which is always a string) into an integer for calculations. This is called typecasting. For that, we have different functions:
Function |
Converts To |
---|---|
int() |
Integer |
float() |
Float |
bool() |
Boolean |
str() |
String |
Here are some examples:
age_str = "25"age = int(age_str)
print(age + 5)
score = 99
score_str = str(score)
print("Your score is " + score_str)
pi = 3.14
rounded = int(pi)
whole_number = 10
decimal_number = float(whole_number)
print(bool(0))
print(bool("hello"))
print(bool(""))
Take User Input
Until now, we have directly hardcoded values into variables. However, you can make your programs more interactive by taking input from the user. So, when you run the program, it will prompt you to enter something. After that, you can do whatever with that value. To take user input, Python has the input() function. You can also store the user input in a variable.
name = input()
To make the program more understandable, you can write a text inside the input function.
name = input("What is your name?")print("Hello", name)
Know that inputs are always taken as strings. So, if you want to do calculations with them, you need to convert them to another data type, such as an integer or float.
age = int(input("What is your age?"))print("In 5 years, you'll be", age + 5)
Do Math With Python
Python supports various types of mathematics. In this guide, we’ll mainly focus on arithmetic operations. You can do addition, subtraction, multiplication, division, modulus, and exponentiation in Python.
x = 10y = 3
a = x + y
b = x - y
c = x * y
d = x / y
g = x // y
e = x % y
f = x ** y
print("Addition: ", a)
print("Subtraction: ", b)
print("Multiplication: ", c)
print("Division: ", d)
print("Floor Division: ", g)
print("Modulus: ", e)
print("Exponent: ", f)
You can do much more advanced calculations in Python. The Python math module has many mathematical functions. However, that’s not in the scope of this guide. Feel free to explore them.
Use Comparison Operators
Comparison operators let you compare values. The result is either True or False. This is super useful when you want to make decisions in your code. There are six comparison operators.
Operator |
Meaning |
---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
Less than |
|
>= |
Greater than or equal |
Less than or equal |
Here are some examples:
a = 10b = 7
print(a > b)
print(a == b)
print(a
print(a != b)
print(a >= b)
print(a # True if a is either less than or equal to b
Apply Logical Operators
Logical operators help you combine multiple conditions and retrurns True or False based on the conditions. There are three logical operators in Python.
Operator |
Meaning |
---|---|
and |
True if both are true |
or |
True if at least one is true |
not |
Flips the result |
Some examples will make it clearer.
age = 17has_license = True
print(age >= 18 and has_license)
day = "Saturday"
print(day == "Saturday" or day == "Sunday")
is_logged_in = False
print(not is_logged_in)
Write Conditional Statements
Now that you’ve learned about comparison and logical operators, you’re ready to use them to make decisions in your code using conditional statements. Conditional statements let your program choose what to do based on certain conditions. Just like real-life decision-making. There are three situations for conditional statements.
if Statement
We use if when you want to run some code only if a condition is true.
if condition:
Here’s an example:
age = 18if age >= 18:
print("You're an adult.")
If the condition is false, the code inside the if block is simply skipped.
In Python, indentation is crucial. Notice that the code inside the if block is indented. Python picks this up to understand which line is part of which block. Without proper indentation, you’ll get an error.
if-else Statement
We use if-else when you want to do one thing if the condition is true, and something else if it’s false.
if condition:
else:
Example:
is_logged_in = Falseif is_logged_in:
print("Welcome back!")
else:
print("Please log in.")
if-elif-else Statement
We use if-elif-else when you have multiple conditions to check, one after the other.
if condition1:
elif condition2:
else:
Let’s see an example.
score = 85if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Keep trying!")
You can add as many elif conditions as you like.
Loop Through Code with for and while
In programming, we often have to do repetitive tasks. For such cases, we use loops. Instead of copying the same code, we can use loops to do the same thing with much less code. We’ll learn about two different loops.
for Loop
The for loop is useful when you want to run a block of code a specific number of times.
for i in range(n):
Let’s print a text using a loop.
for i in range(5): print("Hello!")
This prints “Hello!” 5 times. The value of i goes from 0 to 4. You can also start at a different number:
for i in range(1, 4): print(i)
The ending value (4 in this case) in the range() function isn’t printed because it’s excluded from the range.
while Loop
The while loop is used when you’re uncertain how long the loop will run. When you want to keep looping as long as a condition is true.
while condition:
A quick example.
count = 1while count 3:
print("Count is", count)
count += 1
Two more useful statements in loops are the break statement and the continue statement. The break statement stops a loop early if something you specify happens.
i = 1while True:
print(i)
if i == 3:
break
i += 1
The continue statement skips the rest of the code in the loop for that iteration, and goes to the next one.
for i in range(5): if i == 2:
continue
print(i)
Write Your Own Functions
As your programs get bigger, you’ll find yourself typing the same code over and over. That’s where functions come in. A function is a reusable block of code that you can “call” whenever you need it. It helps you avoid repeating code, organize your program, and make code easier to read and maintain. Python already gives you built-in functions like print() and input(), but you can also write your own.
To create a function, use the def keyword:
def function_name():
Then you call it like this:
function_name()
Let’s create a simple function:
def say_hello(): print("Hello!")
print("Welcome to Python.")
say_hello()
You can also make your function accept parameters. Parameters are values passed into it.
def greet(name): print("Hello,", name)
To call it with an argument:
greet("Alice")greet("Bob")
You can use multiple parameters, too.
def add(a, b): print(a + b)
add(3, 4)
You can reuse the same function multiple times with different inputs.
That covers some of the basics of Python programming. If you want to become a better programmer, you need to start doing some projects, such as an expense tracker or a to-do list app.