1. Introduction to Python Basics
What is Python?
Python is a high-level programming language known for its clean, readable syntax that reads almost like plain English. It was created by Guido van Rossum and first released in 1991, with a core design philosophy centered on simplicity and readability over complex syntax rules. Because of this, Python is widely recommended as the first language for anyone starting their coding journey, since you don't need a technical background to follow along. Even fairly complex tasks can often be written in just a handful of lines compared to other languages. Python is also an interpreted, dynamically-typed language, meaning it checks and runs your code as it goes rather than demanding rigid setup beforehand. Learning Python Basics properly gives you a foundation that carries over into almost every area of modern software development.
Why Python is popular
Python's popularity comes down to a mix of simplicity, versatility, and community support that few other languages manage to combine so well. Its syntax stays close to natural language, which shortens the learning curve dramatically compared to languages like C++ or Java. Large companies such as Google, Netflix, and Instagram rely on Python daily, which proves it isn't just a beginner tool but a genuinely production-ready language used at massive scale. It also has one of the largest open-source communities of any language, meaning free libraries, tutorials, and support exist for almost anything you want to build. Python code also tends to take noticeably less time to write compared to many other languages, which saves real development time. This blend of approachability and real-world power is exactly why so many beginners pick Python Basics as their entry point.
Where Python is used
One of Python's biggest strengths is how many different fields it's actually used in, which makes it a genuinely flexible skill rather than a narrow, niche one. It plays a major role in web development, where frameworks like Django and Flask handle backend logic for real websites. In data science and analytics, libraries like Pandas and NumPy make Python the go-to choice for working with large datasets. Artificial intelligence and machine learning projects frequently rely on Python through tools like TensorFlow and PyTorch. It's also widely used for automation and scripting, handling repetitive tasks that would otherwise take hours manually. Robotics and simple game development projects often use Python too, thanks to its beginner-friendly nature. Once you're comfortable with the fundamentals, you can branch into whichever of these areas interests you most.
- Web development — Django and Flask
- Data science — Pandas and NumPy
- AI and machine learning — TensorFlow and PyTorch
- Automation and scripting — handling repetitive tasks automatically
- Robotics and hardware — controlling sensors and simple hardware projects
- Game development — small games built with libraries like Pygame
print("Welcome to Python!") student = "Kundan" topic = "Python programming" lessons = 3 print("Student:", student) print("Learning:", topic) print("Lessons completed:", lessons) next_lesson = lessons + 1 print("Next lesson number:", next_lesson) print("Python makes programming easier to learn.")
Click Run to see the output.
2. Setting Up Python
Installing Python
Before writing any code, you need Python installed on your computer, and thankfully it's completely free and available for Windows, macOS, and Linux directly from the official Python website. During installation on Windows, it's important to check the box labeled "Add Python to PATH," since skipping this is one of the most common setup mistakes beginners make. Without it, Python commands often won't work properly when typed into the terminal later on. Once the installer finishes, you can confirm everything worked correctly by opening your terminal or command prompt and typing a simple version check command. If it responds with a version number instead of an error message, your installation is ready and you can start writing your very first lines of code. It's also worth noting that some macOS and Linux systems come with an older version of Python pre-installed, so installing the latest version yourself is still recommended.
- Download Python for free from the official Python downloads page
- Choose the installer that matches your operating system (Windows, macOS, or Linux)
- On Windows, always check "Add Python to PATH" during setup
- Follow the installer prompts and let it finish completely
- Confirm installation by running
python --versionin your terminal - Reinstall the latest version even if an older one already exists on your system
What is a Python interpreter?
A Python interpreter is the program responsible for reading your code and executing it line by line, rather than converting the entire file into machine code before anything runs. This is fundamentally different from compiled languages like C, where the whole program must be translated in advance before execution can even begin. Because Python runs each line as it goes, you get near-instant feedback, which means you can write a line, run it, see the result, and fix mistakes almost immediately. This interactive nature is a big reason why testing and debugging feel so much faster and more forgiving in Python compared to many other programming languages. The interpreter installs automatically the moment you install Python itself, so there's no separate setup required. Understanding this concept early helps explain why Python feels so quick and responsive as you experiment with code.
Basic ways to run Python code
There are several beginner-friendly ways to actually execute Python code once it's installed on your system. IDLE, the simple editor that comes bundled directly with Python, is a great starting point for quick tests and small experiments. Code editors like VS Code offer a more professional experience, with syntax highlighting, auto-formatting, and built-in error detection that catches mistakes as you type. You can also run a Python file directly from the terminal or command prompt by typing python followed by the file name. Many beginners also try online compilers, which let you write and run Python code instantly inside a browser without installing anything at all. Each of these options suits a different stage of learning, and most people naturally move from simple tools toward a full code editor as their projects grow larger and more complex.
- IDLE — bundled automatically with every Python installation
- VS Code — a professional, beginner-friendly code editor
- Terminal — run a file with
python filename.py - Online compilers — run Python instantly in a browser
- Jupyter Notebook — popular for data science and step-by-step experiments
- PyCharm — a full-featured IDE for larger Python projects
3. Python Syntax and Indentation
Basic Python syntax
Python's syntax refers to the set of rules that determine exactly how code must be structured for the interpreter to understand it correctly. Unlike many older languages, Python doesn't require semicolons at the end of every line or curly braces to mark the beginning and end of code blocks. Instead, it relies on clean line breaks and consistent spacing to define structure, which is a big part of why Python code tends to look so uncluttered and easy to follow. This minimalist approach means there's simply less visual noise between you and the actual logic you're trying to express. Because of this simplicity, beginners often find that Python code is genuinely easier to read back later compared to more symbol-heavy languages. Getting comfortable with this clean syntax early is one of the very first real steps toward mastering Python Basics.
How indentation works
Indentation in Python isn't just a formatting preference the way it is in many other languages, it's an actual, strictly enforced part of the syntax itself. Python typically uses four spaces of indentation to define exactly which lines belong inside a block, such as the body of a loop, function, or conditional statement. If your indentation is inconsistent within the same block, Python will raise an IndentationError and refuse to run the code entirely, rather than just giving a warning. While this might feel strict or frustrating at first, it actually forces every Python program to remain visually organized, since genuinely messy indentation simply cannot exist without breaking the code outright. A large share of beginner mistakes trace directly back to small, easy-to-miss indentation errors, so it's worth slowing down and double-checking spacing whenever something doesn't run as expected. Over time, consistent indentation becomes second nature and stops feeling like an extra burden.
Comments in Python
Comments are lines of text that the Python interpreter completely ignores when running your code, and they exist purely to explain what the code does to a human reader. A single-line comment starts with a hash symbol, and everything written after it on that same line is skipped entirely by Python. For longer explanations that need to span multiple lines, triple quotes can be used to write block-style comments instead of repeating the hash symbol over and over. Comments become genuinely valuable when you revisit your own code weeks or months later and have forgotten exactly why you wrote something a certain way. They're equally important when someone else needs to understand your logic quickly without reading through every single line. Building the habit of writing clear, honest comments early on will make you a noticeably more thoughtful and organized programmer as your projects grow larger.
# single-line comment"""a multi-line comment"""- Comments are completely ignored when the code runs
- Use them to explain "why", not just "what"
- Helpful for revisiting your own code later
- See official style guidance in PEP 8
temperature = 28 if temperature > 30: print("It is a hot day.") print("Drink enough water.") elif temperature > 20: print("The weather is comfortable.") print("It is a good day to learn Python.") else: print("The weather is cool.") print("Temperature:", temperature) print("Program finished successfully.")
Click Run to see the output.
4. Python Variables
What is a variable?
A variable is essentially a named container that stores a value so it can be reused later on in your program without retyping it every time. A helpful way to picture it is a labeled box, where you place something inside, and whenever you need it again, you simply refer to it by its label instead of the value itself. In Python, you don't need to declare a variable's type in advance the way you would in many other programming languages, which removes a whole layer of complexity for beginners. Variables are what make programs dynamic rather than static, since their stored values can change freely as your program runs and responds to new input or conditions. Almost every meaningful program you write, no matter how simple or advanced, will revolve around creating, updating, and reading variables in some form.
Creating and assigning variables
Creating a variable in Python is as simple as writing a name, an equal sign, and a value, with no special keyword required the way some other languages demand. For example, writing age equals 25 immediately creates a variable named age that now holds the value 25 for later use. You can also assign several variables at once on a single line, which keeps your code compact and readable when setting up multiple related values together. Once a variable already exists, you can update it at any later point simply by assigning it a brand-new value, and Python will silently overwrite the old one without complaint. This flexibility is one of the major reasons Python feels so natural and low-friction to write compared to more rigid, strictly-typed languages that demand upfront declarations.
Variable naming rules
Python enforces a handful of simple but important rules when it comes to naming variables correctly. Variable names can include letters, numbers, and underscores, but they are never allowed to start with a number, since that would confuse the interpreter. Names are also case-sensitive in Python, which means that age and Age would actually be treated as two completely separate, unrelated variables. It's considered good practice to use descriptive, meaningful names like student_name rather than vague single-letter names like x, since this makes your code far easier to read later. Python's own reserved keywords, such as print or for, can never be used as variable names because they already carry special meaning to the interpreter. Following these naming conventions consistently makes your code noticeably easier to understand, both for yourself later and for anyone else who eventually looks at it.
- Can contain letters, numbers, and underscores — cannot start with a number
- Case-sensitive:
ageandAgeare different - No spaces or special symbols allowed in a name
- Use descriptive names like
student_nameinstead ofx - Cannot use Python's reserved keywords as variable names
- Names are usually written in lowercase with underscores (snake_case)
item = "Notebook" price = 50 quantity = 3 discount = 10 subtotal = price * quantity discount_amount = subtotal * discount / 100 final_price = subtotal - discount_amount print("Item:", item) print("Quantity:", quantity) print("Subtotal:", subtotal) print("Discount:", discount_amount) print("Final price:", final_price)
Click Run to see the output.
5. Python Data Types
Numbers and Boolean
Python handles numeric data in two main forms, integers for whole numbers and floats for numbers that include decimal points, and it automatically figures out which one you're using based purely on how the value is written. Boolean is another essential built-in type, but instead of holding numeric or text data, it only ever holds one of two possible values, True or False. Booleans might look deceptively simple at first glance, but they become extremely important the moment you start writing conditions, comparisons, or any kind of decision-making logic. Almost every decision your program ends up making ultimately resolves down to a single True or False result somewhere behind the scenes. Getting comfortable distinguishing clearly between these basic types early on is a necessary step before tackling more advanced Python Basics topics like loops and conditionals. Even experienced programmers rely on this same foundation constantly, just in far more complex combinations.
Strings
Strings are sequences of characters used to represent text, and they're created simply by wrapping content inside either single or double quotation marks. A string can be as short as a single letter or as long as an entire paragraph of text, which makes it one of the most flexible data types available anywhere in Python. Strings can also be joined together using the plus symbol, a process commonly known as concatenation, which is especially useful for building dynamic, personalized messages out of separate pieces of text. Since text-based data shows up absolutely everywhere in real programs, from usernames to file names to error messages, becoming genuinely comfortable working with strings early on pays off throughout your entire programming journey. Strings also support many built-in operations that make manipulating text far easier than it would otherwise be. This makes them one of the very first data types every beginner needs to feel confident using.
Basic type checking with type()
Sometimes you genuinely need to confirm exactly what type of data a particular variable is holding, and Python's built-in type() function makes this remarkably effortless. Passing a number into it will return int or float depending on the value, while passing a piece of text will return str, instantly clearing up any confusion about what you're actually working with. This is especially useful for beginners who are still training themselves to recognize different data types just by glancing at values in their code. It also doubles as a genuinely handy debugging tool, since a surprising number of beginner errors ultimately trace back to a value being a completely different type than what was originally expected. Making type() a regular habit early on will smooth out a lot of unnecessary frustration later, especially once your programs start mixing several different data types together.
type(10)→ inttype(10.5)→ floattype("hello")→ strtype(True)→ booltype([1, 2, 3])→ list- Full reference in the official Python data types documentation
name = "Kundan" age = 15 height = 5.6 is_learning = True languages = ["Python", "JavaScript"] print("Name:", name) print("Age:", age) print("Height:", height) print("Learning:", is_learning) print("Languages:", languages) print("Name type:", type(name).__name__) print("Age type:", type(age).__name__) print("Height type:", type(height).__name__)
Click Run to see the output.
6. Python Input and Output
print() function
The print() function is usually the very first thing beginners ever learn in Python, since it's responsible for displaying output directly on the screen for the user to see. You simply place whatever you want shown, whether that's text, numbers, variables, or some combination of them separated by commas, inside its parentheses. It's an absolutely essential tool for checking what your program is actually doing at each individual step, especially while debugging unexpected or confusing behavior. Print statements let you peek inside your program's logic in real time, rather than guessing blindly about what might be happening internally. Almost every Python program you will ever write, regardless of how advanced it eventually becomes, will use print() somewhere to communicate results back to the user or developer. It remains one of the simplest yet most genuinely useful tools throughout your entire coding journey.
input() function
The input() function allows your program to collect information directly from the user while it's actively running, which is exactly what makes a program feel truly interactive rather than static and predictable. When Python's interpreter reaches an input() call, it pauses execution completely and waits patiently until the user types something and presses enter. One important detail that beginners very often miss is that whatever the user types is always stored internally as a string, even if it visually looks like a plain number. This means numeric input always needs to be explicitly converted before any math can be performed on it correctly. Combining input() together with variables is genuinely enough to build simple but engaging interactive programs fairly early in your Python Basics journey. It's a small function that opens the door to a huge range of practical, real-world program ideas.
Displaying user input
Once input() successfully collects information from the user, you'll usually want to display it back to them in a clear, well-formatted way rather than leaving it invisible. This typically means storing the collected input inside a variable first, then using print() afterward to display it alongside some additional explanatory text. If the input represents a number and you're planning to perform calculations with it later, you'll need to convert it explicitly using either int() or float() before attempting any math. Skipping this conversion step is a genuinely common beginner mistake that leads to confusing errors or completely unexpected results. This complete cycle of asking, storing, and then displaying input forms the real backbone of nearly every interactive Python program you'll ever build, no matter how simple or complex it eventually becomes.
- Collect input:
name = input("Enter your name: ") - Convert if numeric:
age = int(input("Enter your age: ")) - Convert decimal input:
price = float(input("Enter price: ")) - Display it:
print("Hello,", name) - Combine text and variables in one print statement
- Always convert before doing math on user input
See the official input() documentation for more details.
name = "Kundan" marks = 87 total_marks = 100 percentage = (marks / total_marks) * 100 print("Student Report") print("--------------") print("Name:", name) print("Marks:", marks, "/", total_marks) print("Percentage:", percentage, "%") if percentage >= 50: print("Result: Passed") else: print("Result: Failed")
Click Run to see the output.
7. Python Operators
Arithmetic operators
Arithmetic operators let Python perform genuine mathematical calculations directly on numbers, functioning essentially like a fully built-in calculator ready to use at any moment. The plus symbol handles addition, the minus symbol handles subtraction, and the asterisk symbol handles multiplication between two or more numeric values. The forward slash performs division and always returns a float value, even when dividing two whole numbers evenly. There's also a double asterisk used specifically for exponents, letting you raise one number to the power of another with ease. The percentage symbol represents modulus, which returns only the remainder left over after a division operation completes. These operators work directly on values stored inside variables, which is exactly how you'd go about building calculators, unit converters, or genuinely any program that involves meaningful mathematical logic.
+addition-subtraction*multiplication/division (always returns a float)**exponent, used for powers%modulus, the remainder of a division
Comparison operators
Comparison operators compare two separate values against each other and always return either True or False as their final result, nothing else. Common examples include double equals, which checks whether two values are actually equal to one another, and exclamation-equals, which checks the exact opposite condition instead. Symbols like greater-than and less-than compare the relative size of two numeric values directly against each other. Greater-than-or-equal-to and less-than-or-equal-to extend this further by allowing the comparison to also match when both values happen to be identical. For instance, checking whether someone's age is greater than or equal to eighteen is a simple, practical way to determine whether they qualify as an adult. You'll rely on comparison operators constantly the moment you begin writing conditional statements and loops, since nearly every condition in Python ultimately boils down to one of these comparisons happening behind the scenes.
==equal to!=not equal to>greater than<less than>=greater than or equal to<=less than or equal to
Logical operators
Logical operators let you combine multiple separate conditions together into a single, more powerful overall statement rather than checking each one individually. Python provides exactly three of these: and, which strictly requires every single condition involved to be true before the whole statement evaluates as true. The or operator is far more lenient, only requiring at least one condition among several to be true for the overall result to succeed. The not operator works differently altogether, simply flipping whatever result it's given, turning True into False or False back into True instantly. These operators become particularly useful the moment you need to check several separate things simultaneously, such as verifying that a user's age is above eighteen while also confirming their account is currently active before granting them access to something. Mastering these three operators unlocks noticeably more realistic and sophisticated decision-making logic within your programs.
and— every condition must be trueor— at least one condition must be truenot— flips True to False or False to Truein— checks membership inside a collectionis— checks if two variables refer to the same object
Full reference: official Python operator summary.
8. Python Strings
Creating strings
Creating a string in Python is as simple as wrapping a piece of text inside either single or double quotation marks, and both approaches work completely identically in practice. The choice between them usually comes down purely to personal preference, or occasionally to avoiding conflicts whenever your text itself already contains a quotation mark somewhere inside it. For longer blocks of text that need to span multiple separate lines, triple quotes come in especially handy and preserve every line break exactly as originally written. Strings can be stored inside variables just like numbers can, letting you reuse and manipulate the very same piece of text repeatedly throughout your program without ever needing to retype it. This underlying flexibility is exactly why strings end up being one of the most heavily used data types across the entirety of Python Basics, appearing in nearly every program you'll ever write.
String indexing and slicing
Every single character inside a string has its own specific position, formally known as an index, and counting always begins from zero rather than starting at one like you might initially expect. Slicing allows you to extract just a portion of a larger string by carefully specifying both a starting position and an ending position within it. This becomes incredibly useful whenever you only need a small part of a much longer piece of text rather than the entire thing at once. Python also fully supports negative indexing, where negative one refers directly to the very last character in the string, negative two refers to the second-to-last character, and so on backward from the end. This negative indexing trick becomes a genuinely handy shortcut whenever you don't feel like manually counting characters from the very front of a long string. Mastering both indexing and slicing together gives you remarkably precise, fine-grained control over text data throughout all of your programs.
text[0]— first charactertext[0:3]— first three characterstext[2:]— everything from index 2 onwardtext[-1]— last charactertext[::-1]— reverses the entire string
Common string methods
Python includes a wide range of extremely useful built-in string methods that handle common everyday text tasks without requiring any real extra effort on your part. The upper method instantly converts an entire string to uppercase letters, while the lower method does the exact opposite and converts everything to lowercase instead. The strip method removes any extra whitespace sitting at the very start and end of a string, which proves especially useful when cleaning up messy user input before processing it further. The replace method lets you swap out one specific part of a string for something else entirely, which is great for quick text corrections or substitutions. The split method breaks a single string apart into a full list of smaller pieces based on whatever separator character you choose to specify. Together, these small but genuinely powerful built-in tools save an enormous amount of manual, repetitive work whenever you're handling text-based data inside your programs.
.upper()/.lower()— change letter case.strip()— remove extra spaces.replace(old, new)— swap text.split()— break into a list.join()— combine a list back into a string.find()— locate a substring's position
Full list in the official string methods documentation.
9. Python Conditional Statements
if statement
The if statement is fundamentally how Python makes decisions based on whether a particular condition evaluates to true or false at runtime. The block of code sitting underneath an if statement only ever actually runs when that specific condition genuinely holds true at that exact moment. This single concept ranks among the most important building blocks in all of programming, since real-world logic almost never behaves the exact same way regardless of the situation at hand. Without if statements available, a program would be forced to execute in an identical way every single time it ran, completely regardless of whatever data or input it happened to receive. Learning to write clear, precise, and genuinely well-thought-out conditions is a real milestone in understanding Python Basics properly. Once this concept clicks, an enormous number of other programming ideas start to make far more intuitive sense as well.
if-else
The if-else structure is specifically designed to handle two distinct possible outcomes at the same time, one path reserved for when a condition turns out true, and a completely separate path for when it turns out false instead. For example, you could check cleanly whether a given number is even or odd, printing one particular message whenever the condition genuinely matches, and printing an entirely different message through the else block whenever it doesn't match at all. This structure guarantees that your program will always produce some defined, predictable response no matter what input it happens to receive, rather than silently doing absolutely nothing when a condition unexpectedly fails to hold. This particular pattern is extremely common in real code and will show up repeatedly in virtually every meaningful Python program you ever end up writing throughout your entire programming journey.
if-elif-else
Whenever there are genuinely more than just two possible outcomes that need to be handled properly, Python's if-elif-else structure lets you check through several separate conditions in one single, clean, and well-organized sequence. Python evaluates each individual condition strictly from top to bottom in order, and the very moment one of them is found to be true, it immediately runs that specific block of code and then automatically skips over every single remaining condition that follows afterward. This approach neatly avoids the genuinely messy, deeply nested if statements that would otherwise become absolutely necessary if you tried handling the exact same logic using only basic if statements alone. Keeping your logic readable this way remains possible even as the total number of potential outcomes continues growing larger and larger. Mastering this particular structure genuinely unlocks the ability to build far more realistic, dynamic programs that respond intelligently to many different real-world situations.
10. Python Loops
for loop
A for loop repeats a chosen action either a specific, predetermined number of times, or exactly once for every single item sitting inside some larger collection, such as a list or a string of characters. This fundamentally eliminates any real need to manually repeat the exact same line of code over and over again by hand throughout your program. For loops become especially powerful and genuinely essential the moment your programs start growing beyond just a small handful of simple lines. They're particularly useful when combined directly with lists, strings, or numeric ranges, since they let you automatically process an entire collection of data without writing separate code for each individual item. Understanding precisely how for loops actually work under the hood is genuinely one of the most valuable, frequently used skills you'll gain anywhere throughout learning Python Basics. Nearly every intermediate program eventually relies on this pattern somewhere.
while loop
A while loop keeps repeating its block of code for as long as some given condition continues to remain true, rather than running for a fixed, predetermined number of times the way a for loop typically does. This particular design makes it genuinely ideal for situations where you honestly don't know in advance exactly how many repetitions will actually be needed before the task completes. However, this flexibility comes bundled with a real and fairly common risk: if the condition somehow never actually becomes false at any point, the loop will continue running forever, effectively freezing your entire program in what's formally known as an infinite loop. Beginners should always carefully double-check that something meaningful inside the loop's own body genuinely updates the condition being checked, or else the program will simply never exit naturally on its own. Getting this detail right early on prevents a huge amount of confusing, hard-to-diagnose bugs later.
break and continue
The break statement immediately and completely stops a loop from running any further, even if its original condition happens to still technically remain true at that exact moment. This proves genuinely useful whenever you want to exit a loop early the very instant some specific goal has already been successfully reached, such as finally locating a target item somewhere inside a larger list. The continue statement behaves quite differently in comparison, since it only skips the current single iteration entirely and then jumps straight ahead to the very next one, without actually ending the surrounding loop altogether. Both of these tools together give you noticeably finer, more precise control over exactly how your loops behave in different real-world situations. Learning to use break and continue correctly and confidently can genuinely make your loops both far more efficient and far easier to read at the same time.
break— stops the loop entirelycontinue— skips to the next iteration
More examples in the official Python control flow tutorial.
11. Python Lists
Creating and accessing lists
A list in Python is simply a collection of individual items all stored together inside a single variable, created conveniently using square brackets around the values. Lists are genuinely flexible in that they can hold several completely different types of data all at once, including numbers, strings, or even entirely separate lists nested inside them. Individual items sitting inside a list are accessed directly using their specific index number, which, just like strings, always starts counting from zero rather than one. Lists rank among the most frequently used data structures throughout all of Python, largely because they let you group and manage genuinely related pieces of information together in one clean, organized place. This makes lists an absolutely core, foundational part of learning Python Basics properly, since they show up constantly across nearly every real program you'll eventually write, regardless of complexity or purpose.
Adding and removing items
Python makes it remarkably straightforward to modify an existing list even after it's already been fully created and populated with initial values. The append method adds a brand-new item directly onto the very end of an existing list, while the insert method lets you place a new item at any specific position you choose instead. The remove method deletes one particular value from the list entirely, based purely on matching its actual content rather than its numeric position. The pop method, on the other hand, removes an item based specifically on its numeric index position, and conveniently returns that removed value back to you as well. Together, these genuinely useful operations allow lists to grow and shrink dynamically while your program continues actively running, which proves essential for handling real-world data that constantly changes over time in unpredictable ways.
.append(item)— add to the end.insert(index, item)— add at a position.remove(item)— delete by value.pop(index)— delete by position.extend(list2)— add multiple items at once.clear()— remove every item from the list
Basic list methods
Beyond simply adding and removing individual items, Python lists also include several other genuinely useful built-in tools worth knowing well. The sort method rearranges every item inside the list into a proper, predictable order automatically, without requiring any manual comparison logic from you. The reverse method flips the entire current order of the list completely backward, from last item to first. The built-in len function, while technically not a list method itself, tells you exactly how many total items currently exist inside a given list, which proves extremely useful whenever looping through data. The index method helps you quickly locate the exact position of one specific item you're searching for within the list. Together, all of these small but genuinely powerful tools make lists one of the most flexible, practical, and heavily relied-upon data types throughout the entirety of Python Basics.
.sort()— arrange items in order.reverse()— flip the orderlen(list)— count items.index(item)— find a position.count(item)— count how many times an item appears.copy()— create a duplicate of the list
Full reference: official Python lists documentation.
12. Python Tuples and Sets
What is a tuple?
A tuple behaves quite similarly to a regular list in many respects, except for one crucial difference: once it's been created, its contents can never actually be changed afterward, a property formally known as being immutable. Tuples are written using ordinary parentheses instead of the square brackets used for lists, which visually distinguishes them at a glance in your code. Because their values genuinely can't be modified once set, tuples are commonly used to store fixed, permanent data that should never accidentally change midway through a running program, such as geographic coordinates or fixed configuration settings. Despite being unchangeable in this way, individual values sitting inside a tuple can still be accessed normally using indexing, exactly the same way you would with a regular list. Understanding tuples properly helps you make better, more deliberate decisions about exactly which data structure genuinely fits your specific situation, depending on whether your data truly needs to remain constant.
What is a set?
A set is a collection that automatically removes any duplicate values the moment they're added, which guarantees that every single item sitting inside it is genuinely unique with absolutely no repeats allowed. Sets are written using curly braces, and unlike both lists and tuples, they deliberately don't preserve any particular fixed order among the items they contain. This makes sets especially useful whenever you need to quickly check whether a particular value already exists somewhere inside a larger collection of data. They're equally valuable for efficiently cleaning duplicate entries directly out of a messier, larger dataset without writing extra logic yourself. Because sets enforce this strict uniqueness completely automatically behind the scenes, they end up being a remarkably fast and efficient tool for this one particular category of task within Python Basics, even though they're used less frequently overall than lists or dictionaries.
Basic difference between lists, tuples and sets
Lists, tuples, and sets all technically store collections of related data together, yet each one behaves quite differently from the other two in genuinely important ways. Lists remain both ordered and fully changeable, meaning you're completely free to add, remove, or modify individual items whenever you genuinely need to. Tuples stay ordered as well, but critically remain unchangeable once created, which makes them ideal specifically for fixed data that should never be altered accidentally later on. Sets, meanwhile, are deliberately unordered and automatically eliminate any duplicate entries, which makes them genuinely ideal for uniqueness checks rather than for maintaining any particular sequence of items. Ultimately, deciding which of these three structures to actually use in a given situation comes down entirely to what kind of data you're working with, and precisely how you intend to use and manipulate it going forward.
- Lists — ordered and changeable
- Tuples — ordered but unchangeable
- Sets — unordered, automatically unique
Learn more in the official Python tuples and sets guide.
Practical example
Reading the theory is one thing, but watching it happen in front of your eyes is a completely different experience. The code below demonstrates how tuples store fixed, unchangeable sequences while sets automatically filter out duplicate values. Hit Run Code to watch the data structure operations execute live
13. Python Dictionaries
Creating a dictionary
A dictionary in Python stores its data as organized key-value pairs rather than simply holding single standalone values the way a basic list would. It's created using curly braces, where each individual key gets paired directly with its own corresponding value, quite similar conceptually to how a word in a real physical dictionary gets paired with its written definition. This particular structure proves extremely useful whenever you genuinely need to store several closely related pieces of information together in one single, well-organized place, such as a student's name sitting right alongside their age and current grade. Dictionaries make data noticeably easier to understand, manage, and reason about compared to the alternative of juggling several completely separate, disconnected lists at once. This is precisely why dictionaries are widely considered to be one of the single most powerful and genuinely useful tools available anywhere throughout all of Python Basics.
Accessing keys and values
Once a dictionary has already been created, you can retrieve any specific value simply by referring directly to its associated key, which turns out to be far more intuitive overall than trying to remember arbitrary numeric positions the way you would with a plain list. Python also conveniently provides built-in methods like keys, which retrieves every single key stored inside the dictionary at once, and values, which does the exact same thing but for every stored value instead. Attempting to access a key that genuinely doesn't exist inside the dictionary will cause Python to immediately raise an error, so it's important to always double-check spelling and overall accuracy whenever working directly with dictionary keys in your code. This particular key-based access pattern is exactly what makes dictionaries so remarkably efficient for organizing genuinely structured, real-world data throughout your programs.
Adding, updating and removing items
Dictionaries remain genuinely highly flexible in practice, since simply assigning a value to a brand-new key automatically adds that entire pair to the dictionary without any extra steps required. If that same key already happens to exist beforehand, this exact same approach will instead update its existing value rather than mistakenly creating an unwanted duplicate entry. To remove an item completely from a dictionary, you can use either the del keyword directly, or alternatively the pop method, specifying precisely which key you'd like removed from the collection. This underlying flexibility makes dictionaries especially well suited for managing genuinely dynamic data that changes frequently over time, such as evolving user profiles, adjustable settings, or actively changing application state within a running program.
student["grade"] = "A"— add or update a valuedel student["grade"]— remove a keystudent.pop("grade")— remove and return a value
Full guide: official Python dictionaries documentation.
Practical example
Understanding how key-value pairs work makes organizing complex data effortless. The code below creates a student dictionary, accesses values by key, adds a new grade entry, and removes old data fields—all in real time. Hit Run Code to see how Python manages dynamic records
14. Python Functions
What is a function?
A function is essentially a reusable block of code specifically built to perform one clearly defined task, and once it's been properly written a single time, you never genuinely need to rewrite that same underlying logic ever again. Instead of repeating identical lines of code scattered repeatedly throughout an entire program, you simply call the function directly wherever that particular task actually needs to happen. This approach keeps programs noticeably shorter overall, far better organized internally, and considerably easier to maintain properly as they continue growing larger and more complex over time. Functions also make debugging significantly simpler in practice, since fixing an underlying bug only ever requires updating the code in one single, centralized place rather than hunting down every single repeated copy scattered throughout the codebase. Genuinely understanding functions properly marks a real turning point in becoming truly comfortable with Python Basics as a whole.
Creating and calling functions
You create a function in Python using the def keyword, immediately followed by a chosen descriptive name and a pair of parentheses, with the function's actual code indented cleanly underneath that first line. Once a function has been properly defined this way, it can then be called from absolutely anywhere else in your program simply by writing its name followed by parentheses once again. This clean, deliberate separation between defining a function and later calling it lets you thoughtfully organize your program's overall logic well before you actually run any of it for real. A single function can be called as many separate times as genuinely needed throughout an entire program without ever requiring it to be rewritten again from scratch. This underlying reusability is precisely what makes functions such a remarkably powerful tool for keeping your code efficient, consistent, and genuinely maintainable over time.
Parameters and return values
Functions become significantly more powerful and genuinely flexible the moment parameters are properly introduced into the picture, since they allow specific information to be passed directly into the function itself rather than hardcoding one single, fixed behavior permanently. A return statement then lets the function send a meaningful result back to wherever it was originally called from in the first place, meaning functions can not only perform some action, but can also calculate something and hand back a genuinely useful value afterward. This powerful combination of parameters working together alongside return values is precisely what transforms simple functions from basic shortcuts into truly flexible, reusable tools you'll continue relying on constantly throughout your entire Python Basics journey and well beyond it.
def greet(name):— defines a function with a parameterreturn name— sends a value back to the caller
Full reference: official Python functions documentation.
Practical example
Instead of repeating code, functions allow you to write clean logic once and run it whenever needed. The code below defines custom functions that accept input parameters, execute operations, and return calculated results back to your application. Hit Run Code to watch the inputs get processed
15. Python Errors and Exception Handling
Common beginner errors
Beginners genuinely tend to run into a fairly predictable, recurring set of errors while first learning Python, and learning to recognize them quickly saves an enormous amount of unnecessary frustration down the road. Indentation errors happen specifically when spacing inside the same code block isn't kept properly consistent throughout. Syntax errors occur whenever code directly breaks one of Python's fundamental grammar rules, such as accidentally forgetting a required colon somewhere important. Name errors show up when you attempt to use a variable that was genuinely never actually defined beforehand, very often simply due to a small, easy-to-miss typo somewhere in the code. Type errors occur specifically when you try performing some operation on two genuinely incompatible data types together, such as mistakenly attempting to add a plain string directly to a number. Learning to read Python's own error messages carefully and patiently is a genuinely valuable skill that improves remarkably quickly with regular, consistent practice over time.
- Indentation errors — inconsistent spacing
- Syntax errors — broken grammar, like a missing colon
- Name errors — using an undefined variable
- Type errors — mixing incompatible data types
Syntax errors vs runtime errors
Syntax errors occur specifically when your code directly breaks one of Python's fundamental writing rules, and critically, the program won't even actually begin running at all until that particular mistake gets properly fixed first. Runtime errors, by clear contrast, happen instead while the program is already actively running, even though the underlying code itself was technically written with completely correct syntax to begin with. Dividing a number by zero, for example, remains perfectly valid Python syntax on paper, yet it still reliably causes a genuine runtime error simply because it's mathematically impossible to actually compute. Understanding this important distinction clearly helps you know precisely where to look whenever something eventually goes wrong somewhere inside your program. Syntax errors in particular tend to be considerably easier to fix overall, since Python typically points directly to the exact line causing the underlying problem right away.
Basic try and except
Python thankfully lets you handle runtime errors quite gracefully using dedicated try and except blocks, rather than simply allowing your entire program to crash unexpectedly without warning. Any genuinely risky code that might potentially fail gets placed neatly inside the try block, and if an error does happen to occur while it's actively running, Python immediately jumps straight over to the matching except block instead of abruptly stopping the whole program outright. Wrapping a division operation this particular way, for instance, lets you cleanly catch a divide-by-zero error and display a genuinely friendly, understandable message to the user instead of an intimidating crash. Learning basic exception handling reasonably early on makes your overall Python Basics knowledge considerably more practical and genuinely useful for handling real, unpredictable, real-world situations later on.
try:— code that might failexcept:— runs if an error occurs
Full guide: official Python errors and exceptions documentation.
Practical example
Runtime errors can crash your program if left unhandled, but smart exception blocks keep everything running smoothly. The code below places a division operation inside a safety net to catch zero-division errors gracefully without interrupting execution. Hit Run Code to see error handling in action
16. Basic File Handling and Practical Python
Opening and reading a file
Python lets you interact directly with files stored on your computer using the built-in open function, which becomes genuinely essential whenever a program needs to work with previously saved data instead of just information typed manually by hand each time. Opening a file specifically in read mode lets you then use the read method to pull its entire stored content into your program as one continuous string of text. It remains genuinely important to properly close a file once you're completely finished working with it, and using a with statement is generally the recommended, safer approach, since it automatically closes the file for you even if an unexpected error happens to occur partway through the process. File handling represents a genuinely practical, real-world skill that meaningfully bridges basic coding concepts together with actually useful, real applications people build every day.
open("data.txt", "r")— open in read mode.read()— pull the file's content into your program- Use
with open(...) as f:so the file closes automatically
Writing basic data to a file
Just as Python allows reading data from existing files, it equally allows writing brand-new data directly into one using write mode instead. If the specific target file doesn't already exist on disk beforehand, Python will simply go ahead and create it automatically without requiring any extra steps from you. Using append mode instead of regular write mode lets you add fresh new content onto the very end of an existing file without accidentally erasing whatever data was already saved there previously. This underlying ability to permanently store data somewhere persistent is precisely what allows genuine Python programs to move beyond purely temporary, in-memory results and become truly useful, lasting tools people can rely on repeatedly.
open("data.txt", "w")— write mode (overwrites)open("data.txt", "a")— append mode (adds on)
Full guide: official Python file handling documentation.
Creating small beginner-friendly Python programs
Once all these individual fundamentals start feeling genuinely comfortable together, the natural next step becomes combining them thoughtfully into small, genuinely practical programs of your own design. A basic calculator, a simple personal to-do list, or a small program that checks whether a given number happens to be prime are all excellent, approachable beginner-level projects worth attempting early on. These small builds naturally combine variables, loops, conditions, and functions all together at once, giving you a genuine, hands-on chance to apply absolutely everything covered throughout this entire Python Basics guide in one cohesive place. Even genuinely simple projects like these help important concepts stick far more effectively than passive reading alone ever really could. Starting deliberately small and then gradually increasing complexity over time remains the single most effective, proven way to build real, lasting Python skills that actually last.
Practical example
Real-world applications frequently save and retrieve data from disk using file operations. The code below uses Python's with open() manager to write text directly to a file and read its contents back out safely. Hit Run Code to watch the file handling workflow execute
Common Beginner Mistakes in Python Basics
Inconsistent indentation remains one of the most frequent beginner mistakes, since Python treats it as a hard, unavoidable error rather than a simple, forgivable style issue the way many other languages might. Another extremely common mistake involves forgetting that the input function always returns plain text, and skipping the necessary conversion step before attempting to do actual math with that value. Beginners also frequently confuse the single equals sign used for assignment with the double equals sign used for comparison, which quietly leads to confusing, unexpected results later. Forgetting the required colon at the end of if statements, loops, or function definitions is another remarkably frequent slip-up that trips up newcomers constantly. Lastly, many new coders genuinely try to absorb far too many concepts all at once instead of patiently practicing each individual one separately, which noticeably slows down real, lasting understanding over time.
- Inconsistent indentation
- Forgetting to convert
input()before doing math - Confusing
=with== - Forgetting the colon after if/for/while/def statements
- Trying to learn too many concepts at once
Best Practices for Learning Python Basics
The single best way to genuinely learn Python Basics properly is by actually writing code yourself consistently, rather than only passively reading through explanations or simply watching tutorials without ever typing anything out. Practicing just a little bit every single day tends to build noticeably stronger, more lasting habits compared to occasional, long, exhausting study sessions crammed together infrequently. Breaking larger problems down deliberately into smaller, more manageable steps makes even genuinely complex tasks feel far more approachable and achievable for a beginner just starting out. Reading error messages carefully and patiently, rather than simply ignoring them out of frustration, will teach you to debug your own code considerably faster over time as you gain real experience. Finally, building small personal projects of your own, even genuinely simple ones, helps reinforce what you've actually learned far more effectively than passive memorization alone ever could.
- Write code yourself instead of only reading or watching tutorials
- Practice a little every day
- Break problems down into smaller steps
- Read error messages carefully
- Build small personal projects
For a deeper structured path, see the official Python tutorial.
Practice Tasks for Python Basics
Try writing a small program that asks for the user's name and age, then prints back a genuinely personalized greeting using both of those collected values together. Create a simple calculator that accepts two numbers from the user and correctly performs addition, subtraction, multiplication, and division between them. Write a short program that checks cleanly whether a number entered by the user happens to be even or odd, using a straightforward if-else statement. Build a small list containing your favorite movies, then use a for loop to print each individual title out one at a time. Finally, create a dictionary specifically designed to store a student's personal details, then write additional code that updates and neatly displays that information afterward.
- Ask for name and age, then print a personalized greeting
- Build a simple calculator (add, subtract, multiply, divide)
- Check if a number is even or odd
- Print a list of favorite movies using a for loop
- Store and update a student's details in a dictionary
Try these interactively on Replit without installing anything.
Frequently Asked Questions About Python Basics
Summary and Conclusion
This guide covered every essential building block of Python Basics, starting from installation and syntax all the way through variables, data types, operators, strings, conditionals, loops, lists, tuples, sets, dictionaries, functions, error handling, and basic file operations. These fundamentals aren't isolated, disconnected topics on their own, they genuinely form the entire foundation that every single advanced Python skill is eventually built upon, whether that's web development, automation, or data science down the line. The real key going forward is staying consistent with practice, building small personal projects along the way, and gradually taking on new, slightly harder problems as your confidence naturally grows over time. With this genuinely strong base in Python Basics now in place, you're fully ready to explore more advanced areas of Python with real, well-earned confidence.
Conclusion
By now, you should have a solid understanding of how Python Basics work and how each concept connects to build complete, functional programs. These fundamentals aren't just standalone topics, they form the foundation that every advanced Python skill is built upon, whether that's web development, automation, or data science. The key going forward is consistent practice, building small projects, and gradually challenging yourself with new problems. With this strong base in Python Basics, you're now ready to explore more advanced areas of Python with confidence.
