Frequently Asked Questions
Variables in Python
Is True the same as 1 in Python?
Sort of. Booleans are technically a subtype of integers in Python, so true equals 1 and False equals 0 when used in math. Try print (True + True) and you’ll get 2. Odd, but worth knowing.
How do you delete a variable in Python?
Use the
delstatement:del variable_name. After deletion, attempting to access the variable raises aNameError. This is useful for freeing memory or removing a name from scope intentionally.What is the difference between == and is for variables?
==checks if two variables have the same value, whileischecks if they point to the same object in memory. For example,[1,2] == [1,2]isTrue, but[1,2] is [1,2]isFalsebecause they are two different list objects. Useisonly when checking identity (e.g.x is None).Can Python variables change type after assignment?
Yes. Python allows reassigning a variable to a completely different type —
x = 5followed byx = "hello"is valid. This is called dynamic typing. While flexible, it can reduce readability, so use type hints and keep variable roles consistent.What is the difference between a local and a global variable?
A local variable exists only inside the function where it is created and cannot be accessed outside. A global variable is defined at the module level and can be read anywhere in the file. To modify a global variable inside a function, use the
globalkeyword.Does Python require you to declare a variable type?
No. Python is dynamically typed, so you simply assign a value and Python infers the type automatically. You can optionally add type hints (
x: int = 5) for readability and tooling support, but they are not enforced at runtime.
Data Types in Python
Why does “5” + 5 throw an error but “5” + “5” doesn’t?
Because
+means something different depending on the type. Between two strings, it joins them together ("55"). Between a string and an integer, Python doesn’t know what you want, so it refuses rather than guessing wrong.What’s the difference between int and float?
An int has no decimal point (
10), a float does (10.0). Even10.0is treated as a float, not an int, despite looking like a whole number.Can a variable change its data type later?
Yes, and this actually happens a lot in real code. If x=5 and later you write x=”five”, Python doesn’t complain. x is now a string. This flexibility is convenient, but it can also cause bugs if you lose track of what a variable currently holds.
Do I need to tell Python what data type a variable is?
No. Python figures it out automatically based on the value you assign. This is called dynamic typing. Languages like C or Java make you declare the type upfront; Python doesn’t.
Type Casting in Python
Is str() basically the reverse of int()?
Close enough for daily use. str() will turn almost anything into text without complaint. int() and float() are pickier, they only work if what you’re converting actually resembles a number.
Does int() round decimals or just cut them off?
It cuts them off. int(3.9) gives you 3, not 4. If you want rounding, use round() instead, a different function entirely.
What happens if I run int(“hello”)?
ou get a ValueError. int() can only convert text that actually looks like a number. Feed it a word and it has nothing to work with.
Why does input() always return a string, even for numbers?
Python has no way to know if you typed “42” meaning a number or meaning text. String is the safe default. Converting is left to you.
Conditional Statement in Python
Can a condition inside an if statement be something other than a comparison?
Yes. Any expression that evaluates to
TrueorFalsecan be used, including variables that hold Boolean values directly, such asif is_eligible:instead ofif is_eligible == True:.Why does my if block give an IndentationError?
Python requires the code inside an
if,elif, orelseblock to be indented consistently, usually by four spaces. Mixing tabs and spaces, or forgetting to indent at all, causes this error.What’s the difference between using elif and writing separate if statements?
With
elif, Python stops checking as soon as one condition is true. With separateifstatements, Python checks every single one independently, even after finding a match, which can lead to more than one block running when you only wanted one.Can I use elif without an else?
Yes. The
elseblock is optional. You can write anif-elifchain without a finalelseif there’s no need for a default action.What happens if none of the conditions in an if-elif-else chain are True?
The
elseblock runs, if one is provided. If there is noelseblock and every condition isFalse, the program simply skips the entire structure and continues with the next line.
For loop
Is the else clause on a for loop commonly used in real programs?
Not particularly often, but it does show up in textbooks and exams. It’s worth knowing it exists, even if you rarely reach for it in everyday code.
What does range(2, 10, 2) actually generate?
It starts at
2, stops before reaching10, and increases by2each step, producing2, 4, 6, 8.Can a for loop iterate over something other than numbers?
Yes. A
forloop can iterate over any sequence, including strings, lists, tuples, and later, dictionaries, not just numeric ranges.What is the difference between break and continue?
breakexits the loop completely, and no further iterations run.continueskips only the current iteration and allows the loop to continue with the next value.Does range(5) include the number 5?
No.
range(5)generates0, 1, 2, 3, 4, five numbers total, but stops one short of5. This trips up nearly every beginner at least once.
While loop
Why did my password-checking loop run forever even after I typed the right password?
Probably a typo mismatch, extra space, wrong capitalization, or you compared with
=instead of==. Print the variable right before the condition check if you’re stuck; it usually reveals the problem immediately.Is while True a bad practice?
Not at all, as long as there’s a clear
breakcondition inside. It’s actually a very common pattern for things like menus or repeated prompts where you don’t know the exact number of repetitions in advance.Can I use else with a while loop, like with for loops?
Yes. The
elseblock runs if the loop finishes normally, meaning the condition became false on its own, but not if abreakstatement stopped it early.How do I avoid creating an infinite loop by accident?
Make sure whatever variable your condition depends on actually changes inside the loop body. If you’re using
while Trueon purpose, always pair it with abreakstatement somewhere inside.What happens if the condition in a while loop is never true to begin with?
The loop body never runs, not even once. Python checks the condition first, and if it’s already
False, it skips straight past the loop entirely.
List in Python
Is sort() the same as sorted()?
No, and this confuses people. sort() modifies the list in place and returns nothing. sorted() returns a brand new sorted list and leaves the original exactly as it was.
What happens if I try to access an index that doesn’t exist?
Python throws an IndexError. If your list has 3 items, valid indexes are 0, 1, and 2, trying fruits[3] will crash your program.
Can a list contain another list?
Yes. Lists can hold other lists, this is sometimes called a nested list, and it’s how you’d represent something like a grid or a table. That’s a more advanced topic worth exploring once you’re comfortable with basic lists.
What’s the difference between remove() and pop()?
remove() deletes an item by its value, you tell it what to remove, not where. pop() deletes by position, and also returns the removed item, which remove() doesn’t do.
Why does fruits[0] give the first item instead of fruits[1]?
Python, like most programming languages, starts counting positions at 0, not 1. The first item sits at index 0, the second at index 1, and so on.
Tuples in Python
How do I add an item to a tuple if tuples can’t be changed?
You can’t add directly. Convert the tuple to a list with
list(), make your changes, then convert it back to a tuple withtuple().Can I loop through a tuple the same way as a list?
Yes, a regular for loop works exactly the same on both.
Why does (“apple”) not create a tuple?
Because round brackets alone don’t signal a tuple to Python, they’re also used for grouping expressions. The comma is what actually makes it a tuple, so a single-item tuple needs a trailing comma:
("apple",).Why would I ever use a tuple instead of just using a list?
When you want to make sure the data can’t be accidentally changed later in your program. It’s a way of telling both Python and anyone reading your code that these values are fixed.
What’s the actual difference between a list and a tuple?
A list can be changed after creation, items added, removed, or updated. A tuple cannot. Once you create a tuple, its contents are locked in.
Dictionary in Python
What’s the difference between del and pop() when removing a key?
delremoves the key and gives you nothing back.pop()removes the key and returns its value, so you can use that value elsewhere in your code if needed.Do dictionaries keep their items in a specific order?
As of modern Python versions, yes, dictionaries preserve the order items were added in. That said, you should still access items by key rather than relying on position, since that’s what dictionaries are designed for.
Can a dictionary value be a list or another dictionary?
Yes. Dictionary values can be any data type, including lists, tuples, or even other dictionaries. This is common once you start working with more complex, real-world data.
What happens if I access a key that doesn’t exist?
Python raises a KeyError and your program stops, unless you catch the error. Using
.get()instead avoids this, since it returns None (or a default value you specify) rather than crashing.What’s the real difference between a list and a dictionary?
A list stores values in order and you access them by position, index 0, 1, 2. A dictionary stores values by a key you choose yourself, name, age, whatever makes sense, and there’s no guaranteed position involved.
Python Sets
Can a set contain a list inside it?
No. Sets can only contain immutable items, numbers, strings, tuples, but not lists or dictionaries, since those can change and sets rely on items staying fixed to check uniqueness properly.
Why would I use intersection or union in a real program?
Common example: finding students enrolled in two different classes (
&), or combining two lists of email subscribers while automatically removing duplicates (|).What’s the difference between remove() and discard()?
remove()throws an error if the value isn’t in the set.discard()just does nothing in that case, no error, no crash. Usediscard()when you’re not sure the value exists.Can I access a set item using an index, like fruits[0]?
No. Since sets have no defined order, indexing doesn’t work on them. If you need to access items by position, use a list instead.
What’s the real difference between a set and a list?
A list keeps items in order and allows duplicates. A set has no guaranteed order and automatically removes duplicates. Use a set when uniqueness matters more than order.

