Python Basics Explained — Complete Beginner's Guide (2026)
Python variables are named containers used to store data values in memory, enabling dynamic typing and flexible assignment without explicit type declarations.
What You’ll Learn
- What Python is and why it’s one of the most popular programming languages
- How to set up Python and run your first program
- Variables, data types, operators, and strings explained step by step
- How to get user input and build interactive programs
- Common mistakes beginners make and how to avoid them
Why Python Basics Matter
Python powers real-world tools like Durga Antivirus Pro, which uses Python scripts to scan file signatures and detect malware patterns. DodaZIP leverages Python for batch file processing and compression automation. Even Doda Browser uses Python-based build scripts. Every professional tool starts with the fundamentals — variables to store data, operators to process it, and control structures to make decisions. Mastering Python basics gives you the foundation to build anything from automation scripts to full security suites.
flowchart LR
A["Python Basics"] --> B["Control Flow"]
B --> C["Functions"]
C --> D["Lists & Dicts"]
D --> E["Modules & Packages"]
E --> F["File I/O & Errors"]
A:::current --> B
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
style F fill:#f1f5f9,stroke:#94a3b8,color:#64748b
What is Python?
Imagine you want to write a recipe. You could write it in a complex chef language that only professional cooks understand, or you could write it in plain English so anyone can follow it. Python is like that plain English version of programming — it’s designed to be readable and simple, yet powerful enough for professionals.
Python was created by Guido van Rossum and first released in 1991. Here’s what makes it special:
- Interpreted — code runs line by line without needing compilation
- Dynamically typed — you don’t declare variable types; Python figures them out
- Beginner-friendly — syntax is clean and reads like plain English
- Versatile — used for web development (Django, Flask), data science, automation, and cybersecurity
How Python Code Runs
When you write Python code, here’s what happens behind the scenes:
flowchart LR
A["You write code in a<br/><strong>.py file</strong>"] --> B["Python Interpreter<br/>reads line by line"]
B --> C{"Syntax<br/>correct?"}
C -->|"Yes"| D["Converts to<br/>bytecode"]
C -->|"No"| E["Error message<br/>shown"]
D --> F["Python Virtual Machine<br/>executes bytecode"]
F --> G["Output / Result"]
style A fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
style B fill:#fef3c7,stroke:#f59e0b,color:#78350f
style C fill:#fce7f3,stroke:#ec4899,color:#831843
style D fill:#d1fae5,stroke:#10b981,color:#064e3b
style E fill:#fee2e2,stroke:#ef4444,color:#7f1d1d
style F fill:#ede9fe,stroke:#8b5cf6,color:#4c1d95
style G fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
Setting Up Python
Think of Python like a musical instrument. Before you can play, you need to have the instrument. Here’s how to get Python on your computer.
Check if Python is Installed
Open a terminal (Command Prompt on Windows, Terminal on macOS/Linux) and type:
python --versionIf you see Python 3.12.x or higher, you’re ready. If not, follow the steps below.
Installing Python
- Go to python.org/downloads
- Download the latest Python 3.x version for your operating system
- During installation on Windows, check “Add Python to PATH” — this lets you run
pythonfrom any folder - On Linux, use your package manager:
sudo apt install python3
Verify Installation
python --versionRunning Python Code
There are two ways to run Python. Think of them like practicing scales vs performing a song.
1. Interactive Mode (REPL)
Type python in your terminal and you’ll see a >>> prompt. This is like a sandbox — type code and see results immediately:
>>> 2 + 2
4
>>> print("Hello, World!")
Hello, World!
>>> exit()2. Script Mode (File)
Save your code in a .py file and run it like a finished song:
# hello.py
print("Hello, World!")python hello.pyYour First Python Program
Create a file called hello.py and write:
print("Hello, World!")Let’s break this down line by line:
printis a built-in function — think of it as Python’s way of talking to you- The parentheses
()tell Python to call (run) the function "Hello, World!"is a string — text data enclosed in quotes- When you run it, Python executes
print, which displays the text on screen
print("Hello", "World", 2024)
# Output: Hello World 2024print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherryComments
Comments are notes in your code that Python ignores. They help you (and others) understand what the code does.
# This is a single-line comment
print("Hello") # Comments can go after code tooWhy use comments? When you come back to code you wrote six months ago, you’ll thank yourself for leaving notes.
Variables
Think of variables like sticky notes. You write a value on a sticky note (assignment), and you stick it somewhere (a name). Whenever you need that value, you just look at the note.
name = "Alice" # String variable — stores text
age = 25 # Integer variable — stores whole numbers
height = 1.68 # Float variable — stores decimal numbers
is_student = True # Boolean variable — stores True/FalseWhat’s happening here? Python creates a box in memory, labels it with your variable name, and stores the value inside. Unlike other languages, you don’t need to tell Python what type of data goes in the box — Python figures it out automatically.
Variable Naming Rules
| Rule | Valid Examples | Invalid Examples |
|---|---|---|
| Start with a letter or underscore | name, _count | 1name |
| Remaining: letters, digits, underscores | user_name, item2 | user-name |
| Case-sensitive | age and Age are different | — |
| Can’t be reserved keywords | — | class, for, if |
# Good — descriptive names
first_name = "Alice"
total_price = 49.99
is_logged_in = False
# Bad — unclear names
a = "Alice" # What does 'a' mean?
fn = "Alice" # Abbreviations are confusingReassigning Variables
Variables can change at any time — that’s why they’re called “variables”:
score = 10
print(score) # 10
score = 25 # Same name, new value
print(score) # 25
score = "twenty-five" # Even a different type!
print(score) # twenty-fiveData Types
Every value in Python has a type. Python automatically knows the type based on how you write the value.
Integers (int) — Whole Numbers
age = 25
population = -5000
big_number = 1_000_000 # Underscores improve readabilityFloats (float) — Decimal Numbers
price = 19.99
pi = 3.141590.1 + 0.2 gives 0.30000000000000004, not exactly 0.3. This isn’t a Python bug — it’s how all computers represent floating-point numbers in binary.Strings (str) — Text
name = "Alice"
greeting = 'Hello' # Single quotes work too
multi_line = """This is a
multi-line string."""Booleans (bool) — True/False
is_active = True
is_completed = FalseNoneType (None) — Empty Value
result = NoneThink of None as an empty box — the box exists, but nothing’s inside yet.
Checking Types
Use the type() function:
print(type("hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>Type Conversion
Sometimes you need to change one type to another. Think of this like converting between currencies:
# String to integer
age_str = "25"
age_int = int(age_str) # Now you can do math
print(age_int + 5) # 30
# Integer to string
count = 10
count_str = str(count)
print("Count: " + count_str) # "Count: 10"
# String to float
price = float("19.99")
print(price + 0.01) # 20.0Operators
Operators are the action words of programming. They tell Python what to do with values.
Arithmetic Operators
a, b = 10, 3
print(a + b) # 13 — Addition
print(a - b) # 7 — Subtraction
print(a * b) # 30 — Multiplication
print(a / b) # 3.333... — Division (always returns float)
print(a // b) # 3 — Floor division (integer result, rounded down)
print(a % b) # 1 — Modulo (remainder after division)
print(a ** b) # 1000 — Exponentiation (10 to the power of 3)The // operator is useful when you need whole numbers:
minutes = 125
hours = minutes // 60 # 2 (whole hours)
remaining = minutes % 60 # 5 (remaining minutes)
print(f"{hours}h {remaining}m") # 2h 5mComparison Operators
These return True or False:
print(5 == 5) # True — Equal to
print(5 != 3) # True — Not equal to
print(5 < 10) # True — Less than
print(5 > 10) # False — Greater than
print(5 <= 5) # True — Less than or equal to
print(5 >= 10) # False — Greater than or equal toCommon confusion: = assigns a value. == checks equality.
x = 5 # Assigns 5 to x
x == 5 # Checks if x equals 5 → TrueLogical Operators
Combine multiple conditions:
x, y = True, False
print(x and y) # False — both must be True
print(x or y) # True — at least one is True
print(not x) # False — inverts the valueReal-world use:
age = 20
has_license = True
if age >= 18 and has_license:
print("You can drive!")
# Output: You can drive!This is how Durga Antivirus Pro checks multiple conditions before flagging a file as suspicious — both the signature match AND the behavior pattern must be present.
Strings in Detail
Strings are sequences of characters. Think of a string like a bead necklace — each bead is a character, and the string holds them in order.
String Indexing
Each character has a position (index), starting from 0:
flowchart LR
subgraph Positive["Positive Indexes"]
P0["0: P"] --> Y1["1: y"]
Y1 --> T2["2: t"]
T2 --> H3["3: h"]
H3 --> O4["4: o"]
O4 --> N5["5: n"]
end
subgraph Negative["Negative Indexes"]
N_6["-6: P"] --> N_5["-5: y"]
N_5 --> N_4["-4: t"]
N_4 --> N_3["-3: h"]
N_3 --> N_2["-2: o"]
N_2 --> N_1["-1: n"]
end
word = "Python"
print(word[0]) # P — first character
print(word[-1]) # n — last character
print(word[0:3]) # Pyt — characters 0 to 2 (end is exclusive)Common String Methods
text = " Python is FUN! "
print(text.upper()) # " PYTHON IS FUN! "
print(text.lower()) # " python is fun! "
print(text.strip()) # "Python is FUN!" (removes whitespace)
print(text.replace("FUN", "awesome")) # " Python is awesome! "
print("is" in text) # True — check if substring exists
csv = "apple,banana,cherry"
fruits = csv.split(",") # ["apple", "banana", "cherry"]
print(fruits)f-Strings (Python 3.6+) — The Cleanest Way
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 25 years old.
print(f"Pi is approximately {3.14159:.2f}") # Format to 2 decimalsUser Input
Getting input from the user is like asking a question and waiting for an answer:
name = input("What is your name? ")
print(f"Hello, {name}!")Important: input() always returns a string. If you need a number, convert it:
age = int(input("How old are you? ")) # Convert string to integerComplete Input Example
name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print(f"Hi {name}, you are {age} years old and {height}m tall.")Common Mistakes
1. Forgetting Indentation
Python uses indentation to group code. Other languages use braces {}, but Python uses spaces:
# Wrong
if True:
print("Hello") # IndentationError!
# Right
if True:
print("Hello") # 4 spaces2. Confusing = and ==
# Wrong — assigns, doesn't compare
if x = 5:
print("x is 5")
# Right — compares
if x == 5:
print("x is 5")3. Forgetting to Convert Input
# Wrong — comparing string to int
age = input("Age: ")
if age > 18: # TypeError!
# Right
age = int(input("Age: "))
if age > 18:
print("Adult")4. Trying to Modify a String
Strings are immutable — you can’t change them in place:
text = "Hello"
# text[0] = "J" # TypeError!
text = "J" + text[1:] # "Jello" — create a new string5. Naming Variables After Python Keywords
# Wrong — 'list' is a Python keyword
list = [1, 2, 3] # Shadows the built-in list() function
# Right
my_list = [1, 2, 3]6. Not Using Underscores in Large Numbers
# Hard to read
population = 1000000000
# Easy to read
population = 1_000_000_000Practice Questions
1. What is the output of print(type(3.14))?
<class 'float'>. Python sees the decimal point and knows it’s a float.
2. Fix this code:
name = "Alice"
age = "25"
print(name + " is " + age + " years old")This actually works since both are strings. But to make age an integer:
age = 25
print(name + " is " + str(age) + " years old")
# Or use an f-string:
print(f"{name} is {age} years old")3. What’s the difference between 10 / 3 and 10 // 3?
10 / 3 → 3.333... (float division). 10 // 3 → 3 (floor division, integer result).
4. Why does "Hello" + 5 cause an error?
You can’t concatenate a string and an integer. Convert the int first: "Hello" + str(5).
Challenge: Write a program that asks for a word and prints:
- The length of the word
- The word in uppercase
- The first and last character
- Whether the word contains the letter “e”
Solution
word = input("Enter a word: ")
print(f"Length: {len(word)}")
print(f"Uppercase: {word.upper()}")
print(f"First char: {word[0]}")
print(f"Last char: {word[-1]}")
print(f"Contains 'e': {'e' in word.lower()}")FAQ
Try It Yourself
Run this complete program to see Python basics in action:
# Personal Info Card
print("=" * 40)
print(" PROFILE CARD GENERATOR")
print("=" * 40)
name = input("Enter your name: ")
age = input("Enter your age: ")
city = input("Enter your city: ")
language = input("Favorite programming language: ")
print("\n" + "=" * 40)
print(" YOUR PROFILE CARD")
print("=" * 40)
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Language: {language}")
print(f"\nFun fact: \"{name}\" has {len(name)} characters.")
print(f"Your city in uppercase: {city.upper()}")Expected output (example):
========================================
PROFILE CARD GENERATOR
========================================
Enter your name: Alice
Enter your age: 25
Enter your city: Mumbai
Favorite programming language: Python
========================================
YOUR PROFILE CARD
========================================
Name: Alice
Age: 25
City: Mumbai
Language: Python
Fun fact: "Alice" has 5 characters.
Your city in uppercase: MUMBAIWhat’s Next
Now that you’ve mastered Python basics, move on to control flow where you’ll learn to make decisions and repeat actions in your programs.
| Topic | Description | Link |
|---|---|---|
| Python Control Flow | Conditionals and loops | https://tutorials.dodatech.com/programming-languages/python/py-control-flow/ |
| Python Functions | Write reusable code | https://tutorials.dodatech.com/programming-languages/python/py-functions/ |
| JavaScript Basics | Another language to compare | JavaScript |
Practice tip: The best way to learn programming is to write code every day. Try modifying the examples above — change variable values, add new questions to the input form, and experiment with different string methods.
What’s Next
Congratulations on completing this Py Basics tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro