Top Python MCQs with Answers 1

The post contains 20 Top Python MCQs with Answers about basic concepts of the language. The quiz is about the Introduction to Python. Let us start with the Python MCQs with Answers

Online MCQs about Python with Answers

1. How can we tell what version of python we are currently using?

 
 
 
 

2. Suppose you have a dataframe called $df$. Which pandas method is used to create a histogram of a column in a dataframe?

 
 
 
 

3. What datatype would the following variable have main_data=read.csv("path/to/myfile.csv").

 
 
 
 

4. What is the primary instrument used in Pandas?

 
 
 
 

5. How do we create a dataframe using Pandas?

 
 
 
 

6. Which of the following is not important when writing Python code?

 
 
 
 

7. A data professional is working with a pandas dataframe named $sales$ that contains sales data for a retail website. The data professional wants to know the average price of an item. What code can he use to calculate the mean value of the Price column?

 
 
 
 

8. Given the variables below, determine which print statement would return False.
a = True or False
b = False and True
c = False and False

 
 
 
 

9. Before using pandas which code must first be run to make the library available?

 
 
 
 

10. What libraries do you use for data visualization.

 
 
 
 

11. What type of data can be stored in a list in python?

 
 
 
 

12. In Python, ————- typically contain a collection of functions and global variables.

 
 
 
 

13. Which of the following is not comparison operator (these return a bolean value of true or false).

 
 
 
 

14. How would you generate descriptive statistics for all the columns for the dataframe $df$.

 
 
 
 

15. What data type do you expect the column that contains price to be

 
 
 
 

16. Why is Python such a popular language?

 
 
 
 

17. Which python libraries were used to create the boxplots?

 
 
 
 

18. What does method df.dropna() do?

 
 
 
 

19. What is a Python library?

 
 
 
 

20. Which of the following are not functions?

 
 
 
 

What is Python?

Python is a powerful, versatile, and beginner-friendly high-level programming language.

  • Readability: With clear and simple syntax python resembles plain English. Therefore, Python code is easier to learn, understand, and write compared to some other programming languages.
  • Large Standard Library: Python comes with a very huge collection of built-in modules, functions, and libraries as a toolkit for many tasks without needing to write everything from scratch.
  • Versatility: Python is used in a wide range of applications, such as web development, data analysis, machine learning, scripting, scientific computing, etc.
  • Strong Community: Python has a large and active community of developers, providing extensive support, libraries, and learning resources.

Top Python MCQs with Answers

Python MCQs with Answers
  • What is the primary instrument used in Pandas?
  • What libraries do you use for data visualization.
  • What data type do you expect the column that contains price to be
  • Suppose you have a dataframe called $df$. Which pandas method is used to create a histogram of a column in a dataframe?
  • What type of data can be stored in a list in Python?
  • How do we create a dataframe using Pandas?
  • What does method df.dropna() do?
  • Which of the following is not important when writing Python code?
  • What datatype would the following variable have main_data=read.csv(“path/to/myfile.csv”).
  • Which Python libraries were used to create the boxplots?
  • Which of the following is not comparison operator (these return a boolean value of true or false).
  • Before using pandas which code must first be run to make the library available?
  • In Python, ————- typically contain a collection of functions and global variables.
  • A data professional is working with a pandas dataframe named $sales$ that contains sales data for a retail website. The data professional wants to know the average price of an item. What code can he use to calculate the mean value of the Price column?
  • Given the variables below, determine which print statement would return False. a = True or False b = False and True c = False and False
  • What is a Python library?
  • How can we tell what version of Python we are currently using?
  • Why is Python such a popular language?
  • How would you generate descriptive statistics for all the columns for the dataframe $df$.
  • Which of the following are not functions?
RFAQS.com R Programming Language

https://itfeature.com

https://gmstat.com

Simulating Coin Tossing: Game of Chance

Introduction to Simulating Coin Tossing

Simulation provides a straightforward way of approximating probabilities. For simulating a Game of chance of coin tossing, one simulates a particular random experiment (coin tossing, dice roll, and/or card drawing) a large number of times. The probability of an outcome is approximated by the relative frequency of the outcome in the repeated experiments.

The use of simulation experiments to better understand probability patterns is called the Monte Carlo Method.

Practical Example: Simulating Coin Tossing Experiment

Let person “A” and person “B” play a simple game involving repeated tosses of a fair coin. In a given toss, if the head is observed, “A” wins $1 from “B”; otherwise if the tail is tossed, “A” gives $1 to “B”. If “A” starts with zero dollars, we are interested in his fortune as the game is played for 50 tosses.

Simulating The Game in R using sample() Function

For the above scenario, one can simulate this game using the R function “sample()”. A’s winning on a particular toss will be $1$ or $-1$ with equal probability. His winning on 50 repeated tosses can be considered to be a sample of size 50 selected with replacement from the set {$1, -$1}.

option(width=60)
sample(c(-1, 1), size = 50, relapce = T)

# output
 [1] -1  1  1 -1 -1  1 -1  1  1 -1  1 -1  1  1 -1 -1  1 -1 -1 -1  1  1  1 -1 -1
[26]  1 -1  1 -1  1 -1 -1  1  1  1 -1 -1  1 -1 -1 -1  1 -1  1  1 -1  1 -1  1  1

Graphical Representation of the Simulations

One can graphically represent the outcome, as coded below. Note that the results will be different for each compilation of the code as samples are drawn randomly.

results <- sample( c(-1, 1), size = 50,replace = TRUE)

x = table(results)
names(x) = c("loss", "win")

barplot(x)
Simulating a Game of Chance of Coin Tossing

Extended Example

Suppose “A” is interested in his cumulative winnings as he plays this game. One needs to score his toss winnings in the variable $win$. The function “cumsum()” will compute the cumulative winnings of the individual values and the cumulative values are stored in “cam.win“.

win = sample(c(-1, 1), size = 50, replace = T)
cum.win = cumsum(win)

# Output for different execution 
 [1] -1 -2 -1 -2 -1  0  1  0 -1  0  1  0  1  2  1  2  1  2  3  4  5  6  7  6  5
[26]  4  5  4  5  6  7  6  7  8  9  8  7  6  5  4  5  4  3  2  1  0 -1 -2 -3 -4

 [1] 1 2 1 0 1 2 1 2 1 2 1 2 3 4 5 4 5 6 7 8 7 8 7 6 7 6 5 4 5 4 3 4 3 4 5 4 3 2
[39] 3 4 3 4 3 2 3 4 5 6 5 4

Extending and plotting the sequence of cumulative winnings for 4 games. For four games, the win/loss score is plotted in four combined (2 by 2) graphs, to visualize the situation in all four games.

par(mfrow = c(2, 2))
for (j in 1:4){
win = sample( c(-1, 1), size = 50, replace = TRUE)
plot(cumsum(win), type = “l”, ylim = c(-15, 15))
abline(h=0)
}

Four coin toss win loss change

The horizontal line in each graph is drawn at break-even. The points above the horizontal line show the win situation while the information below the horizontal line shows the loss to the player.

One can make a customized function for the situation discussed above. For example,

# customized function 
winloss <- function (n=50){
    win = sample(c(-1,1), size = n, replace = T)
    sum(win)
}

# Insights about win/ loss situation
F = replicate(1000, winloss() )

table(F)

# output
F
-22 -18 -16 -14 -12 -10  -8  -6  -4  -2   0   2   4   6   8  10  12  14  16  18 
  3   6   7  22  28  52  60  78  82 128  93 103  95  72  50  48  34  24   8   3 
 20  22  24 
  1   2   1 


par(mfrow = c(1, 1) )

plot(table(F))

Game of Change: Simulating coin Experiment

https://itfeature.com

https://rfaqs.com

Lexical Scoping in R Language

Introduction to Lexical Scoping

The Lexical Scoping in R Language is the set of rules that govern how R will look up the value of a symbol. For example

x <- 10

In this example, scoping is the set of rules that R applies to go from symbol $x$ to its value 10.

Types of Scoping

R has two types of scoping

  1. Lexical scoping: implemented automatically at the language level
  2. Dynamic scoping: used in select functions to save typing during interactive analysis.

Lexical scoping looks up symbol values based on how functions were nested when they were created, not how they are nested when they are called to figure out where the values of a variable will be looked up. You just need to look at the function’s definition.

Basic Principles of Lexical Scoping in R Language

There are four basic principles behind R’s implementation of lexical scoping in R Language:

Name Masking

The following example will illustrate the basic principle of lexical scoping

f <- function(){
      x <- 1
      y <- 2
      c(x, y)
}

f()
Name Masking in R Functions

If a name is not defined inside a function, R will look one level up.

x <- 2
g <- function(){
       y <- 1
       c(x,y)
}
g()

The same rules apply if a function is defined inside another function: look inside the current function, then where the function was defined, and so on, all the way up to the global environment, and then on to other loaded packages.

x <- 1
h <- function(){
       y <- 2
   i <- function(){
       z <- 3
       c(x,y,z)
   }
i()
}

h()
r(x,y)

The same rules apply to closures, functions created by other functions. The following function, j( ), returns a function.


How does R know what the value of y is after the function has been called? It works because k preserves the environment in which it was defined and because the environment includes the value of y.

j <- function(x){
       y <- 2
    function(){
       c(x,y)
    }
}
k<-j(1)
k()
rm(j,k)
Name Masking in R Example

Functions vs Variables

Finding functions works the same way as finding variables:

l <- function(x){
       x+1
}
m <- function(){
l <- function(x){
       x*2
}
  l(10)
}
m()
Lexical Scoping Functions VS Variables in R

If you are using a name in a context where it’s obvious that you want a function (e.g. f(3)), R will ignore objects that are not functions while it is searching. In the following example, n takes on a different value depending on whether R is looking for a function or a variable.

n <- function(x) {
      x/2
}
o <- function(){
      n <- 10
   n(n)
}
o()

Fresh Start

The following questions can be asked (i) What happens to the values in between invocation of a function? (ii) What will happen the first time you run this function? and (iii) What will happen the second time? (If you have not seen exists() before it returns TRUE if there’s a variable of that name, otherwise it returns FALSE).

j <- function(){
       if(!exists("a")) {
         a <- 1
       } else {
         a<-a+1
       }
    print(a)
          }
j()

From the above example, you might be surprised that it returns the same value, 1 every time. This is because every time a function is called, a new environment is created to host execution. A function has no way to tell what happened the last time it was run; each invocation is completely independent (but see mutable states).

Dynamic Lookup

Lexical scoping determines where to look for values, not when to look for them. R looks for values when the function is run, not when it’s created. This means that the output of a function can be different depending on objects outside its environment:

f <- function() {
       x
}
x <- 15
f()

x <- 20
f()

You generally want to avoid this behavior because it means the function is no longer self-contained.
One way to detect this problem is the findGlobals() function from codetools. This function lists all the external dependencies of a function:

f <- function{ 
     x + 1
}
codetools::findGlobals(f)
Lexical Scoping Dynamic Lookup in R


Another way to try and solve the problem would be to manually change the environment of the function to the emptyenv(), an environment that contains absolutely nothing:

environment(f) <- emptyenv()

This doesn’t work because R relies on lexical scoping to find everything, even the + operator. It’s never possible to make a function completely self-contained because you must always rely on functions defined in base R or other packages.

Since all standard operators in R are functions, you can override them with your alternatives.

'(' <- function(e1) {
      if(is.numeric(e1) && runif(1)<0.1){
         e1 + 1
      } else {
        e1
      }
}
replicate (50,(1+2))

A pernicious bug is introduced: 10% of the time, 1 will be added to any numeric calculation inside parenthesis. This is another good reason to regularly restart with a clean R session!

Bound Symbol or Variable

If a symbol is bound to a function argument, it is called a bound symbol or variable. In case, if a symbol is not bound to a function argument, it is called a free symbol or variable.

If a free variable is looked up in the environment in which the function is called, the scoping is said to be dynamic. If a free variable is looked up in the environment in which the function was originally defined the scoping is said to be static or lexical. R, like Lisp, is lexically scoped whereas R and S-plus are dynamically scoped.

y = 20
foo = function(){
  y = 10  #clouser for the foo function
  function(x) {
    x + y
    }
}
bar=foo()

Foo returns an anonymous function.

bar=foo() is a function in global like foo. $x + y$ is created in the foo environment not in global. Foo has a function as a return value, which is then bound to bar the global environment. Note that anonymous is a function that has no name.

https://itfeature.com

https://gmstat.com