0% found this document useful (0 votes)
10 views9 pages

Python Quiz and Coding Exercises

The document is a Python tutorial that includes multiple choice questions, true/false statements, coding exercises, and code completion tasks. It covers various Python concepts such as variable naming, data types, loops, functions, and basic algorithms. Additionally, it provides a dataset example for data manipulation using pandas.

Uploaded by

SSA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Python Quiz and Coding Exercises

The document is a Python tutorial that includes multiple choice questions, true/false statements, coding exercises, and code completion tasks. It covers various Python concepts such as variable naming, data types, loops, functions, and basic algorithms. Additionally, it provides a dataset example for data manipulation using pandas.

Uploaded by

SSA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Tutorial

Section 1: Multiple Choice Questions

1. Which of the following is a valid variable name in Python?


A. 2ndValue
B. value@
C. _value
D. class

2. What does len("Python") return?


A. 5
B. 6
C. 7
D. Error

3. What is the output of print(3 ** 2)?


A. 6
B. 9
C. 5
D. 8

4. Which of the following is a mutable data type in Python?


A. tuple
B. string
C. list
D. int

5. What does print(type(10.5)) display?


A. <class 'int'>
B. <class 'float'>
C. <class 'double'>
D. <class 'str'>

6. What is the correct way to write a comment in Python?


A. // This is a comment
B. # This is a comment
C. <!-- This is a comment -->
D. % This is a comment

7. Which loop will run at least once even if the condition is false?
A. while
B. for
C. do-while
D. None of the above

8. What is the output of print("5" + "5")?


A. 10
B. 55
C. Error
D. None

9. What is the keyword used to define a function in Python?


A. function
B. def
C. define
D. func

10. What does the expression 10 // 3 evaluate to?


A. 3
B. 3.33
C. 4
D. 3.0

11. Which of the following will result in a syntax error?


A. print("Hello")
B. if True print("Yes")
C. x = 5 + 4
D. while x > 0: x -= 1

12. What does input() return in Python?


A. Integer
B. Float
C. String
D. Boolean

13. What is the purpose of indentation in Python?


A. Improve performance
B. Denote code blocks
C. Add comments
D. Declare variables

14. Which statement is used to skip the current iteration in a loop?


A. break
B. stop
C. skip
D. continue
Section 2: True / False

1.

def multiply(x, y):


return x * y
print(multiply(2, 4))

Output: 8
A. True
B. False

2.

x = 10
if x < 5:
print("Low")
else:
print("High")

Output: High
A. True
B. False

3.

for i in range(3):
print(i)

Output: 0 1 2
A. True
B. False

4.

name = "Alice"
print(name[5])

Output: Error
A. True
B. False
5.

x = "10"
y = 10
print(x == y)

Output: True
A. True
B. False

6.

def greet():
print("Hello")
greet()

Output: Hello
A. True
B. False

Section 3: Write Code

Q1. Write an algorithm and a Python code that converts temperature from Celsius to Fahrenheit.
Formula: F = (C × 9/5) + 32

• Start.

• Ask the user to input a temperature in Celsius.

• Apply the formula: F = (C × 9/5) + 32.

• Display the result.

• End.

# Step 1: Input temperature in Celsius


celsius = float(input("Enter temperature in Celsius: "))

# Step 2: Apply the conversion formula


fahrenheit = (celsius * 9/5) + 32
# Step 3: Display the result
print(f"The temperature in Fahrenheit is: {fahrenheit:.2f}°F")

Q2. Write a program to check if a given number is a prime number.

• Start.

• Ask the user to enter a number.

• If the number is less than 2, it is not prime.

• For all numbers from 2 to sqrt(number), check:

• If the number is divisible by any, it is not prime.

• If no divisibility is found, the number is prime.

• Display the result.

• End.

import math

# Step 1: Input number


num = int(input("Enter a number: "))

# Step 2: Check for prime


if num < 2:
print(f"{num} is not a prime number.")
else:
is_prime = True
for i in range(2, int([Link](num)) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Q3. Write a program to calculate factorial of a number using a loop.

• Start.

• Ask the user to enter a non-negative integer.

• Initialize factorial = 1.
• Loop from 1 to the number:

• Multiply factorial by the current number.

• After the loop, display the factorial.

• End.

# Step 1: Input number


num = int(input("Enter a non-negative integer: "))

# Step 2: Initialize factorial


factorial = 1

# Step 3: Calculate factorial using loop


if num < 0:
print("Factorial does not exist for negative numbers.")
else:
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is: {factorial}")

Q4. Write a program that finds the sum of all odd numbers from 1 to a user-given number N.

• Start.

• Ask the user to enter a positive integer N.

• Initialize sum = 0.

• Loop from 1 to N:

• If the number is odd, add it to sum.

• After the loop, display the sum.

• End.
N = int(input("Enter a positive integer N: "))

# Step 2: Initialize sum


sum_odds = 0

# Step 3: Loop to find sum of odd numbers


for i in range(1, N + 1):
if i % 2 != 0:
sum_odds += i

# Step 4: Display the result


print(f"The sum of all odd numbers from 1 to {N} is: {sum_odds}")

Section 4: Complete the Missing Code

Q1. Fill in the missing parts to complete this BMI calculator. From the list

Use the following words to file the blanks listed below:

weight , bmi, float

# Calculate BMI from weight and height


weight = _float(input("Enter weight in kg: "))
height = float(input("Enter height in meters: "))
bmi = _weight_/ (height ** 2)
print("BMI is:",_bmi_)

Q2. Fill in the missing parts to get the maximum of three numbers.

Use the following words to file the blanks listed below:


else , print , elif

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a > b and a > c:
print("Max is:", a)
elif _ b > c:
print("Max is:", b)
else :
print("Max is:", c)

Q3. Complete the following function to return the square of a number.

Use the following words to file the blanks listed below:


input , def , n

_def_____ square(x):
return x * x
n = int(input("Enter a number: "))
print("Square:", square(_n_))

Q4. Complete the code that sums integers in a list.

Use the following words to file the blanks listed below:


numbers , total , num

numbers = [1, 3, 5, 7, 9]
total = 0
for ___num__ in __numbers___:
___total____+= num
print("Total:", total)

1. You are given a dataset uae_energy_consumption.csv that captures energy usage data
across the UAE. The dataset includes details such as sector type, energy consumption,
units, and emirate. Here’s an overview of the dataset:
Energy_Consumption Cost
Record_ID Sector Units Emirate
(kWh) (AED)

2001 Residential 1500 2 450 Dubai

Abu
2002 Commercial 2500 3 750
Dhabi

2003 Industrial 5000 5 1250 Sharjah

2004 Agricultural 800 1 200 Ajman

2005 Residential 1200 2 360 Dubai

− Use the following commands to complete the tasks listed below:


− List of Commands: { head(), total, read_csv, head(3), dropna, set_index,
rename, unique(), sum() }

import pandas as pd

# Tasks

A. Load the dataset file uae_energy_consumption.csv into a DataFrame named df.


df = pd. read_csv ("uae_energy_consumption.csv")
B. Display the first three rows of the DataFrame. [0.5 Mark]
print(df. head(3))
C. Drop any rows containing missing values.
df. dropna (axis=0, how='any', inplace=True)
D. Set Record_ID as the index.
df. set_index ("Record_ID", inplace=True)
E. Calculate and display the total energy consumption across all records in kWh.
print(df["Energy_Consumption (kWh)"].sum())
F. Display all unique sector types in the dataset.
print(df["Sector"].unique())

You might also like