← Back to quizzesFree quiz

Fundamentals of Python Programming

Welcome to this comprehensive guide on the fundamentals of Python programming . Whether you are a beginner or brushing up on essential topics, this course will walk you through key ideas…

21 questions~11 min
Fundamentals of Python Programming — Qwi
0 / 21
Score: 0%
1

Which data type should be used to store a telephone number and why?

2

What will be the output of the expression `int(5.7)` in Python?

3

A programmer writes `x = 9; x = "Misty"; print(type(x))`. What does this illustrate about Python variables?

4

Given `x = 31; y = 15; print(x // y)`, which of the following statements is true?

5

When opening a file for reading, which mode string is optional because it is the default?

6

Which of the following best describes the difference between a `for` loop and a `while` loop?

7

What will be printed by the following code? ```python x = 25 print(x > 15 and x < 30) print(not (x > 15 and x < 20)) print(x > 35 or x < 12) ```

8

A developer needs to ensure that a user‑entered postcode follows the UK format. Which validation technique is most appropriate?

9

In the context of Python naming conventions, which style is recommended for constants?

10

What is the effect of using the `break` statement inside a `for` loop that iterates over a list of subjects?

11

When performing a binary search, why must the data be sorted beforehand?

12

Which of the following statements about the `range()` function is false?

13

What will be the output of the following code? ```python j = 9 j = "Misty" print(j) print(type(j)) ```

14

Which Python operator should be used to test whether variable `x` is greater than or equal to 20?

15

A function defined as `def add(a, b): return a + b` is called with `add(2, "3")`. What will happen?

16

What is the primary advantage of using a `dictionary` over a `list` for storing key‑value pairs?

17

In Python, what does the `pass` statement achieve inside an empty `for` loop?

18

Which of the following best explains why a `while` loop that never increments its counter can cause an infinite loop?

19

When using the `open()` function with mode `'x'`, what will happen if the file already exists?

20

Which sorting algorithm is described as having a best‑case performance of O(n²) and requiring no additional storage?

21

What is the purpose of a `try`/`except` block when validating user input?

Fundamentals of Python Programming: Core Concepts Explained

Welcome to this comprehensive guide on the fundamentals of Python programming. Whether you are a beginner or brushing up on essential topics, this course will walk you through key ideas such as data types, type conversion, dynamic typing, floor division, file handling, loop structures, boolean logic, and input validation. Each section is crafted to be SEO‑friendly, using clear headings, concise explanations, and practical examples that align with common search queries like "Python data types", "Python floor division", and "Python file mode".

1. Choosing the Right Data Type for a Telephone Number

When storing a telephone number, the string data type is the most appropriate choice. Unlike numeric types, a string preserves leading zeros, hyphens, parentheses, and any country code symbols.

  • Why not int? Integers drop leading zeros (e.g., 01234 becomes 1234) and cannot store characters like "+" or "-".
  • Why not float? Floats are designed for decimal arithmetic, not for fixed‑length identifiers.
  • Why not bool? Booleans represent only two states (True or False), which is insufficient for a phone number.

Storing phone numbers as strings also simplifies validation and formatting tasks, such as applying regular expressions or adding country prefixes.

2. Converting Float to Integer: int(5.7)

The expression int(5.7) returns 5. The int() constructor truncates the decimal part, effectively performing a floor operation toward zero.

  • It does not round; int(5.9) also yields 5.
  • If you need rounding, use round() or math.floor() for explicit floor behavior.

3. Python’s Dynamic Typing Explained

Consider the code snippet:

x = 9
x = "Misty"
print(type(x))

This demonstrates that variables in Python are dynamically typed. The type of a variable is determined by the value it currently holds, not by a declaration.

  • After assigning 9, x is an int.
  • Reassigning "Misty" changes x to a str.
  • The type() function always reflects the current value’s type.

Mnemonic: DYNAMIC – “Don’t Assign a Fixed Identity, Change It Anytime, Now You’ll See It’s Python.”

4. Understanding Floor (Integer) Division: The // Operator

Python provides the double‑slash operator (//) for floor division. It divides two numbers and discards any remainder, returning the largest integer less than or equal to the exact quotient.

x = 31
y = 15
print(x // y)  # Output: 2

Key points:

  • If both operands are integers, the result is an integer.
  • If either operand is a float, the result is a float that represents an integer (e.g., 7 // 2.0 yields 3.0).
  • Floor division is useful for pagination, chunking data, or any scenario where you need whole‑number counts.

Memory aid: “Double slash = Drop the remainder, keep the whole part.”

5. File Opening Modes: The Default is Read ("r")

When you open a file in Python without specifying a mode, the interpreter assumes the "r" (read) mode:

with open('data.txt') as f:
    content = f.read()

Other common modes include:

  • "w" – write (creates or truncates the file).
  • "a" – append (adds to the end of an existing file).
  • "x" – exclusive creation (fails if the file already exists).
  • Adding "b" (e.g., "rb") opens the file in binary mode.

6. Loop Structures: for vs. while

Both loops enable repetition, but they serve different purposes:

  • for loops iterate over a known collection or range. Use them when you know the number of iterations in advance.
    for i in range(5):
        print(i)
    
  • while loops continue until a condition becomes false. They are ideal for situations where the iteration count depends on runtime data.
    count = 0
    while count < 5:
        print(count)
        count += 1
    

Remember: “for loops iterate a known number of times; while loops iterate until a condition becomes false.”

7. Boolean Logic in Python

Understanding logical operators (and, or, not) is essential for controlling program flow. Examine the following code:

x = 25
print(x > 15 and x < 30)          # True
print(not (x > 15 and x < 20))    # True
print(x > 35 or x < 12)           # False

Explanation:

  • The first expression checks two conditions simultaneously; both are true, so the result is True.
  • The second expression negates a true statement, yielding True again.
  • The third expression uses or; since neither condition is true, the result is False.

8. Validating User Input: UK Postcode Format Check

When you need to ensure a postcode follows the UK pattern (e.g., SW1A 1AA), a format check using regular expressions is the most appropriate technique.

import re
pattern = r'^[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}$'
postcode = 'SW1A 1AA'
if re.match(pattern, postcode):
    print('Valid postcode')
else:
    print('Invalid postcode')

This approach validates both length and the specific arrangement of letters and numbers, which simple length or range checks cannot guarantee.

9. Recap of Key Takeaways

  • Use str for telephone numbers to preserve formatting.
  • int(5.7) truncates the decimal part, returning 5.
  • Python variables are dynamically typed; their type follows the assigned value.
  • The // operator performs floor division, discarding remainders.
  • Opening a file without a mode defaults to read ("r").
  • for loops iterate a known number of times; while loops depend on a condition.
  • Boolean expressions combine conditions with and, or, and not.
  • Validate complex patterns like UK postcodes with format checks (regular expressions).

10. Frequently Asked Questions (FAQ)

Can I store a phone number as an integer?

Technically you can, but you lose leading zeros and cannot include symbols such as "+" or "-". Storing it as a string is the industry‑standard practice.

What is the difference between / and //?

The single slash (/) performs true division and returns a float, while the double slash (//) performs floor division, returning the integer part of the quotient.

When should I use while instead of for?

Use while when the number of iterations cannot be determined before the loop starts, such as reading data until an end‑of‑file marker is reached.

11. Further Learning Resources

  • Official Python Tutorial – Comprehensive guide for beginners.
  • Real Python: Working with Strings – Deep dive into string handling and validation.
  • Real Python: While Loops – Practical examples of while loops.
  • Python re Module – Documentation for regular expression usage.