Python data types explained for interview questions and answers.

7.Can you compare strings in Python using comparison operators? How does Python perform this comparison?

Of course, one can compare strings using the following operators: == , !=, <, >, <=, > to say whether two strings are the same or different. Python, comparing the characters of the two strings from left to right and matching them with each other in alphabetical orders, checks here in fact using Unicode values behind the scenes.

Here is how it works :
1. To check whether two strings are equal or not:
To know if two strings are the same, use the operator == and for not the same operator != .
a = "apple"
b = "apple"
print(a == b) # True, because both are exactly the same
c = "banana"
print(a != c) # True, because "apple" and "banana" are different

2. Knowing which string comes first alphabetically:
Python allows comparisons in which a given string would come before or even after another, just like word definitions in a dictionary.
print("banana" > "apple") # True, because 'b' comes after 'a'
print("apple" < "banana") # True, because 'a' comes before 'b'
If the first letters are the same, he keeps looking at the next letters
3. Uppercase and lower case matter:
Comparating letters between upper and lower case is not an example using the print statement above as it proves true because of the capitalized letters.
Like this:
print("Apple" < "apple") # True, capital 'A' is considered smaller than lowercase 'a'
Such can affect results, so it is good to know when sorting or comparing words.

Summary:
Yes, one can compare strings in Python with the use of common symbols like == or <. Python makes comparisons letter by letter according to their order in the alphabet. Keep in mind capitals and small letters are not the same. This helps to sort names, check if two words are equal, or determine which one comes first in an alphabet list.


8.Explain the truth tables for the and, or and not operators.

1. and Operator
The and operator checks if both conditions are true. If even one is false, the whole result becomes false. Think of it this way:
You go outside only when the sun is shining and when you are free from obligations. If any one of those conditions is not true, you remain indoors.
Examples:
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
2. or Operator
An or operator is a logical operator that returns True if one or both conditions are true and returns False only when both the conditions are false.
Example in real-life situations:
If your friend is free or you are in the mood, you will see a movie; you don't need both things to happen-just one is enough.
Examples:
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
3. not Operator
The not operator inverts a value
If something is true, not makes it False.
If something is false, not makes it True.
Like a switch flipping.
Examples:
print(not True) # False
print(not False) # True
Quick Recap:
and = both must be true conditions
or = at least one must be true
not = change the value (true becomes false, and vice versa
These would come in handy while you are using conditions in if statements or combining rules in your Python code. They make your program smarter by deciding what should happen in different situations.
Let me know if you would like a couple more examples of the if statements at a beginner level?


9.Describe the concept of short-circuiting in logical and and or operations. Give an example where this is useful.

Short-Circuiting can be defined as a convenient feature within Python, especially when applied to logical operations with and or or operators. Whenever possible, the essence of short-circuiting is to avoid evaluating any of the subsequent conditions in a statement, thus leading to an early exit. This pipeline goes further to conserve time as well as prevent unwanted mishaps, maybe even errors, from occurring.

How It Works with and
As soon as Python finds one false condition, it will halt evaluation of the and expression; this is because and conditions must be true for the result to be true. If the first condition is false, the result is already known to be false regardless of the other conditions, and Python does not waste time checking them.
Example:
x = 0
if x != 0 and (10 / x) > 1:
  print("Condition met")
In this example, Python will not try to compute 10/x, which will crash with a divide-by-zero error because the first condition x != 0 is already false. Therefore, it will save you from crashing your code.
How It Works with or
In the case of or, Python stops checking as soon as it finds a true condition. After all, only one true condition is required for the entire statement to evaluate to true; therefore there is no need to check further.
Example:
user_logged_in = True
if user_logged_in or check_password():
  print("Access granted")
Here, as user_logged_in is already true, Python skips the call to check_password() since it knows that the whole condition is true.
Advantages of Short-Circuiting
They are useful since:
They can help avoid errors in your code.
Programs are made to run faster by not checking more than necessary.
It allows writing smart and safe code.


10.Write a Python condition that checks if a number n is both greater than 5 and less than 15.

In actual scenarios, we usually need to validate whether a number lies in a certain range or not. For instance, writing a program which checks whether a kid's age is between 6 and 14 for an event. Python can very easily handle this kind of check.
Let us take an example, if it is one variable called n, it holds a number.

To know if n is actually more than 5 and less than 15 we have:
if n > 5 and n < 15:
   print("n is between 5 and 15")
Here's what happens:
n > 5 checks if the number is greater than 5
n < 15 checks if the number is less than 15.
And tells Python that both the conditions must be true for the whole sentence to be.
If both conditions are true, then the message will be printed.

A More Pythonic Way
That condition can also be written in an easier and more natural way.
if 5 < n < 15:
  print("n is between 5 and 15")
Reading and comprehension are easier on this version. It does the exact same function as that, but cleaner. This chained comparison is one of Pythons friendly features.

This is How It Works:
n = 10
if 5 < n < 15:
  print("Yes, the number is within range.")
The number 10 is definitely between 5 and 15, hence the message will get printed.
But trying this gives:
n = 3
No output will be generated since 3 is not greater than 5.


11.What is the basic assignment operator in Python?

It is the equal sign (=) which is the primary assignment operator for use in Python.
Exposition:
You are assigning a variable a value when you use the = operator. This does not mean that you are saying two 'things' are equal as in mathematics; rather, you are telling Python to store a value inside a variable so that you can use it later.
Examples:
x = 10
name = "Alice"
In the case of the first statement, it assigns 10 to the variable named x.
The second statement assigns a string of characters "Alice" to a variable named name.
Thereafter, you would be able to use x and name anywhere in your application program.
The Importance:
This is one of the essential foundations in Python.
It is not possible to save and reuse data in the program without assignment.
Once a variable is assigned a value, it does not change until it is reassigned.
In Summary:
Basically, = is like putting something in a labeled box. Write score = 95, which means "Hey Python, remember that the score is 95."


12.Rewrite the statement x = x + 5 using a compound assignment operator.

The statement: x = x + 5 can also be rewritten using a compound assignment operator such that:
x += 5
Simple Explanation:
+= is simply a short method to tell Python that what ever the value on the right is to be added to the variable on left hand side and then the output result is to be stored back to the same variable.
Thus:
x = x + 5
and
x += 5
are both performing the same task - adding 5 to the value of x.

Why use it? - Making your code clean and short.
Much easy to read, especially with loops or math calculations.
Example:
x = 10
x += 5
print(x) # Output: 15


13. Explain the difference between x = 5 and x == 5.

Really important concept, those little symbols makes a lot of difference in Python as for x = 5 and x == 5, both look pretty similar, but they do entirely different things.
x = 5 — Assignment Operator
So it favours:
"The value of variable is to be set to 5."
You're assigning a value to the variable.
This operation would now allow the storage of a number in the x variable.

Example:
x = 5
print(x) # 5
x == 5 — Equality Comparison Operator
This explains:
"Find out whether the value held by x equals 5."
You are asking a question, not assigning value.
It will somewhat yield a True/False answer.
It normally features in if conditions or statements.

Example:
x = 5
print(x == 5) # Output: True
print(x == 10) # Output: False
In Simple Words:
= is like giving a value to a x.
== is like checking what's inside the x.

Summary:
Most beginners tend to write x = 5 when they should actually mean 'x == 5' in a condition. If either of the mistakes is made, Python will give an error or act strangely-and this is the mistake one should remember to avoid.


14.When would you use the is operator in Python? How does it differ from ==? Provide an example.

We use is when we want to see if both variables point to the very same object in memory-not if they are meant or whether they look fled or not, but to try to see if they are, in fact, the same object.

Now what is is about==?
== checks whether the values of two objects are the same.
is checks both objects against one another: whether they are a single object at the same location in memory.
The two can yield the same result at times but not always.

Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True — values are equal
print(a is b) # False — because they are two different list objects
Although both a and b look the same, they are stored at different places in memory-a is b is False.

Another Example:
x = None
print(x is None) # True — checks whether something is None (a special object in Python)
This common way is also the recommended way of checking if a variable is none.

Summary:
Use == while you compare whether values are the same. Use is to check whether two variables refer to one and the same object.


15.Explain the concept of object identity and how it relates to the id() function.

In Python, everything is an object: be it numbers or strings, lists or even functions! Object identity is the term that states that the object occupies a region in memory wherein the object is assigned with its present identity in time and really refers principally to an identity as being fingerprinting. It speaks of where the object is in memory and not what is inside it.
Hence these two different variables binding to the same value will not differ from being the same objects.

How does python check object identity?
To verify if two variables refer to the identical object, Python utilizes the is operator.
Suppose for example:
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y) # True-y refers to the same object as x
print(x is z) # False-z is a different object even if the content is the same

What is the id() function?
Python has a built-in id() function that returns a number (ID) unique to every object - this number indicates the location at which this object is stored in memory.
Let x = [1, 2, 3].
Let y = [1, 2, 3].
Example:
print(id(x)) # Example: 139957272175104
print(id(y)) # Different ID: 139957272176000.
x and y appear to be identical however, these two are objects at different memory addresses with separate identities.
But, with:
a = 10
b = 10
print(id(a))
print(id(b))
You'll likely see the same ID for both since small integers are commonly cached and reused by Python to save memory.
So, in this case a is b could be True.

In brief:
Every object in Python has a unique ID that shows where it lives in memory.
That memory address is what the id() function gives us.
Use is for comparing object identities and not only content.


16.How do you check if the value 3 is present in the list my_list = [1, 2, 3, 4]?

You can use the in operator to check if 3 is in my_list = [1, 2, 3, 4].
It is a simple and fast way to check if a particular element is in the list.
This is how you carry it out:
my_list = [1, 2, 3, 4]
if 3 in my_list:
  print("The number 3 is present in the list!")
else:
  print("The number 3 is not in the list".)
Explanation:
The in operator basically checks if a specific value is available inside the list.
In our case, the expression 3 in my_list will evaluate as true since 3 really is a member of the list [1, 2, 3, 4].
If it is found, then it will print, "3 is present in the list!" Otherwise, it will print, "3 is not found in the list."
And it is as simple as that! This method is concise and readable.


17.How can you check if a key exists in a Python dictionary? What operator is commonly used?

It is the in operator that checks whether a key exists in a dictionary in Python.
As an example,
my_dict = {'a': 1, 'b': 2, 'c': 3}
If 'b' in my_dict:
  print("Key 'b' is present in the dictionary!")
else:
  print("Key 'b' is not in the dictionary.")
Explanation:
The in operator checks whether the 'b' exists within the dictionary my_dict.
If 'b' is a key of the dictionary, it will print: "Key 'b' is present in the dictionary!"; otherwise, it will print: "Key 'b' is not in the dictionary."
This is a very effective and popularly used methodology for testing the existence of keys in a dictionary within Python.


18.Evaluate the expression 10 + 2 * 3 ** 2. Explain the order of operations.

Evaluate the expression.
let's break down 10 + 2 * 3 ** 2 and bring the order of operations involved:
Evaluation:
Exponentiation (**): First, Python handles the exponent.
3 ** 2 = 9
The expression now becomes: 10 + 2 * 9
Multiplication (*): Next by Python makes the multiplication.
2 * 9 = 18
The expression now becomes: 10 + 18.
Addition (+): Finally, the last operation Python does is addition.
10 + 18 = 28
Thus the value of 10 + 2 * 3 ** 2 is 28.

Principle of Order Operations (Order of Precedence):
Python keeps a distinct order of the operations which is learned as PEMDAS/BODMAS (though the acronym sometimes varies slightly).
Parentheses (or Brackets)
Exponents (or Orders)
Multiplication and Division (from left to right)
Addition and Subtraction (from left to right)
In the expression 10 + 2 * 3 ** 2:

The operation of an exponentiation which is the most important one in handling has to be performed first- 3 ** 2.
After this comes the evaluation of the multiplication 2 * 9.
Of least precedence among all is addition: 10 + 18.

Notice: this is how the expression is consistently evaluated and gives the correct value. If you wanted to change the order, you would use parentheses to group operations.
For example, (10 + 2) * 3 ** 2 would yield a different result because the addition would be performed before the multiplication and exponentiation.


19.What are some examples of values in Python that are considered "falsy"? How are these evaluated in boolean contexts?

Examples of Falsy Values in Python:
With the term "blank" some values are intended to be considered as 'false', so that they behave like false values themselves in conditions such as "if statements" and "logical operations".

Here are some common examples treated as False values in Python:
None – Absent of any value
False – Boolean False itself
0 – Holds zero for any numeric type (0, 0.0, 0j)
"" – Indicates an empty string
[] – An empty list
{} – An empty dictionary
() – An empty tuple
set() – An empty set
range(0) – An empty range
float('nan') - It is not indeed a falsy, but it behaves oddly in comparisons so one usually treats it cautiously.

How Are These Values Checked?
When an expression is evaluated in boolean context if, or while internally Python will use bool(). Then if bool(value) is equal to False, it classifies the value as falsy.
Example:
if not []:
  print("Empty list is falsy")
if "":
  print("This won't print because empty string is falsy")
if 0:
  print("This also won't print because 0 is falsy")
if None:
  print("This will not print because None is falsy")
Output:
Empty list is falsy

Summary:
Simply put, falsy values are the values that Python decides to treat as False during a logical check. Just understand what those are so that you don't begin to get into odd behavior in conditions and you have cleaner more predictable code.


20. Can you Rewrite the following if-else statement using a ternary operator:

if age >= 18:
    status = "Adult"
else:
    status = "Minor"

Yes! The provided if-else statement may be written in Python using a ternary operator (conditional expression) as follows:
status = "Adult" if age >= 18 else "Minor"
Interpretation:
This line means: "if age is greater than or equal to 18, status will be assigned to be the string Adult otherwise, it will be assigned to be the string Minor."
The expression becomes concise and cleaner when used for simple and easy to understand single line decisions.
Such form is frequently employed when both the condition and the assignments in question are simple and easy to read.