Quick answer: To learn Python basics, install Python 3, run a first program, and then study variables, input, conditions, loops, strings, lists, dictionaries, functions, errors and files in that order. Type every example, change it and predict the output. Finish by building one small program, such as a marks report, that uses all of these ideas together.
This Python basics tutorial takes you from zero to a small working program. You do not need any coding experience. You need a laptop, about an hour a day and the patience to type each example yourself.
Every step follows the same pattern: one idea, a short program, the output and a small task. Try to guess the output before you read it. A wrong guess is useful because it shows you what to study.
How to use this Python basics tutorial
The tutorial has eight steps. Each step uses what you learned before it.
| Step | Topic | What you can write after it |
|---|---|---|
| 1 | Setup and first program | A greeting |
| 2 | Variables, types and input | A bill calculator |
| 3 | Conditions | A pass or fail check |
| 4 | Loops | A multiplication table |
| 5 | Strings and lists | A name list |
| 6 | Dictionaries, tuples and sets | A phone book |
| 7 | Functions and errors | A safe calculator |
| 8 | Files and a mini project | A marks report |
One or two steps a week is a good speed for a college student. Keep a folder named python-practice and save each program with a clear name, such as step2_bill.py.
Steps 1 and 2: first program, variables and input
Step 1: Install Python and run a program
- Download Python 3 from python.org.
- On Windows, tick the option that adds Python to PATH if the installer shows it.
- Install VS Code or open IDLE.
- Create a file named
hello.pywith this code:
print("Hello, Python")
print(10 + 5)
In a terminal opened in that folder, run python hello.py. On some computers the command is python3 hello.py or py hello.py. You will see:
Hello, Python
15
The first line has quotes, so Python prints the text. The second line has no quotes, so Python does the sum. print("10 + 5") would show 10 + 5.
Step 2: Store values in variables
A variable is a name for a value. You do not write the type; Python works it out.
name = "Divya" # str, text
age = 19 # int, whole number
height = 5.4 # float, decimal number
is_student = True # bool, True or False
print(name, "is", age)
print(type(height))
Divya is 19
<class 'float'>
Names can use letters, digits and _, but cannot start with a digit. total_marks is fine. 2marks is not. Python also treats Age and age as two different names.
Taking input. The input() function always gives you text, even when the user types a number. Convert it before you do maths:
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(f"Total: {total:.2f}")
If you type 49.5 and then 2, the last line is Total: 99.00. The f before the quotes lets you put a variable inside {}. The .2f part shows two decimal places.
Common mistake: Forgetting to convert input. If the user types 5 and 3,
input()gives"5"and"3". Adding them gives"53", not 8. Useint()orfloat()first.
Useful operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
/ |
Divide | 9 / 2 |
4.5 |
// |
Divide and round down | 9 // 2 |
4 |
% |
Remainder | 9 % 2 |
1 |
** |
Power | 3 ** 2 |
9 |
== |
Is it equal? | 4 == 4 |
True |
!= |
Is it different? | 4 != 5 |
True |
Task: ask for a distance in kilometres and print it in metres.
Step 3: Make decisions with conditions
Programs need to choose. Use if, elif and else:
marks = 72
if marks >= 75:
print("Distinction")
elif marks >= 40:
print("Pass")
else:
print("Try again")
Pass
Python checks from top to bottom and runs the first block that is true. Then it skips the rest. So the order matters. If you checked marks >= 40 first, a student with 90 would only see "Pass".
Look at the spaces. Python uses indentation to know which lines belong to a block. Use four spaces each time, and end the if line with a colon.
Join two checks with and, or and not:
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("You may enter")
You may enter
Task: ask for a number and print "Even" or "Odd". Hint: use %.
Step 4: Repeat work with loops
A for loop repeats for each item. range(1, 4) gives 1, 2 and 3. It stops before the last number.
for i in range(1, 4):
print(f"7 x {i} = {7 * i}")
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
A while loop repeats as long as a condition is true:
count = 3
while count > 0:
print(count)
count = count - 1
print("Go")
3
2
1
Go
Remember to change the value inside a while loop. Without count = count - 1, it would never end. Press Ctrl+C to stop a stuck program.
A very common pattern is to keep a running total:
total = 0
for number in [4, 6, 10]:
total = total + number
print(total)
20
Start at zero, add each item, print at the end. You will use this pattern for sums, counts and averages.
| Use | When |
|---|---|
for |
You know the items or the count |
while |
You repeat until something changes |
break |
You want to leave the loop now |
continue |
You want to skip to the next round |
Task: print the sum of all even numbers from 1 to 20. The answer is 110.
Step 5: Work with strings and lists
A string is text. Each character has a position, and counting starts at 0.
word = "Python"
print(word[0])
print(word[-1])
print(word[0:3])
print(word.upper())
print(len(word))
P
n
Pyt
PYTHON
6
The slice [0:3] takes positions 0, 1 and 2. A string cannot be changed in place, so word.upper() makes a new string.
A list holds many values in order, and you can change it:
names = ["Ravi", "Asha"]
names.append("Kiran")
names[0] = "Rahul"
names.sort()
print(names)
print(len(names))
['Asha', 'Kiran', 'Rahul']
3
You can loop over a list, and you can also build a new list in one line. This is called a list comprehension:
marks = [35, 80, 62, 20]
passed = [m for m in marks if m >= 40]
print(passed)
print(max(marks), sum(marks))
[80, 62]
80 197
Read it as: "take each m in marks, and keep it if it is 40 or more".
Task: from a list of words, make a new list that keeps only words longer than four letters.
Step 6: Use dictionaries, tuples and sets
A dictionary stores a value under a key, like a phone book stores a number under a name.
phone = {"Asha": "90001", "Ravi": "90002"}
phone["Meena"] = "90003"
print(phone["Ravi"])
print(phone.get("John", "Not found"))
for name, number in phone.items():
print(name, number)
90002
Not found
Asha 90001
Ravi 90002
Meena 90003
phone["John"] would stop the program with a KeyError. The get method is safer because you can give a fallback value.
Two more collections complete the set:
- Tuple: a fixed group, as in
point = (4, 7). You cannot change it. - Set: unique items only, as in
{1, 2, 2}, which becomes{1, 2}.
| Collection | Brackets | Changes allowed? | Repeats allowed? |
|---|---|---|---|
| List | [ ] |
Yes | Yes |
| Tuple | ( ) |
No | Yes |
| Set | { } |
Yes | No |
| Dictionary | {key: value} |
Yes | Keys: no, values: yes |
Task: count how many times each letter appears in "banana". You should get b: 1, a: 3, n: 2.
Note: Once you finish this step, solve a few of our Python basics practice problems. They use exactly these tools.
Step 7: Write functions and handle errors
A function is a named block of code that you can use again.
def average(numbers):
if len(numbers) == 0:
return 0
return sum(numbers) / len(numbers)
print(average([10, 20, 30]))
print(average([]))
20.0
0
numbers is a parameter. return sends a result back. The check for an empty list stops a division by zero. Note that / gives 20.0, a float.
print and return are not the same. print shows a value on screen. return gives the value back to your program, so you can use it in the next step.
Users make typing mistakes, so handle errors with try and except:
def to_number(text):
try:
return int(text)
except ValueError:
return None
print(to_number("42"))
print(to_number("forty"))
42
None
Catch the exact error you expect, such as ValueError. A bare except: hides real bugs.
Interview note: "What happens if a function has no return statement?" It returns
None. This small question appears often in Python viva and fresher interviews.
Step 8: Build a mini project with a file
Now join all the Python basics examples into one program. It saves marks to a file, reads them back and prints a report.
def grade(mark):
if mark >= 75:
return "A"
if mark >= 40:
return "B"
return "Fail"
students = {"Asha": 82, "Ravi": 55, "Kiran": 31}
with open("marks.txt", "w") as file:
for name, mark in students.items():
file.write(f"{name},{mark}\n")
total = 0
count = 0
with open("marks.txt") as file:
for line in file:
name, mark = line.strip().split(",")
mark = int(mark)
total = total + mark
count = count + 1
print(name, mark, grade(mark))
print("Average:", total / count)
Asha 82 A
Ravi 55 B
Kiran 31 Fail
Average: 56.0
Read it slowly. "w" opens the file for writing and replaces old content. \n starts a new line. strip() removes that line break, and split(",") cuts the line into two parts. The with block closes the file for you.
Make it your own with these upgrades:
- Take names and marks from the user.
- Reject marks below 0 or above 100.
- Print the topper's name.
- Add a menu: add, view, search and exit.
If you can do all four without copying, your Python basics are strong.
What to do after you learn Python basics
Tutorials about Python basics for beginners end here, but your practice should not. Follow this order:
- Practise: solve two problems a day for two weeks.
- Revise: keep the Python basics cheat sheet open and test yourself.
- Learn OOP: classes and objects prepare you for frameworks.
- Pick a path: web development, data or automation.
For web development, follow our Python full stack developer roadmap. Still choosing a first language? Compare Java and Python for freshers.
Pro tip: When you get an error, read the last line first. It names the problem. Then look at the line number just above it. Fixing your own errors is one of the fastest ways to learn Python basics.
If you want a teacher to check your code, the Python Full Stack with AI course begins from zero and keeps each batch to 27 students. Our course guide explains the full syllabus.
Frequently asked questions
Can I learn Python basics with no coding experience?
Yes. Python uses short, readable lines and you can run a program on your first day. Type each example yourself and change it. That is how the ideas start to make sense.
How long does it take to learn Python basics?
With one to two hours of practice a day, many beginners can cover these basics in about four to six weeks. Regular practice matters more than long study hours on one day.
Do I need a powerful laptop to learn Python?
No. Python basics run on almost any working laptop. You only need Python 3 and a simple editor such as VS Code or IDLE, which is included in the usual Python installer for Windows.
What should I learn after Python basics?
Learn object-oriented programming and solve more problems. Then choose a direction. Django, SQL and React lead to full stack work, while pandas, SQL and Power BI lead to data analytics.
Why does my Python program show an IndentationError?
Python uses the spaces at the start of a line to group code. The error means that a line has too many or too few spaces, or that a block is missing. Use four spaces for each level.
Want to learn Python with personal attention? Book a free demo class, at our Madhapur campus or live online, and see how a batch of up to 27 learns.
