PLD EXAM (copy)
Question: Where does the name "Python" come from?
Answer: The name comes from Monty Python’s Flying Circus, a comedy series enjoyed by Guido van Rossum, Python's creator.
Python's design philosophy emphasizes code readability and simplicity, reflecting creativity akin to the show.
Commands: A complete set of commands in a program is referred to as a "command list."
Statements and Boolean Operations:
Python includes logical operators: and, or, not.
Important truths:
True + 1
evaluates to 2
.
True and False
evaluates to False
.
True or False
evaluates to True
.
Python’s Creator:
Created by Guido van Rossum in the late 1980s; first released in 1991.
Designed for simplicity and readability, minimizing programming complexity.
Execution: Python is an interpreted language, executing code line-by-line by an interpreter.
This characteristic aids in testing, debugging, and facilitates prototyping and iterative development.
Single-Line Comments: Start with the #
symbol; essential for code readability.
Multi-Line Comments: Use triple quotes (''' ... '''
) to denote multi-line comments as Python lacks traditional symbols.
High-Level Language: Abstractions simplify interaction with complex computer processes.
Contrasts with low-level languages that operate close to hardware, making Python more user-friendly.
Type Checking: Use built-in functions like isinstance()
to verify variable types (e.g., int
, str
).
Example: Checking if x
is an integer:
x = 10
if isinstance(x, int):
print("Integer")
else:
print("Not Integer")
Separators in Print Statements: Use the sep
parameter with print()
to define separators:
Example: print("Python", "Programming", sep="-")
results in "Python-Programming".
End Parameter in Print: Change the ending character:
Example:
print("Hello", end="@")
print("World")
Results in "Hello@World".
Types of Errors:
Syntax Errors: Identified during compilation (e.g., missing parentheses).
Runtime Errors: Identified during program execution.
Example of syntax error: print("Hello World!"))
causes SyntaxError
due to extra parenthesis.
Taking Input: Use the input()
function to gather user input, which returns a string. Converting to other types is common.
Example:
user_input = input("Enter a number: ")
print ("You entered:", int(user_input))
While Loops: Repeat code while a condition holds true:
Example:
X = 10
while X > 0:
X -= 1
print(X)
Counts down from 9 to 0.
For Loops: Used with ranges:
Example:
for number in range(1, 6):
if number % 2 != 0:
print(number)
Outputs odd numbers: 1, 3, 5.
Identifiers: Must start with a letter (A-Z or a-z) or underscore (_), followed by letters, numbers, or underscores.
Valid identifier example: mile
.
Invalid identifier example: $343
.
Order of Operations: PEMDAS
Parentheses
Exponents
Multiplication/Division
Addition/Subtraction
Example:
result = 2 + 2 ** 3 / 2
Evaluates as 2 + (8 / 2) = 6.0
.
Common Errors: Syntax errors (like SyntaxError
for structural issues) and NameError
when names are not found.
Example of a syntax error:
print("Hello World!"))
Extra parenthesis causes a SyntaxError
.
Concatenation: Adding strings using +
, but need to convert numbers:
Example:
print("The answer is " + str(42))
Writing Algorithms: Use pseudocode or flowcharts to outline program structure.
Flowcharts represent paths and loops visually.
Supports Multiple Paradigms: Python accommodates object-oriented, functional, and procedural programming.
Exponentiation: Symbol for exponentiation in Python is **
.
Example:
2 ** 3 # Results in 8
Do not use ^
, which is a bitwise XOR.
• If X = 8, "Yoyo" might print 7 times if the loop reduces X by 1 each time it prints.
• If X = 0 after a loop, it could signal a condition to print "Bye."
• If X = 10 and each iteration reduces X by 2 while printing, "Yoyo" would print 5 times.
Identifying Errors: Example of a syntax error,
Problematic string: ‘3\’
, which can lead to issues in interpretation due to incomplete backslashes.
Addition Challenge: Adding string and number like ('123' + 4)
causes an error. Convert using str()
to add.
Example:
print("123" + str(4)) # Output: 1234
Flowcharts: A method to graphically represent the steps of a process. Useful for planning and understanding programming logic.
Basic Symbols:
Oval (Start/End): Marks start and end points (labeled "Start" and "End").
Rectangle (Process): Represents actions (e.g., calculations).
Diamond (Decision): Decision-making points (Yes/No conditions).
Parallelogram (I/O): Input/output operations.
Arrows: Show the flow direction between steps.
Analyzing Flowcharts:
Start at "Start" symbol and follow arrows sequentially.
At Decision points, follow the path based on the condition (True/False or Yes/No).
Review process steps till reaching "End".
Sequential Flowcharts: Steps occur with no branching (e.g., fixed messages).
Decision Flowcharts: Handle branching conditions, if-else logic. (e.g., positive/negative number checks).
Looping Flowcharts: Represent repetitive tasks, while-for loops. (e.g., countdowns).
Flowchart for Calculating Sum:
Start
Input: Get two numbers (num1, num2).
Process: Calculate sum = num1 + num2.
Output: Display sum.
End.
Flowchart for Even or Odd Check:
Start
Input: Get a number.
Decision: Check if num % 2 == 0
:
Yes: Output "Even".
No: Output "Odd".
Here’s a breakdown of how it works:
Start: The process begins here.
Input: The program asks the user to enter a number (let's call it num
).
Decision: The program checks if the number divided by 2 has a remainder of 0 (this is done using the modulus operator %
). This means it checks if num % 2 == 0
.
If Yes: If the condition is true (i.e., the number is even), the program will output "Even".
If No: If the condition is false (i.e., the number is odd), the program will output "Odd".
End: The process concludes here.
Flowchart Example: Example of counting down from 1 to 5 using a decision structure.
Start
Initialize count = 1
Decision: Is count <= 5?
Yes: Print count; increment count.
No: End
Here’s a breakdown of the steps:
Start: This is where the process begins.
Initialize count: We start by setting the count variable to 1 (count = 1
). This tells the program that our starting point is 1.
Decision: We then ask the question: "Is count less than or equal to 5?"
If the answer is Yes: We print the current value of count and then add 1 to it (incrementing count). The flow loops back to the decision step to check again.
If the answer is No: We exit the process and reach the end of the flowchart.
Counter Loops: Repeat processes a fixed number of times.
Conditional Branching: Handle decisions diverging based on conditions (true/false, if-else).
Accumulators: Collect values, often used in loops for cumulative calculations.
Example Question: Analyzing a flowchart that checks if a number is greater than 10. Outputs a message based on the input.
Answer: (Flowchart)
Start
Input: number
Decision: number > 10
Yes: Print “Greater than 10”
No: Print “10 or Less”
End
Define the Goal: Clearly specify the program's objectives.
Choose Symbols Carefully: Proper usage of symbols aids clarity.
Use Arrows for Flow Direction: Maintain visibility of operational paths.
Keep It Simple: Avoid unnecessary complexity in designs.
Label Decisions: Clearly mark paths (Yes/No, True/False).
Flowcharts are a crucial tool for visualizing programming logic, enhancing understanding of algorithms. Practicing flowchart creation bolsters problem-solving skills and logical programming approaches.
Question: Where does the name "Python" come from?
Answer: The name comes from Monty Python’s Flying Circus, a comedy series enjoyed by Guido van Rossum, Python's creator.
Python's design philosophy emphasizes code readability and simplicity, reflecting creativity akin to the show.
Commands: A complete set of commands in a program is referred to as a "command list."
Statements and Boolean Operations:
Python includes logical operators: and, or, not.
Important truths:
True + 1
evaluates to 2
.
True and False
evaluates to False
.
True or False
evaluates to True
.
Python’s Creator:
Created by Guido van Rossum in the late 1980s; first released in 1991.
Designed for simplicity and readability, minimizing programming complexity.
Execution: Python is an interpreted language, executing code line-by-line by an interpreter.
This characteristic aids in testing, debugging, and facilitates prototyping and iterative development.
Single-Line Comments: Start with the #
symbol; essential for code readability.
Multi-Line Comments: Use triple quotes (''' ... '''
) to denote multi-line comments as Python lacks traditional symbols.
High-Level Language: Abstractions simplify interaction with complex computer processes.
Contrasts with low-level languages that operate close to hardware, making Python more user-friendly.
Type Checking: Use built-in functions like isinstance()
to verify variable types (e.g., int
, str
).
Example: Checking if x
is an integer:
x = 10
if isinstance(x, int):
print("Integer")
else:
print("Not Integer")
Separators in Print Statements: Use the sep
parameter with print()
to define separators:
Example: print("Python", "Programming", sep="-")
results in "Python-Programming".
End Parameter in Print: Change the ending character:
Example:
print("Hello", end="@")
print("World")
Results in "Hello@World".
Types of Errors:
Syntax Errors: Identified during compilation (e.g., missing parentheses).
Runtime Errors: Identified during program execution.
Example of syntax error: print("Hello World!"))
causes SyntaxError
due to extra parenthesis.
Taking Input: Use the input()
function to gather user input, which returns a string. Converting to other types is common.
Example:
user_input = input("Enter a number: ")
print ("You entered:", int(user_input))
While Loops: Repeat code while a condition holds true:
Example:
X = 10
while X > 0:
X -= 1
print(X)
Counts down from 9 to 0.
For Loops: Used with ranges:
Example:
for number in range(1, 6):
if number % 2 != 0:
print(number)
Outputs odd numbers: 1, 3, 5.
Identifiers: Must start with a letter (A-Z or a-z) or underscore (_), followed by letters, numbers, or underscores.
Valid identifier example: mile
.
Invalid identifier example: $343
.
Order of Operations: PEMDAS
Parentheses
Exponents
Multiplication/Division
Addition/Subtraction
Example:
result = 2 + 2 ** 3 / 2
Evaluates as 2 + (8 / 2) = 6.0
.
Common Errors: Syntax errors (like SyntaxError
for structural issues) and NameError
when names are not found.
Example of a syntax error:
print("Hello World!"))
Extra parenthesis causes a SyntaxError
.
Concatenation: Adding strings using +
, but need to convert numbers:
Example:
print("The answer is " + str(42))
Writing Algorithms: Use pseudocode or flowcharts to outline program structure.
Flowcharts represent paths and loops visually.
Supports Multiple Paradigms: Python accommodates object-oriented, functional, and procedural programming.
Exponentiation: Symbol for exponentiation in Python is **
.
Example:
2 ** 3 # Results in 8
Do not use ^
, which is a bitwise XOR.
• If X = 8, "Yoyo" might print 7 times if the loop reduces X by 1 each time it prints.
• If X = 0 after a loop, it could signal a condition to print "Bye."
• If X = 10 and each iteration reduces X by 2 while printing, "Yoyo" would print 5 times.
Identifying Errors: Example of a syntax error,
Problematic string: ‘3\’
, which can lead to issues in interpretation due to incomplete backslashes.
Addition Challenge: Adding string and number like ('123' + 4)
causes an error. Convert using str()
to add.
Example:
print("123" + str(4)) # Output: 1234
Flowcharts: A method to graphically represent the steps of a process. Useful for planning and understanding programming logic.
Basic Symbols:
Oval (Start/End): Marks start and end points (labeled "Start" and "End").
Rectangle (Process): Represents actions (e.g., calculations).
Diamond (Decision): Decision-making points (Yes/No conditions).
Parallelogram (I/O): Input/output operations.
Arrows: Show the flow direction between steps.
Analyzing Flowcharts:
Start at "Start" symbol and follow arrows sequentially.
At Decision points, follow the path based on the condition (True/False or Yes/No).
Review process steps till reaching "End".
Sequential Flowcharts: Steps occur with no branching (e.g., fixed messages).
Decision Flowcharts: Handle branching conditions, if-else logic. (e.g., positive/negative number checks).
Looping Flowcharts: Represent repetitive tasks, while-for loops. (e.g., countdowns).
Flowchart for Calculating Sum:
Start
Input: Get two numbers (num1, num2).
Process: Calculate sum = num1 + num2.
Output: Display sum.
End.
Flowchart for Even or Odd Check:
Start
Input: Get a number.
Decision: Check if num % 2 == 0
:
Yes: Output "Even".
No: Output "Odd".
Here’s a breakdown of how it works:
Start: The process begins here.
Input: The program asks the user to enter a number (let's call it num
).
Decision: The program checks if the number divided by 2 has a remainder of 0 (this is done using the modulus operator %
). This means it checks if num % 2 == 0
.
If Yes: If the condition is true (i.e., the number is even), the program will output "Even".
If No: If the condition is false (i.e., the number is odd), the program will output "Odd".
End: The process concludes here.
Flowchart Example: Example of counting down from 1 to 5 using a decision structure.
Start
Initialize count = 1
Decision: Is count <= 5?
Yes: Print count; increment count.
No: End
Here’s a breakdown of the steps:
Start: This is where the process begins.
Initialize count: We start by setting the count variable to 1 (count = 1
). This tells the program that our starting point is 1.
Decision: We then ask the question: "Is count less than or equal to 5?"
If the answer is Yes: We print the current value of count and then add 1 to it (incrementing count). The flow loops back to the decision step to check again.
If the answer is No: We exit the process and reach the end of the flowchart.
Counter Loops: Repeat processes a fixed number of times.
Conditional Branching: Handle decisions diverging based on conditions (true/false, if-else).
Accumulators: Collect values, often used in loops for cumulative calculations.
Example Question: Analyzing a flowchart that checks if a number is greater than 10. Outputs a message based on the input.
Answer: (Flowchart)
Start
Input: number
Decision: number > 10
Yes: Print “Greater than 10”
No: Print “10 or Less”
End
Define the Goal: Clearly specify the program's objectives.
Choose Symbols Carefully: Proper usage of symbols aids clarity.
Use Arrows for Flow Direction: Maintain visibility of operational paths.
Keep It Simple: Avoid unnecessary complexity in designs.
Label Decisions: Clearly mark paths (Yes/No, True/False).
Flowcharts are a crucial tool for visualizing programming logic, enhancing understanding of algorithms. Practicing flowchart creation bolsters problem-solving skills and logical programming approaches.