← Back to quizzesFree quiz

Fundamentals of Python Syntax and Data Types

Welcome to this comprehensive module on Python fundamentals. Whether you are a beginner or need a quick refresher, this course will guide you through the essential syntax, operators, and…

10 questions~5 min
Fundamentals of Python Syntax and Data Types — Qwi
0 / 10
Score: 0%
1

Which operator correctly assigns the value 5 to variable `a` in Python?

2

What is the result of `print(10 % 3)` in Python?

3

Which built‑in function returns the data type of a variable `x`?

4

If `my_set = {1, 2, 3}` and `my_set.add(2)` is executed, what will be printed?

5

What does the expression `print(True or False)` output?

6

Which slicing syntax extracts characters from index 2 up to but not including index 5 in the string `alphabet = "abcdefg"`?

7

What will be the type of variable `y` after executing `x = 123; y = int(x)`?

8

When attempting to access a non‑existent key in a dictionary using `dict[key]`, what occurs?

9

Which of the following statements about Python `list` objects is true?

10

What is the output of the following code? ``` my_list = [10, 20, 30, 40] print(my_list[-2]) ```

Fundamentals of Python Syntax and Data Types

Welcome to this comprehensive module on Python fundamentals. Whether you are a beginner or need a quick refresher, this course will guide you through the essential syntax, operators, and built‑in data types that form the backbone of Python programming. By the end of the lesson you will be able to write correct assignment statements, understand modulo arithmetic, use type introspection, manipulate sets and dictionaries, and apply logical operators and slicing effectively.

1. Assignment Operators in Python

In Python, the assignment operator is the single equals sign (=). It stores the value on the right‑hand side into the variable on the left‑hand side.

  • a = 5 assigns the integer 5 to the variable a.
  • Using == performs a comparison, not an assignment. It returns True or False and is often used in conditional statements.
  • The := operator, known as the walrus operator, was introduced in Python 3.8 and is used for assignment within expressions, but it cannot replace a simple = statement.
  • Symbols such as <- belong to other languages (e.g., R) and are not valid in Python.

Correct usage example:

a = 5
print(a)  # Output: 5

2. Modulo Operator (%)

The modulo operator returns the remainder after division of one number by another. It is frequently used for tasks such as determining even/odd status, cycling through indices, or extracting digits.

Example:

print(10 % 3)  # Output: 1

Explanation: 10 divided by 3 equals 3 with a remainder of 1, so the expression evaluates to 1. This operator works with integers and floats, but the result is always the remainder of the division.

3. Determining the Data Type of a Variable

Python provides the built‑in function type() to retrieve the class of an object. Knowing the type is crucial for debugging and for writing type‑aware code.

x = 42
print(type(x))  # Output: 

y = "hello"
print(type(y))  # Output: 

Other functions like print() display values, while typeof() and class() do not exist in Python's standard library.

4. Working with Sets

Sets are unordered collections of unique elements. Adding an element that already exists does not change the set.

my_set = {1, 2, 3}
my_set.add(2)
print(my_set)  # Output: {1, 2, 3}

Key points about sets:

  • Duplicates are automatically ignored.
  • Sets are mutable; you can add or remove items.
  • Because they are unordered, the printed representation may vary, but the content remains the same.

5. Logical Operators: or and and

Python evaluates logical expressions using short‑circuit semantics. The expression True or False evaluates to True because the or operator returns the first truthy operand.

print(True or False)  # Output: True
print(False and True)  # Output: False

Understanding these operators helps you write concise conditional statements and control flow.

6. String Slicing

Slicing extracts a subsequence from a sequence type (string, list, tuple). The syntax sequence[start:stop] includes the element at start and excludes the element at stop.

alphabet = "abcdefg"
print(alphabet[2:5])  # Output: "cde"

Explanation: Indexing starts at 0, so positions 2, 3, and 4 correspond to c, d, and e. The character at index 5 (f) is not included.

Common variations:

  • alphabet[:5] – from the start up to index 5 (exclusive).
  • alphabet[2:] – from index 2 to the end.
  • alphabet[-3:] – last three characters.

7. Type Conversion (Casting)

Python allows explicit conversion between compatible types using functions such as int(), float(), str(), and list(). When you execute x = 123; y = int(x), the variable y becomes an integer.

x = 123
y = int(x)
print(type(y))  # Output: 

Even if x were already an integer, calling int() simply returns a new integer object with the same value.

8. Accessing Dictionary Keys

Dictionaries map immutable keys to values. Attempting to retrieve a value with a non‑existent key using the bracket notation (dict[key]) raises a KeyError.

person = {"name": "Alice", "age": 30}
print(person["name"])   # Output: Alice
print(person["city"])   # Raises KeyError

If you need a safe lookup, use the get() method, which returns None (or a default you provide) instead of raising an exception:

print(person.get("city"))          # Output: None
print(person.get("city", "NY"))   # Output: NY

9. Summary of Core Concepts

  • Assignment: Use = to store values.
  • Modulo: % returns the remainder; 10 % 3 = 1.
  • Type Introspection: type(variable) reveals the object's class.
  • Sets: Unique, unordered collections; duplicate adds are ignored.
  • Logical Operators: or returns True if any operand is true; and returns True only if all are true.
  • Slicing: sequence[start:stop] extracts a range, excluding the stop index.
  • Casting: Functions like int() convert values to the desired type.
  • Dictionaries: Accessing a missing key with [] raises KeyError; use get() for safe retrieval.

10. Practice Exercises

Test your understanding with these short tasks. Write the code, run it, and verify the output matches the expected result.

  1. Assign the string "Python" to a variable language and print its type.
  2. Calculate 27 % 4 and explain why the result is what it is.
  3. Create a set {"apple", "banana"}, add "apple" again, and display the set.
  4. Given data = {"id": 101, "status": "active"}, safely retrieve the value for the key "role" using get() with a default of "guest".
  5. Slice the string "programming" to obtain "gram" using appropriate indices.

Review the solutions after attempting the exercises to reinforce the concepts covered.

11. Frequently Asked Questions (FAQ)

Can I use == for assignment? No. == checks equality and returns a Boolean value. Use = for assignment. What happens if I slice with a start index larger than the stop index? You will get an empty sequence because slicing respects the direction; seq[5:2] returns '' for strings. Is there a way to add multiple items to a set at once? Yes. Use the update() method: my_set.update([4,5]). How can I avoid a KeyError when accessing a dictionary? Use dict.get(key, default) or check key in dict before accessing.

12. Next Steps

Now that you have mastered the basics, consider exploring more advanced topics such as list comprehensions, function definitions, and object‑oriented programming. Each of these builds on the foundations covered here and will enable you to write more powerful and efficient Python code.