Semantics (Meaning and Logic) Flashcards

Semantics in Python

1
Q

Semantics

A

Semantics focuses on the intended meaning of the code.

Semantic errors occur when the code runs without syntax errors but produces incorrect results due to faulty logic or misuse of concepts.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Types of Semantic

A
  • Type Compatibility
  • Undefined Variables
  • Logical Errors
  • Control Flow Errors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Type Compatibility

A

Python is dynamically typed, but operations on incompatible types lead to runtime errors.

x = “10”
y = 5
print(x + y) # TypeError: can only concatenate str (not “int”) to str

Fix
print(int(x) + y) # Correct: Outputs 15

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Undefined Variables

A

A variable must be initialized before it is used, even if the syntax is correct.

print(x) # NameError: name ‘x’ is not defined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Logical Errors

A

These are errors in the logic of the code that lead to unintended outcomes.

def is_even(num):
return num % 2 == 1 # Incorrect logic for checking even numbers

def is_even(num):
return num % 2 == 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Control Flow Errors

A

These occur when the intended flow of the program is not achieved.

for i in range(5):
if i == 3:
continue
print(i) # This print statement is unreachable

for i in range(5):
if i == 3:
continue
print(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why Syntax and Semantics Matter in Python

A

For Readability: Python’s strict syntax (e.g., indentation) ensures clean, readable code.

For Debugging: Semantic errors are harder to detect because the code runs without errors but produces the wrong results.

For Robust Programs: Understanding both aspects helps write error-free and maintainable programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly