InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Python Commands |
|
Answer» Magic Commands are one of the new features added to the python shell. Basically, they are enhancements over the normal python code, provided by the IPython Kernel. The main syntax for these commands is that they are prefixed by as “%” character. They prove useful in solving many common problems we encounter while coding and also provide us some versatile shortcuts.
Some examples of these commands in Python are:
print("Hello World") runner() %run runner.py Output: Hello World
for i in range(10000): a = a + i**2 Output: CPU Times: user: 3.72 ms, sys: 9us, , total: 3.73ms, Wall time: 3.75ms
def func(): print("Hello") func() Output: Overwriting code.py
def func(): print("Hello") func()
b = 5 c = 1 %who Output: a b c
<html> <body> <table> <tr> <th>Name</th> <th>Country</th> <th>Age</th> </tr> <tr> <td>Sid</td> <td>India</td> <td>22</td> </tr> <tr> <td>Dave</td> <td>UK</td> <td>28</td> </tr> </table> </body> </html> Output:
Some other useful tools for Python
We can conclude that Python is a robust, high-level, interpreted programming language. It is also an Object Oriented Programming Language that strongly follows all OOPs principles. It has various inbuilt powerful modules that follow simple syntax which makes it appealing to both beginners and experienced folks alike. A vast collection of libraries and functions makes the development of any sort much easier in Python. In this cheat sheet, we have covered the most common fundamentals of python language that would help you kickstart your career in python. Useful Resources:
|
|
| 2. |
Python Virtual Environment |
|
Answer» Virtual Environments are used to encapsulate certain Python Libraries of Python for single project, which might not be used in other projects, rather than installing those dependencies globally. Installation Steps: pip install virtualenv pip install virtualenvwrapper-winUsage Steps: mkvirtualenv Test # Make virtual environment called Test#setprojectdir . deactivate # To move to something else in the command #line. workon Test # Activate environment |
|
| 3. |
Python Dataclasses |
|
Answer» Python Classes used for storing data objects are called Dataclasses. They have certain features like:
Python 2.7: The example shows the performing function of Dataclasses in older versions of python when Dataclasses were not yet introduced. class Self:def __init__(self, x): self.x = x ob = Self("One") print(ob.x) Output: One Python 3.7: The example shows using dataclasses in newer versions of python. @dataclass #annotation indicates that it is a dataclass moduleclass Self: x: string ob = Self("One") print(ob.x) Output: One Note: It is compulsory to specify the datatype of each variable declared. If at any point we don’t want to specify the type, set the type as typing.Any. from dataclasses import dataclassfrom typing import Any @dataclass class WithoutExplicitTypes: name: Any age: Any = 16 |
|
| 4. |
if __name__ == "__main__" in Python |
|
Answer» __main__ is the name of the scope in which the top-level code executes. It can check if it is running in its own scope by checking its own __name__. ... main() |
|
| 5. |
*args and **kwargs in Python |
|
Answer» We can pass a variable number of arguments to a function using special symbols called *args and **kwargs. The usage is as follows:
Example: # the function will take in a variable number of arguments# and print all of their values def tester(*argv): for arg in argv: print(arg) tester('Sunday', 'Monday', 'Tuesday', 'Wednesday') Output: Sunday Monday Tuesday Wednesday
Example: # The function will take variable number of arguments# and print them as key value pairs def tester(**kwargs): for key, value in kwargs.items(): print(key, value) tester(Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4) Output: Sunday 1 Monday 2 Tuesday 3 Wednesday 4 |
|
| 6. |
Ternary Operator in Python |
|
Answer» The ternary operator is used as an alternative to the if-else conditional statements and provides a way to write a short crisp one-liner statement. The syntax is as follows: <expression 1> if <condition> else <expression 2> f = 2s = 2 # if the sum of f and s is greater than 0 the sum # is printed, else 0 is printed print(f + s if (f + s > 0) else 0) Output: 4 |
|
| 7. |
Lambda Function in Python |
|
Answer» These are small anonymous functions in python, which can take any number of arguments but returns only 1 expression. Let us understand it with an example, Consider the function which multiplies 2 numbers: def mul(a, b):return a * b print(mul(3, 5)) Output: 15 The equivalent Lambda function for this function will be: mul = lambda a, b: a * bprint(mul(3, 5)) Output: 15 The syntax for this will be as shown below: Similarly, other functions can be written as Lambda functions too, resulting in shorter codes for the same program logic. |
|
| 8. |
Logging in Python |
||||||||||||||||||
|
Answer» Logging allows us to keep track of some events which occurs when some software runs. It becomes highly important in Software Development, Debugging and Running Softwares. import logging# Create and configues the logger logging.basicConfig(filename="newfile.log", format='%(asctime)s %(message)s', filemode='w') # Creates logging object logg = logging.getLogger() # Sets the level of logging to DEBUG logg.setLevel(logging.DEBUG) # Messages logg.debug("Debug Message") logger.warning("Its a Warning") logger.info("Just an information") Levels of Logging: Described in order of increasing importance
|
|||||||||||||||||||
| 9. |
Debugging in Python |
|
Answer» Raising Exceptions with raise statement: The raise statement is used to raise exceptions and consists of 3 components:
Traceback (most recent call last): File "./prog.py", line 1, in <module> Exception: Error Occurred!! Traceback as String There is a function in python called traceback.format_exc() which returns the traceback displayed by Python when a raised Exception is not handled as a String type. The Traceback Module is required to be imported for this purpose. Example: import tracebacktry: raise Exception('Error Message.') except: with open('error.txt', 'w') as error_file: error_file.write(traceback.format_exc()) print('The traceback info was written to error.txt.') Output: The traceback info was written to error.txt. Assert Statements in Python: Assert Statements/Assertions are widely used for debugging programs and checking if the code is performing some operation that is obviously wrong according to the logic of the program. The special thing about assert is that when an assert fails, the program immediately crashes, allowing us to narrow down our search space for the bug.
>>> assert sum == 5, 'Addition Error' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: Addition Error Assertions can be disabled by passing the -O option when running Python as shown in the commands below. $ python -Oc "assert False"$ python -c "assert False" Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError |
|
| 10. |
Python RegEx |
||||||||||||||||||||||||||||||||
Answer»
The re module in python allows us to perform regex matching operations. import relandline = re.compile(r'\d\d\d\d-\d\d\d\d') num = landline.search('LandLine Number is 2435-4153') print('Landline Number is: {}'.format(num.group())) Output: Landline Number is: 2435-4153 The above example landline number from the string and stores it appropriately in the num variable using regex matching.
A group is a part of a regex pattern enclosed in parenthesis (). We can put matches into different groups using the parenthesis (). We can access the groups using group() function. import relandline = re.compile(r'(\d\d\d\d)-(\d\d\d\d)') num = landline.search('LandLine Number is 2435-4153') # This will print the first group, which is the entire regex enclosed in the brackets print(num.group(0)) # This will print the second group, which is the nested regex enclosed in the 1st set of nested brackets print(num.group(1)) # This will print the third group, which is the nested regex enclosed in the 2nd set of nested brackets print(num.group(2)) Output: 2435-4153 2435 4153
There are a lot of regex symbols that have different functionalities so they are mentioned in the table below:
Example: Here we define a regex pattern, address = "(\\d*)\\s?(.+),\\s(.+)\\s([A-Z]{2,3})\\s(\\d{4})"From the above table, we can explain some of the symbols in this pattern:
|
|||||||||||||||||||||||||||||||||
| 11. |
Formatting Dates in Python |
|
Answer» To handle date and time operations in Python, we use the datetime module.
Example: import datetimetm = datetime.time(1, 30, 11, 22) print(tm) Output: 01:30:11.000022
Example: import datetimedate = datetime.date(2000, 11, 16) print('Date date is ', date.day, ' day of ', date.month, ' month of the year ', date.year) Output: Date date is 16 day of 11 month of the year 2000
Example: from datetime import datetimeprint(datetime.strptime('15/11/2000', '%d/%m/%Y')) Output: 2000-11-15 00:00:00
For example: from time import gmtime, strftimes = strftime("%a, %d %b %Y %H:%M:%S + 1010", gmtime()) print(s) Output: Sun, 28 Nov 2021 18:51:24 + 1010 |
|
| 12. |
String Manipulation in Python |
||||||||||||||||||||
Answer»
Escape Sequences are used to print certain characters to the output stream which carry special meaning to the language compiler. Examples:
Multiline Strings are used in python through triple quotes ''' Example: a = ''' HelloWorld! This is a Multiline String.''' print(a) Output: Hello World! This is a Multiline String.
Strings in Python are indexed the same way as a list of characters, based on 0-based indexing. We can access elements of a string at some index by using the [] operators. Consider an example of the string value Python. a = "Python"print(a[0], a[2], a[4]) print(a[-1], a[-3], a[-5]) Output: P t o n h y
Slicing is also done the same way as in lists. a = "Hello"# Slices the string from 0 to 3 indexes print(a[0:3]) # Slices the string from 3 to -1(same as 4) indexes print(a[3:-1]) Output: Hel l
The upper() and lower() functions are used to convert a string of letters into uppercase or lowercase respectively. The isupper() and islower() functions are used to check if a string is in all uppercase or lowercase respectively. a = "Hello"print(a) # Converts string to uppercase print(a.upper()) # Converts string to lowercase print(a.lower()) # Checks if string is uppercase print(a.isupper()) # Checks if string is lowercase print(a.islower()) Output: Hello HELLO hello False False Other similar functions:
join() function merges elements of a list with some delimiter string, and returns the result as a string. list = ["One", "Two", "Three"]# join function s = ','.join(list) print(s) Output: One,Two,Three split() function splits the into tokens, based on some delimiters and returns the result as a list. # split functionnewList = s.split(',') print(newList) Output: ['One', 'Two', 'Three'] In general, a string can be split to list using split() method and a list can be joined to string using the join() method as shown in the image below:
String Formatting is done with the str.format() function. first = "first"second = "second" s = "Sunday is the {} day of the week, whereas Monday is the {} day of the week".format(first, second) print(s) Output: Sunday is the first day of the week, whereas Monday is the second day of the week
It is recommended to be used when formatting strings generated by users. They make the code less complex so are easier to understand. They can be used by importing the Template class from the string module. Example: >>> from string import Template>>> name = 'Scaler' >>> t = Template('Hey $name!') >>> t.substitute(name = name) 'Hey Scaler!' |
|||||||||||||||||||||
| 13. |
Comprehensions in Python |
Answer»
# b will store values which are 1 greater than the values stored in a b = [i + 1 for i in a] print(b) Output: [1, 2, 3, 4]
# b will store squares of the elements of a b = {i ** 2 for i in a} print(b) Output: {0, 1, 4, 9}
# b stores elements of a in value-key pair format b = {val: k for k , val in a.items()} print(b) Output: {'World': 'Hello', 1: 'First'} |
|
| 14. |
Sets in Python |
||||||||||
|
Answer» Initializing Sets: Sets are initialized using curly braces {} or set() in python. A python set is basically an unordered collection of unique values, i.e. it will automatically remove duplicate values from the set. s = {1, 2, 3}print(s) s = set([1, 2, 3]) print(s) s = {1, 2, 3, 3, 2, 4, 5, 5} print(s) Output: {1, 2, 3} {1, 2, 3} {1, 2, 3, 4, 5} Inserting elements in set: We can insert a single element into a set using the add function of sets. s = {1, 2, 3, 3, 2, 4, 5, 5}print(s) # Insert single element s.add(6) print(s) Output: {1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 6} To insert multiple elements into a set, we use the update function and pass a list of elements to be inserted as parameters. s = {1, 2, 3, 3, 2, 4, 5, 5}# Insert multiple elements s.update([6, 7, 8]) print(s) Output: {1, 2, 3, 4, 5, 6, 7, 8} Deleting elements from the set: We can delete elements from a set using either the remove() or the discard() function. s = {1, 2, 3, 3, 2, 4, 5, 5}print(s) # Remove will raise an error if the element is not in the set s.remove(4) print(s) # Discard doesn't raise any errors s.discard(1) print(s) Output: {1, 2, 3, 4, 5} {1, 2, 3, 5} {2, 3, 5} Operators in sets: The below table shows the operators used for sets:
The set operators are represented in the Venn Diagram below: Examples: a = {1, 2, 3, 3, 2, 4, 5, 5}b = {4, 6, 7, 9, 3} # Performs the Intersection of 2 sets and prints them print(a & b) # Performs the Union of 2 sets and prints them print(a | b) # Performs the Difference of 2 sets and prints them print(a - b) # Performs the Symmetric Difference of 2 sets and prints them print(a ^ b) Output: {3, 4} {1, 2, 3, 4, 5, 6, 7, 9} {1, 2, 5} {1, 2, 5, 6, 7, 9} |
|||||||||||
| 15. |
Python Dictionaries |
|
Answer» Dictionaries in Python are equivalent to Maps in C++/JAVA. They are used to store data in key-value pairs. Printing key and values in dictionaries: To print the keys of the dictionary, use the .keys() method and to print the values, use .values() method. dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}# dict.keys() method will print only the keys of the dictionary for key in dict.keys(): print(key) # dict.values() method will print only the values of the corressponding keys of the dictionary for value in dict.values(): print(value) Output: firstsecond third sunday monday tuesday Update key value in dictionary:
for item in dict.items(): print(item) dict['fourth'] = 'wednesday' for item in dict.items(): print(item) Output: ('first', 'sunday') ('second', 'monday') ('third', 'tuesday') ('first', 'sunday') ('second', 'monday') ('third', 'tuesday') ('fourth', 'wednesday')
for item in dict.items(): print(item) dict['third'] = 'wednesday' for item in dict.items(): print(item) Output: ('first', 'sunday') ('second', 'monday') ('third', 'tuesday') ('first', 'sunday') ('second', 'monday') ('third', 'wednesday')
for item in dict.items(): print(item) del dict['third'] for item in dict.items(): print(item) Output: ('first', 'sunday') ('second', 'monday') ('third', 'tuesday') ('first', 'sunday') ('second', 'monday') Merging 2 dictionaries We can merge 2 dictionaries into 1 by using the update() method. dict1 = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}dict2 = {1: 3, 2: 4, 3: 5} dict1.update(dict2) print(dict1) Output: {'first': 'sunday', 'second': 'monday', 'third': 'tuesday', 1: 3, 2: 4, 3: 5} |
|
| 16. |
Tuples in Python |
|
Answer» Tuples are entities in Python that work almost similar to that of lists, but differ in the main feature from lists, is in that they are inmutable. They are initialized by writing the elements of the tuple with (), separated by commas. # Defining and Initializing a tuple called exampleexample = ("First", "Second", "Third", "Fourth") print(example) print(example[1:3]) Output: ('First', 'Second', 'Third', 'Fourth') ('Second', 'Third') Type Converting between Tuples, Lists, and Strings: # Convert list to a tupletuple(['first', 'second', 'third']) # Convert tuple to a list list(('first', 'second', 'third')) # Convert string to a list list("Scaler") |
|
| 17. |
Lists in Python |
|
Answer» Lists are used to store multiple items in a single variable. Their usage and some functions are shown below with examples: example = ["Sunday", "Monday", "Tuesday", "Wednesday"];print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday']
# Positive Indexing print(example[0], example[1]) # Negative Indexing print(example[-1]) Output: Sunday Monday Wednesday
# Positive Slicing print(example[0:2]) # Negative Slicing print(example[-3:-1]) Output: ['Sunday', 'Monday'] ['Monday', 'Tuesday']
print(example) example[0] = "Saturday" print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday'] ['Saturday', 'Monday', 'Tuesday', 'Wednesday']
When we merge the contents of 2 lists into one list, it is called list concatenation. example = ["Sunday", "Monday", "Tuesday", "Wednesday"];example1 = ["Weekdays", "Weekends"] # Concatenation example = example + example1 print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Weekdays', 'Weekends'] Copying the contents of a list, some finite number of times into the same or some list is called list replication. example = ["Sunday", "Monday", "Tuesday", "Wednesday"];example1 = ["Weekdays", "Weekends"] # Replication example1 = example1 * 3 print(example1) Output: ['Weekdays', 'Weekends', 'Weekdays', 'Weekends', 'Weekdays', 'Weekends']
print(example) del example[2] print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday'] ['Sunday', 'Monday', 'Wednesday']
for ex in example: print(ex) Output: Sunday Monday Tuesday Wednesday in and not in keywords: print("Sunday" in example) print("Hello" not in example) Output: True True
insert(): This function inserts an element into a particular index of a list. example = ["Sunday", "Monday", "Tuesday", "Wednesday"];print(example) example.insert(1, 'Days') print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday'] ['Sunday', 'Days', 'Monday', 'Tuesday', 'Wednesday'] append(): This function appends an element at the back of a list. example = ["Sunday", "Monday", "Tuesday", "Wednesday"];print(example) example.append('Days') print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday'] ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Days']
example = ["Sunday", "Monday", "Tuesday", "Wednesday"]; print(example) # Sort in ascending order example.sort() print(example) # Sort in descending order example.sort(reverse = True) print(example) example = [1, 5, 3, 7, 2] # Sort in ascending order example.sort() print(example) # Sort in descending order example.sort(reverse = True) print(example) Output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday'] ['Monday', 'Sunday', 'Tuesday', 'Wednesday'] ['Wednesday', 'Tuesday', 'Sunday', 'Monday'] [1, 2, 3, 5, 7] [7, 5, 3, 2, 1] |
|
| 18. |
Exception Handling in Python |
|
Answer» Exception Handling is used to handle situations in our program flow, which can inevitably crash our program and hamper its normal working. It is done in Python using try-except-finally keywords.
The same has been illustrated in the image below: Example: # divide(4, 2) will return 2 and print Division Complete# divide(4, 0) will print error and Division Complete # Finally block will be executed in all cases def divide(a, denominator): try: return a / denominator except ZeroDivisionError as e: print('Divide By Zero!! Terminate!!') finally: print('Division Complete.') |
|
| 19. |
Importing Modules in Python |
|
Answer» Python has various external libraries of code with useful utilities and functions. To use these modules, we need to import them into our code, using the import keyword. For example, if we want to use the functionalities of the math module, then we can import it in our python code by using import math as shown in the example below. import mathprint(math.pi) Output: 3.141592653589793 If we want to perform any string manipulations, we can use the string module as import string in python. More of this is covered in the String Manipulation section below. |
|
| 20. |
Global Statement |
|
Answer» To modify a global variable from inside a function, we use the global statement: def func():global value value = "Local" value = "Global" func() print(value) Output: Local We set the value of “value” as Global. To change its value from inside the function, we use the global keyword along with “value” to change its value to local, and then print it. |
|
| 21. |
Python Variable Scope Resolution |
|
Answer» Scope of a variable is the part of the code, where it can be accessed freely and used by the program. The scopes in the above image are explained as follows:
The rules used in Python to resolve scope for local and global variables are as follows:
|
|
| 22. |
Functions in Python |
|
Answer» Functions are used to well-organized our code and enhance code readability and reusability. In Python, a function is defined using the def keyword. A function can return some value, or not depending upon its use case. If it has to return a value, the return statement (which has been discussed) is used. The syntax of a python function is shown in the image below: Example of a function: # Function to return sum of two numbersdef getSum(a, b): return a + b # Function to print sum of 2 numbers def printSum(a, b): print(a + b) print(getSum(5, 6)) printSum(5, 6) |
|
| 23. |
Jump Statements in Python |
Answer»
... print(i) ... if i == 3: ... break ... 0 1 2 3
... if i == 3: ... continue ... print(i) ... 0 1 2 4
if i % 2 == 0: pass else: print(i) Output: 1 3
if x == 'Hello': return True else: return False |
|
| 24. |
Loop Statements in Python |
|
Answer» Loops in Python are statements that allow us to perform a certain operation multiple times unless some condition is met. For Loops: For loop is used to iterate iterables like string, tuple, list, etc and perform some operation as shown in the flowchart below:
print(i) Output: 0 1 2 3 4
This will run the loop from start to stop - 1, with step size = step in each iteration. print(i) Output: 2 4 6 8
for ele in a: print(ele) Output: 1 3 5 7
>>> while count > 0: ... print(count) ... count -= 1 ... 5 4 3 2 1 |
|
| 25. |
Conditional Statements in Python |
Answer»
>>> if var == "Good": ... print("Same") ... Same
>>> if var == "Good": ... print("Same") ... elif var != "Good": ... print("Not Same") ... Same
>>> if var != "Good": ... print("Not Same") ... else: ... print("Same") ... Same The final if-elif-else ladder looks like shown below: |
|
| 26. |
Boolean Operators in Python |
||||||||
|
Answer» The Table gives a list of boolean operators available in Python along with their functions:
Examples: # and operatorprint(True and False) False # or operator print(True or False) True # not operator print(not False) True |
|||||||||
| 27. |
Program Flow Control in Python |
||||||||||||||
|
Answer» Relational Operators in Python The Table gives a list of relational operators available in Python along with their functions:
Some examples are given below: # Equality Operator>>> 10 == 10 True # 10 is equal to 10, so true >>> 10 == "10" False # The first string is of type int, 2nd of type string, so false. # Greater than >>> 10 > 20 False # 10 is lesser than 20, so above expression is false. # Inequality >>> 10 != 20 True # 10 is not equal to 20, so the expression is true # Greater than or equal to >>> (2 + 3) >= (4 + 1) True # (2 + 3) = 5 and (4 + 1) = 5, so the expression is true. >>> True is False False >>> True is not False True |
|||||||||||||||
| 28. |
Python Type Casting |
|
Answer» Type casting is basically a conversion of variables of a particular datatype into some other datatype, such that the conversion is valid. Type casting can be of two types:
float_num = 1.01 ans = int_num + float_num print(type(int_num)) print(type(float_num)) # ans is implicitly typecasted to float type for greater precision print(type(ans))
1. Integer to String or Float: To typecast an integer into a string type, we use the str() method. Similarly, to typecast it into a float type, we use the float() method. For example: >>> var = 123>>> str(var) '123' >>> var = 123 >>> float(var) 123.0 2. Float to Integer: To typecast a float datatype into an integer datatype, we use the int() method. For example: >>> var = 7.8>>> print(int(var)) 7 |
|
| 29. |
Standard Python Functions |
Answer»
The print() function prints some specified message to the screen or some standard output device. We can print strings, numbers, or any other object using this function. We can print multiple tokens, and also specify to print the data separated by different delimiters using the print() function. >>> print("Hello World")Hello World >>> var = "Interviewbit" >>> print("My name is ", var) ('My name is ', 'Interviewbit') >>> print("My name is " + var) My name is Interviewbit >>> print(123) 123 >>> a = [1, 2, 3, 4] >>> print(a) [1, 2, 3, 4]
The input() function in Python is used to take any form of inputs from the user/standard input device, which can later be processed accordingly in the program. It is complementary to the print() function. >>> print('Enter your name.')>>> myName = input() >>> print('Hello, {}'.format(myName)) Enter your name. Interviewbit Hello, Interviewbit
The len() function is used find the length(number of elements) of any python container like string, list, dictionary, tuple, etc. # For Lista = [1, 2, 3] print(len(a)) # For string a = "hello" print(len(a)) # For tuple a = ('1', '2', '3') print(len(a))
The ord() function in Python will return an integer that represents the Unicode Character passed into it. It takes a single character as a parameter. Example: # Print unicode of 'A'print(ord('A')) # Print unicode of '5' print(ord('5')) # Print unicode of '$' print(ord('$')) Output: 65 53 36 |
|
| 30. |
Python Comments |
|
Answer» Comments are lines of text/code in the program, which are ignored by the compiler during program execution. There are multiple types of comments in python:
We can write an Inline Comment by typing # followed by the comment. # Inline Comment to calculate sum of 2 numbersdef fun(a, b): return a + b
We can write a Multiline Comment by typing # followed by the comment in each of the lines. # Multiline# Comment # Function to calculate # sum of 2 numbers def fun(a, b): return a + b
Docstring comments are achieved by Typing the comment within triple quotes. (''' comment ''') '''This is a function to find sum of 2 numbers. This is an example of docstring comment. ''' def fun(a, b): return a + b |
|
| 31. |
Python Variables |
|
Answer» Variables are names given to data items that may take on one or more values during a program’s runtime.
Some examples are shown below: >>> variable_name = "Hello">>> variable_name 'Hello' >>> variableName = 123 >>> variableName 123 |
|
| 32. |
Python Data Types |
||||||||||
|
Answer» The table below lists the different data types in Python along with some examples of them:
|
|||||||||||
| 33. |
Python Arithmetic Operators |
||||||||||||||||||||||||||||
|
Answer» The Arithmetic Operators in the below table are in Lowest to Highest precedence.
Some examples are shown below: #Example for Addition>>> 1 + 3 4 #Example for Subtraction >>> 1 - 3 -2 #Example for Multiplication >>> 6 * 6 36 #Example for Floored Division >>> 4 // 2 2 #Example for Division >>> 3 / 2 1.5000 #Example for Modulo >>> 3 % 2 1 |
|||||||||||||||||||||||||||||