Python Workbook For Absolute Beginners (Part 1) (BooksRack - Net)
Python Workbook For Absolute Beginners (Part 1) (BooksRack - Net)
[Part 1]
by
Koding Success
Correct Answer/Explanation:
Python is a high-level, interpreted, object-oriented, and interactive
programming language. It is designed to be highly readable and makes use of
English keywords frequently in place of punctuation used in other languages.
Also, compared to other languages, Python has fewer syntactical
constructions.
Question 2
What are the key features of Python?
Correct Answer/Explanation:
Question 3
In what areas does Python find major applications?
Correct Answer/Explanation:
Data Science
Software Development
Database Access
Machine Learning (ML)
Network Programming
Web Application Development
Artificial Intelligence (AI)
Applications in Business
Applications in Education
Graphic User Interface (GUI)
Automation
Games, 3D Graphics etc.
Question 4
What are variables in Python?
Correct Answer/Explanation:
Variables are “containers” that hold you values. And just as the name
implies, it can be changed to hold a different value.
Question 5
What are the supported data types in Python?
Correct Answer/Explanation:
Python supports five standard data types:
Tuples—Much like a list, with the differences been that it is immutable (i.e.
we cannot change a value in it) and it is declared using a round bracket ( ).
Question 6
What are the mutable and immutable built-in data types in Python?
Correct Answer/Explanation:
Mutable (that can be changed) built-in data types in Python are:
Lists
Sets
Dictionaries
Immutable (that cannot be changed) built-in data types in Python are:
Strings
Numbers
Tuples
Question 7
Is Python a case-sensitive language?
Correct Answer/Explanation:
A language is said to be case-sensitive if it differentiates between identifiers
like myname and Myname. To put it in another way, it cares about case—
lowercase or uppercase. Let’s verify this with Python:
As you can observe, we got a NameError which says “name ‘Myname’ is not
defined” from the output of this code. This goes to show that Python is
indeed case-sensitive.
Question 8
How do you get an input from a user?
Correct Answer/Explanation:
To get an input from a user, we use the function input ( ). In Python 2, we had
another function which is raw_input ( ).
The input ( ) function usually take, as an argument, the text to be displayed
for the task:
For string input:
Question 9
Write a simple program that accepts the user’s name and then greet the
user.
Correct Answer/Explanation:
Code:
Output:
Question 10
Is it necessary to declare variables with data in Python?
Correct Answer/Explanation:
No, it is not necessary. Unlike languages like C where you have to declare
variables with data before using them, Python is a dynamically typed
language. This means that the Python interpreter automatically identifies the
data type of a variable according to the type of value assigned to the variable.
Question 11
What action do //, %, and ** operators perform in Python?
Correct Answer/Explanation:
For floor division, which will return the integer part of the result, we use //
operator.
Question 12
Write a code to sort out a numerical list containing these integers: 16, 7,
25, 4, 19, 28, 12
Correct Answer/Explanation:
Question 13
In a dictionary, how do you get a list containing all the keys?
Correct Answer/Explanation:
To get a list containing the keys in a dictionary, we use the keys( ) function.
Let’s see how we can do that.
Question 14
How do you get a list of all the values in a dictionary?
Correct Answer/Explanation:
To get a list containing all the values in a dictionary, we use the values( )
function.
Let’s also see how we can do that.
Question 15
How do you work with numbers other than those in the decimal number
system?
Correct answer/Explanation:
With Python, it is possible to type in other number systems such as binary,
octal, and hexadecimal.
Binary numbers (in base 2) are only made up of 0 and 1. To type a number
in binary, we use the prefix 0b or 0B.
Octal numbers (base 8) usually have digits from 0 to 7. The prefix used in
octal numbers is 0o or 0O.
Hexadecimal numbers (in base 16) usually have digits from 0-9 and letters
a-f. The prefix used here is 0x or 0X.
Question 16
What is slicing in Python?
Correct Answer/Explanation:
Slicing is a technique that let us retrieve only a part of a list, tuple, or string.
To implement slicing, a slicing operator [ ] is used.
Question 17
How do you convert an integer to a string and vice versa?
Correct Answer/Explanation:
To convert an integer to a string, we use the str function.
To convert a string to an integer, we use int function.
Question 18
What is the importance of indentation in Python?
Correct Answer/Explanation:
Indentation is important and even a compulsory part of Python syntax.
Python uses indentation as a way of defining the scope and extent of the
block of codes, just as all programming languages has some way of doing
that. Indentation brings better readability to the code, which may be the
reason why Python has made it compulsory.
Question 19
What is the assignment operator in Python?
Correct Answer/Explanation:
An assignment operator (=) assigns a value to a variable.
Question 20
How will you remove a recurring or duplicate element from a list?
Correct Answer/Explanation:
To do that, we can turn this list to a set.
Question 21
If you are given the first and last names of all students in a class, which
data type will you most likely use to store it?
Correct Answer/Explanation:
A dictionary can be used here. Here is an example:
Question 22
What is PEP 8 in Python?
Correct Answer/Explanation:
PEP 8 is a coding convention, a set of recommendations, that lets us write
more readable code in Python.
Question 23
In what ways is Python different from Java?
Correct Answer/Explanation:
Here in the table below is some comparisons of Python vs Java.
Java Python
Statically typed. Dynamically typed.
Needs braces. Mandates indentation
Java is verbose i.e. the codes are Python is simple and concise
usually long.
In terms of speed, Java is faster. Python is slower.
Average in Data Science and Excellent in Data Science and
Machine Learning applications. Machine Learning applications.
Question 24
What are negative indices?
Correct Answer/Explanation:
A negative index begins searching from the right, unlike the positive one that
begins from the left and start with zero.
Let’s use a list for an example:
Question 25
What is the help( ) and dir( ) utility in Python?
Correct Answer/Explanation:
help( )
The help( ) utility let you check the name of any module, keyword, or topic to
get help on writing Python programs and using Python modules. It can be
accessed by just typing “help( )” into the Python interpreter.
In the help( ) utility, I typed in “symbols” and this is the output:
dir( )
The dir( ) utility displays all the members of an object (any kind).
Let’s check out the dir of a string i.e. dir(str):
Question 26
Up to how many arguments can the range ( ) function take?
Correct answer/Explanation:
In Python, the range function can take up to 3 arguments. Let’s take a look at
it one after the other.
i. One argument
If only one argument is passed, it will be taken as the stop value. So the start
value is 0, and the step value +1.
ii. Two arguments
When we pass two arguments, then the first will be the start value, and the
second will be the stop value.
Question 27
What are sets in Python?
Correct Answer/Explanation:
In Python, sets are collections of unique but unordered items.
Two things to note in sets are:
Note: whenever a set is created from a list, it will come out sequentially—
irrespective of whether the list from which it is created is sequentially ordered
or not.
Question 28
Using the print function to evaluate, how can you convert a user input in
Celsius to Fahrenheit?
Correct Answer/Explanation:
Code:
Output:
Question 29
What are relational operators?
Correct Answer/Explanation:
Relational operators are used in the relation and comparison of one value to
another.
Less than (<)— if the value on the left is lesser, it correctly returns True.
Less than or equal to (<=)—if the value on the left is less than or equal to
that on the right, it returns True.
Greater than (>)—if the value on the right is greater, it correctly returns
True.
Greater than or equal to (>=)—if the value on the left is greater than or
equal to than on the right, it returns True.
Equal to (= =)—if two value are equal or the same, it returns True.
Question 30
How do you perform some basic math operations like square root,
power, factorial etc. using the math module?
Correct Answer/Explanation:
First, you have to import the math module by saying:
import math or import math as m
Question 31
How is a comment declared in Python?
Correct Answer/Explanation:
Languages like C++ have multiline comments, but in Python, there’s nothing
of such. To declare a comment in Python, you have to start with hash or
octothorpe (#). Any string of words following a hash is taken as a comment,
and the interpreter ignores it.
Question 32
Given a list containing 1, 3, 6, 8, how do you insert an object at a
specified index?
Correct Answer/Explanation:
a = [1, 3, 6, 8]
To insert an object at any index on a list, we use insert. The first argument is
the index at which to insert and the second argument is the value to insert.
Let’s insert 10 at the third index.
Question 33
How do you convert a string into a lowercase or uppercase?
Correct Answer/Explanation:
To convert a string into a lowercase, we use the lower ( ) method.
Question 34
What are some other functions we can perform on a string?
Correct Answer/Explanation:
To check if a string is in title case using istitle( ) method
Question 35
How do you count the number of vowels in a string?
Correct Answer/Explanation:
To check the number of vowels in a given string, make sure you enter a string
that contains words.
Code:
Output:
Question 36
What purpose do bytes serve in Python?
Correct Answer/Explanation:
bytes( ) is an in-built Python function that returns an immutable bytes object.
Let’s see some examples:
Question 37
What is concatenation in Python?
Correct Answer/Explanation:
It is a way of adding two or more strings using the ‘+’ symbol.
Question 38
Explain Python list comprehension
Correct Answer/Explanation:
Python list comprehension is a way of declaring a list in one line of code. For
better understanding, let’s see some examples.
Question 39
What is the output of the following code?
Correct Answer/Explanation:
Just like slice has been talked about in question 11, the first slice here (text
[:3]) gives us “s t u” and other slice (text [:3]) gives us “ v w x y z”.
Question 40
How is the length of a string determined?
Correct Answer/Explanation:
This is simple and straightforward. We only need to call the function len ( )
on the string we want to determine the length of.
Question 41
How is a block defined in Python?
Correct Answer/Explanation:
As part of coding convention, for any statements, we might possibly need to
define a block of code under them.
However, unlike languages such as C++, Java, C#, and JavaScript that
embrace curly braces as the primary symbol for blocks, Python does not
support curly braces.
What this means is that we must end such statements with colons (:) and then
indent the blocks under those with the same amount.
Question 42
How long can an identifier be in Python?
Correct Answer/Explanation:
Based on the official Python documentation, an identifier can be as long as
you want. But PEP-8 suggests that you maintain a maximum limit of 79
characters for all lines. Also, PEP-20 says “readability counts”. Thus, a very
long identifier will go against PEP-8 and PEP-20.
Aside from that, there are some certain rules we must abide with to name an
identifier:
Question 43
What are logical operators in Python?
Correct Answer/Explanation:
There are three logical operators in Python: and, or, not
Question 44
If you want to print a string five times in a row, how will you do it?
Correct Answer/Explanation:
Question 45
You are given a list, how will you convert it to a string?
Correct Answer/Explanation:
To convert the given list to a string, we’ll make use of the join( ) function.
Question 46
How will you print an output in a single line?
Correct Answer/Explanation:
To print an output in a single line in Python, the end=” “ function is used.
Let’s see an example.
Question 47
What are identity operators in Python?
Correct Answer/Explanation:
These operators (“is” and “is not”) tells us if two values have the same
identity.
Let’s see some examples:
Question 48
By getting values from a user, use the math function to perform as many
arithmetic operations as you can.
Correct Answer/Explanation:
Just like in Question 30 where we first made use of the math module, we’ll
also be making use of it to perform up to nine arithmetic operations.
Code:
Output:
Question 49
Also using the math module, how can you find the area of a circle and
the volume of a sphere?
Correct Answer/Explanation:
Code:
Output:
Question 50
How do you turn a string to a tuple?
Correct Answer:
Question 51
Using a while loop, write a Python code for increment.
Correct Answer/Explanation:
First, we initiate a counter by setting i = 1, then we put in the while statement,
and finally we set the increment by saying i += 1 and this will increase by 1
up till 10.
Code:
Output:
Question 52
What is the difference between a .pyc and .py file?
Correct Answer/Explanation:
While both file formats are designed to hold bytecode, the compiled version
of a Python file is .pyc. It has platform-dependent bytecode. Thus, we can
execute it on any kind of platform that supports the .pyc format. Python
generates it by default to improve performance (in terms of load time, and not
speed).
Question 53
Write a code, using for loop, to print out a pattern of stars beginning
with the first star and ending with the fifth stars.
Correct Answer/Explanation:
Code:
Output:
Question 54
Using the if statement, write a code to determine if a user input is greater
than or less than a given value (100).
Correct Answer/Explanation:
Code:
Output:
Question 55
What are membership operators in Python?
Correct Answer/Explanation:
With these operators (‘in’ and ‘not in’), we can confirm if a value is a
member in another value or not.
Question 56
What are bitwise operators in Python?
Correct Answer/Explanation:
These operators operate on value bit by bit. To understand how bitwise
operators work, you need to have the basic understanding of how a truth table
works.
There are six bitwise operators:
Binary One’s Complement (~) : This is the reverse of a binary format.
Bitwise AND (&): This performs & on each bit pair.
Bitwise XOR (^): On each bit pair, this performs the exclusive-OR
operation.
Binary Left-Shift (<<): This operator shifts the bits to the left according to
the specified amount.
Basically, what this operator does is that it shifts 1010 (which is the binary
format of 10) to two places to the left which gives us 101000.00. Converting
101000 to a whole number gives 40.
Binary Right-Shift (>>): This operator shifts the bits to the right according
to the specified amount.
Also, what this operator does is that it shifts 1010 (which is the binary format
of 10) to two places to the right which gives us 10.00. Converting 10 to a
whole number gives 2.
Question 57
Explain the pass, break, and continue statements in Python?
Correct Answer/Explanation:
Pass
There might be times in our code when we have not decided what to do yet,
but must type in something to avoid syntax error. In a case like this, we make
use of the pass statement.
Break
The break statement breaks or jumps out of a loop/block. In other words, the
break statement will skip the entire iteration.
Continue
The continue statement will not jump out of the loop/block, but skips to the
next iteration.
Question 58
Write a code that will get a number of values (let’s say 4) from a user
and find its average value.
Correct Answer/Explanation:
First, your code should begin with getting the total number of values and then
the individual values from the user.
Next your code should give an error message when a number is not a positive
integer.
Finally, your code should evaluate the average value of the numbers entered
and print it out.
Code:
Output:
Question 59
How do you write a code to check if a number is odd or even?
Correct Answer/Explanation:
To check if an integer is odd or even, we use the modulus operator (%).
If an integer divided by 2 gives a remainder of 1, then it is odd. But if an
integer is divided by 2 and doesn’t give any remainder, then it is even.
Code:
Output:
Question 60
Write a code with the if statement to check whether a user is eligible to
vote or not.
Correct Answer/Explanation:
Code:
Output:
Question 61
Write a code to find the greatest of three integers that will be given by a
user.
Correct Answer/Explanation:
In this code, we’ll make use of the if and elif statements.
elif means else if—which means it will only check for other conditions
assuming the if statement is false.
Code:
Output:
Question 62
With the use of a nested while, print out the following on a single line:
“Hi, hope you’re keeping safe?”
Correct Answer/Explanation:
First off, a nested while is a while statement inside another while statement.
The sentence above can be printed using a single while statement, but we’ll
be using a nested while for you to know how it works and be able to deploy it
in later coding.
Code:
Output:
Question 63
How do you work with a do-while loop in Python?
Correct Answer/Explanation:
Python does not support do-while loops, so you can’t work with them. You
can only work with do-while loops in languages like C++.
Question 64
If it ever happens that you are stuck in an infinite loop, how will you
break out of it?
Correct Answer/Explanation:
Every programmer accidentally writes an infinite while loop from time to
time. To break out of an infinite loop, press Ctrl+C on your keyboard. This
command interrupts the execution.
In order to demonstrate this, let’s create an infinite loop.
Code:
Output:
Question 65
Given a string “I love Python”, write a code to print only up to the letter
t.
Correct Answer/Explanation:
Question 66
Using the same string in Q65, write a code to print everything except the
spaces.
Correct Answer/Explanation:
Question 67
What are arrays in Python?
Correct Answer/Explanation:
Here are what you need to know about arrays in Python:
➢ Arrays are similar to list with the only difference being that you
need to have all the values be of the same type.
➢ They are flexible to work with and it offers you certain methods to
work with. For example, if you want to add an element you can use
append. You can also use index to get the index number of a
particular value.
➢ Arrays don’t have specific size, which means you can expand or
shrink it.
Output:
Question 68
Write a code to accept the values of an array from a user and then print
out the array.
Correct Answer/Explanation:
Code:
Output:
Question 69
What are some of the operations you can perform on an array?
Correct Answer/Explanation:
There are quite a number of operations that can be performed on an array.
But we can’t do this with an array itself because it does not support these
operations.
So for these operations to be carried out, we have to make use of a special
package in Python called numpy.
Adding a number to each value of an array
Question 70
Write a code to print your system OS name and platform?
Correct Answer/Explanation:
Code:
Output:
Question 71
What is a function in Python?
Correct Answer/Explanation:
Functions are used to execute a sequence of statements. You need to give a
name to your function based on the task it’ll perform.
To declare a function, the def keyword is used.
And for you to create your own function, two steps are involved:
Output:
Question 72
How does a function return value?
Correct Answer/Explanation:
Apart from a function executing a task, it can also return you a value. return
is the keyword used in function to return a value.
To see how a function return values, let’s create a function that checks a list
of integers and then print out the number of even and odd integers contained
in the list.
Code:
Output:
Correct Answer:
Code:
Output:
Question 74
Explain parameter-passing mechanism in Python.
Correct Answer:
Python, in passing its parameter to a function, uses pass-by-reference. If you
change a parameter within a function, the change will reflect in the calling
function. This is its behavior by default. But when we pass literal arguments
such as strings, numbers, or tuples, they pass by value. This is mainly
because they are immutable.
***************************