8.How to swap variable values in Python?
In Python, variable values can be swapped in an elegant and concise way by allowing simultaneous assignments (tuple unpacking).
a = 5
b = 15
print(f"Before swapping: a = {a}, b = {b}")
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
Python uses a temporary tuple of values from the right-hand side and unpacks it to variables on the left-hand side, thereby swapping values.
9.What are global and local variables in Python?
The variable scope refers to a section in code in which variables can be accessed.
•Global Variable: A variable that is defined outside any function/class. Hence, it can be accessed from anywhere in the code.
global_var = "I am global"
def my_func():
print(global_var)
my_func()
print(global_var)
•Local Variable: A variable that is defined inside a function. Hence, it can be accessed from that function only.
def another_func():
local_var = "I am local"
print(local_var)
another_func()
# print(local_var) #This would cause an error
Global variables can be modified inside a function, but the global keyword must be used.
10.How to take user input and store it in a variable in Python?
The input() function is handy to take text input from the user. The function pause the running program, prompts any text provided as an argument and returns the input as a string.
user_name = input("Please enter your name: ");
print(f"Hello, {user_name}!");
age_str = input("Please enter your age: ");
age = int(age_str); print(f"You are {age} years old!");
Remember, the input() function always returns a string; this means that one must go about converting it to the required data type themselves (like int or float) and take care of any possible errors in case the user input does not convert.
11.What is type casting in Python?
Think about a toy designed to fit into a specific box. Sometimes you may almost have one sized right and you have to change it just a bit to make it fit perfectly.
That's somewhat how type casting works in Python.
Type casting or type conversion is the change of type from one to another. This is good since many times we want to work with data in a particular format.
For instance, if you ever received a number as an input text from a user like "10," you can't do any math on it directly but you must first convert it into an actual number with an integer type.
In-built functions have been provided for the conversion based on the behavior you want. It is like having special tools of shape and size for your data to suit your work.
For example, a recipe calls for 2 cups of flour. If you only had a measuring cup that measured in ounces, you would have to convert ounces to cups to be able to correctly follow the recipe.
Similarly, type-casting in programming is to make sure data is in the right "unit" for the operation you want to do.
12.How to convert a string to an integer in Python?
You've got some text that looks like a whole number, like "123", but Python sees it just as a sequence of characters (a string). To do any math with it, you need to convert it into an actual integer. Python conveniently provides an int() function for this.
Here's how it works:
number_as_string = "456"
actual_number = int(number_as_string)
print(actual_number) # Output: 456
print(type(actual_number)) # Output: <class 'int'>
The int() function here takes in as input the string "456" and returns the integer value 456. Now the actual_number variable holds a proper integer and you can do calculations with it:
result = actual_number + 10
print(result) # Output: 466
Now, one important point is that whatever string you are trying to convert into an integer must really represent a whole number.
If something contains decimal points or letters or any other characters that are not a digit (except a leading minus for negative numbers), you will get a Python error:
invalid_string = "12.3"
# integer_value = int(invalid_string) # This will raise ValueError
another_invalid = "hello";
# integer_value_2 = int(another_invalid) # This will also raise ValueError
But if you have a string that represents a decimal number, you would typically want to convert it first to a float using the float() function.
13.How to assign the same value to multiple variables in Python?
You have to set the scores for a new game about which you want to initialize all players' scores to zero. A nifty and efficient way to do that in Python is to use chained assignment in a single line of code.
And this is how it looks:
player1_score = player2_score = player3_score = 0
print(player1_score) # Output: 0
print(player2_score) # Output: 0
print(player3_score) # Output: 0
The value 0 is assigned first to player3_score. Then the value of player3_score, which is now 0, is assigned to player2_score, and finally, the value of player2_score is assigned to player1_score. It goes like a chain reaction from right to left.
It is a useful cleaning method whenever you would like to supply several variables with the same beginning value, keeping your code clean and readable.
14.What are reserved keywords in Python?
Consider reserved keywords in Python as special words that are understood by the language and are being used by it for specific purposes. These words form part of the vocabulary of Python and have a meaning attached, and you cannot assign a name for your variable, function, class, or any other identifier for these words. If you try to do so, Python will get confused and throw a syntax error. It would be like naming your pet using "if" or "for".
Some examples of reserved keywords are:
if, else, elif, for, while, def, class, return, import, from, as, try, except, finally, raise, with, assert, break, continue, del, in, is, lambda, nonlocal, not, or, pass, print, True, False, None
You don't need to learn them all by heart at once, but you will start to become aware of them as you study more Python. Most code editors would provide a mechanism to visually highlight these keywords in some specific color, which in turn should help prevent using these words as names by accident.
Choosing good variable and function names, descriptive of what they do, is a nicer practice, in order to avoid all the reserved keywords. This enhances readability of your code and also keeps the code free from any conflict with the structure of the Python language.
15.How to write comments in Python?
Comments, like little sticky notes left by the programmer for himself-or herself and for anyone else reading his code-are noted down to be ignored by the computer during execution of the program. It is worth noting that whereas comments are totally useless to the computer, these little notes are very precious for explaining code, telling why one did a certain thing, or just to ease the reading of the code.
Python has two major ways of writing comments:
•Single-line comments: You use a hash symbol (#) to mark the start of a comment that occupies only one line.
Everything to the right of the # in that line is taken as a comment.
# This is a single-line comment explaining the next line of code
x = 10 # Assigning the value 10 to variable x
•Multi-line comments (docstrings): There is no particular syntax for multi-line comments, as found in some other languages (e.g. /*...*/), but the introduction of docstrings (Documentation Strings) serves as a sort of multi-line comment in Python. These are multi-line strings written between triple quotes ('''Docstring goes here''' or """Docstring goes here"""), which are commonly used for documenting functions, classes, and modules.
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
'''
This is another way to write a
multi-line comment using triple single quotes.
It's often used for longer explanations.
'''
Although docstrings serve for documentation, you can simply use triple-quoted strings everywhere as comments. For any minor clarifications in your code, though, single-line comments using # are preferred.
A well-commented code would be more maintainable and readable, especially with the passage of time or when some other person has to work on it.
16.What is the significance of indentation in Python?
Indentation in Python is not an icing on the cake; rather, it is an integral part of the language's syntax and conveys tremendous significance. In most other programming languages, indentation caters to readability while the actual programming structure of the code is governed by curly braces {}. In Python, indentation acts as a structural device to define blocks of code.
A block of code is a set of statements executed together. These blocks are usually associated with control flow structures such as:
• if statements
• for loops
• while loops
• def (function definitions)
• class (class definitions)
• try and except blocks
The particular level of indentation allows Python to associate statements with the appropriate block. All statements in a block must share the same indentation level (typically, four spaces are preferred, but using either spaces or tabs consistently is important).
An illustration will aid understanding:
if age >= 18:
print("You are an adult.") # This line is part of the 'if' block
can_vote = True # So is this line
else:
print("You are not yet an adult.") # This line is part of the 'else' block
can_vote = False # And this one too
print("End of check.") # This line is outside the 'if-else' block
If the age is greater than or equal to 18, the lines of code under the if statement (indented) will be executed; otherwise, those under the else statement will be executed. The last print statement that lies outside the if or else statements is executed in either case.
Mistake the indentation, and Python will throw an IndentationError, preventing your program from running. This seems hard apparently, but it is advantageous in the long run, as it enforces a certain consistent readable style of coding. It visually enhances the indentation of code and disambiguates it.
17.Can variable names start with numbers in Python?
Variable names in Python can't start with a number. This is one of the most basic rules in the syntax of Python for naming identifiers (including variable names, function names, class names, etc.).
Trying to declare a variable starting with a digit will yield a SyntaxError without exception.
They allow variable names to start with a letter (a-z, A-Z) or an underscore (_).
This is what will happen if you try:
# 1st_item = "apple" # This will cause a SyntaxError
You can use numbers as the other characters in a variable's name, after the first character:
item1 = "apple" # Valid
count_2 = 10 # Valid
_version3 = "3.0" # Valid (starts with an underscore)
This rule is intended to eliminate any possible confusion and to facilitate differentiation of variable names from numeric literals by the Python interpreter.
For instance, one is liable to mistake 10apples for a variable name of 10apples, where as it could mean the actual number 10 followed by the word "apples."
Keeping to this rule will help you avoid unnecessary confusion. hence, always remember to start variable names with a letter or an underscore.
18.How to delete a variable in Python?
Deleting a variable may arise in your case if you consider it deleted as it is of no more use to you, or in other words, to free memory. The delete keyword is used in Python.
Example of usage:
my_variable = 42
print(my_variable) # Will Print: 42
del my_variable
# print(my_variable) #This causes a NameError now since my_variable no longer exists
After the execution of the command del my_variable, the name my_variable is no longer defined in the current scope.
If usage of my_variable is attempted afterward, Python raises a NameError stating not found.
Thus, del also enables deletion of items in both Lists and Dictionaries:
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Removes the element at index 2 (which is 3)
print(my_list) # Output: [1, 2, 4, 5]
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b'] # Remove key 'b' and its value
print(my_dict) # Output: {'a': 1, 'c': 3}
While del explicitly deletes the variable, Python also has another mechanism known as garbage collection that automatically reclaims memory from any object that is no longer referenced by any variable. Therefore, you do not always need to delete variables manually, although, in select cases, you may want to forcefully remove a variable from the namespace, especially with a heavy load on memory.
19.What happens if you use a variable without assigning it in Python?
If a variable in Python is called into action before it has been assigned any value, a NameError exception will be raised by the interpreter. This error shows up when the interpreter finds a name that hasn't been defined in the present scope. The Python interpreter has to know the value a variable holds before it can be used in any operations or expressions.
Consider this example:
# print(undefined_variable) # This line will cause a NameError
defined_variable = 10
print(defined_variable) # This is fine
Once you run the first line (commented above), you would receive an output similar to: NameError: name 'undefined_variable' is not defined. This was Python's way of telling you, "Hey, I don't know what undefined_variable is! You haven't given it a value yet."
This is a frequent error made by beginners; hence it is a good practice to first check that a variable has been assigned a value before using it in any code. Always do this to avoid the NameError.
20.How to print multiple variables in one line in Python?
A number of methods exist to print data in one line with the variable prints. Such outputs are informative as well as good-looking.
Some of the methods include:
• Using commas in the print() function: Simply pass the variables you want printed as parameter arguments to the print(), separating them by commas. Python will insert a space between the values by default.
name = "Charlie"
age = 30
city = "London"
print(name, age, city) # Output: Charlie 30 London
• Using f-strings (formatted string literals): A very powerful and readable way of injecting expressions (including variables) directly into strings. All you have to do is prefix your string with an f and then put your variables inside curly braces {}.
name = "Alice"
score = 95
print(f"The student's name is {name} and their score is {score}.")
# Output: The student's name is Alice and their score is 95.
F-strings are pretty flexible and grant you the ability to format the output in different ways.
Using the .format() method: This is yet another way of formatting strings, in which placeholders {} are put within the string, and values to be inserted are given to the string by .format().
product = "Laptop"
price = 1200.50
print("The product is {} and its price is ${}.".format(product, price))
# Output: The product is Laptop and its price is $1200.5.
You can also use positional or keyword arguments with .format() for more control.
Method preference depends most heavily on the user and how complicated or messy output needs to be. Generally, the most readable and concise method for outputting variations of primitive input is through f-string. Comma-separated printing is the short way where high conditions outputs are not needed. .format() is a strong way to give a standard output more customizability.
Previous Topic==> Introduction To Python FAQ || Next Topics==> Python Data Types FAQ
Other Topic==>
Input In Python
Top SQL Interview Questions
Employee Salary Management SQL FAQ!.
Top 25 PL/SQL Interview Questions
Topics Wise Top SQL Interview Questions