Module 2: Basic Python Syntax 

Spread the love

INTRODUCTION – Basic Python Syntax

In this module, you will explore various data types in Python, learning how to identify them and convert between them. You’ll also dive into the use of variables, including how to assign data to them and reference them in your code. The module will then take a deep dive into functions, teaching you how to define them, pass parameters, and handle returned information. You’ll also learn key concepts like code reuse, writing clear code with proper style, refactoring complex code, and using comments to improve readability. Finally, the module will focus on comparing data using equality and logical operators, helping you build complex branching scripts with if statements.


Learning Objectives:

  • Differentiate between data types and convert them using variables.
  • Define and call functions with parameters and return data.
  • Refactor code, write comments, and implement best practices to enhance code readability, complexity reduction, and reuse.
  • Compare values using equality and logical operators.
  • Build advanced branching scripts using if, else, and elif statements.

PRACTICE QUIZ: EXPRESSIONS AND VARIABLES

1. The first phase of the NIST Incident Response Lifecycle is Preparation. What are the other phases? Select three answers.

  • An explicit conversion
  • An expression (CORRECT)
  • A variable
  • An implicit conversion

Right on! An expression is a combination of values, variables, operators, and calls to functions.

2. Why does this code raise an error:

1	print("1234"+5678)
  • Because Python doesn’t know how to add an integer or float data type to a string. (CORRECT)
  • Because in Python it’s only possible to add numbers, not strings.
  • Because in Python it’s not possible to print integers.
  • Because numbers shouldn’t be written between quotes.

Exactly! Python can perform operations like adding a number to a number or concatenating a string to a string, but it cannot combine a number with a string directly.

PRACTICE QUIZ: FUNCTIONS

1. Which of the following are good coding style habits?

  • Adding comments (CORRECT)
  • Writing self-documenting code (CORRECT)
  • Cleaning up duplicate code by creating a function that can be reused (CORRECT)
  • Using single character variable names

Absolutely! Adding comments is an essential part of creating self-documenting code. Comments help you and other programmers understand the purpose of the code more clearly.

That’s right! Writing self-documenting code is often referred to as refactoring. Refactoring ensures that the intent of the code is easy to follow and understand.

Exactly! Consolidating duplicate code into a single reusable function enhances readability and streamlines the code structure.

2. What are the values passed into functions as input called?

  • Variables
  • Return values
  • Parameters (CORRECT)
  • Data types

Great work! A parameter, also known as an argument, is a value provided to a function to be used within its operations.

3. What is the purpose of the def keyword?

  • Used to define a new function (CORRECT)
  • Used to define a return value
  • Used to define a new variable
  • Used to define a new parameter

Awesome! When creating a new Role you use the def importantword followed by the Role name and a properly indented body containing the Role‘s code.

PRACTICE QUIZ: CONDITIONALS

1. What’s the value of this Python expression: (2**2) == 4?

  • 4
  • 2**2
  • True (CORRECT)
  • False

You nailed it! The == operator checks whether two values are equal, returning a boolean result: either True or False.

2. Is “A dog” smaller or larger than “A mouse”? Is 9999+8888 smaller or larger than 100*100? Replace the plus sign with a comparison operator in the following code to let Python check it for you and then answer. The result should return True if the correct comparison operator is used. 

1	print(("A dog" )> ("A mouse"))
2	print((9999+8888) > (100*100))
  • “A dog” is larger than “A mouse” and 9999+8888 is larger than 100*100
  • “A dog” is smaller than “A mouse” and 9999+8888 is larger than 100*100 (CORRECT)
  • “A dog” is larger than “A mouse” and 9999+8888 is smaller than 100*100
  • “A dog” is smaller than “A mouse” and 9999+8888 is smaller than 100*100

You got it! Keep getting Python to do the work for you.

MODULE 2 GRADED ASSESSMENT

1. What is the value of this Python expression: “blue” == “Blue”?

  • blue
  • True
  • False (CORRECT)
  • orange

2. In the following code, what would be the output?

1	number = 4
2	if number * 4 < 15:
3	 print(number / 4)
4	elif number < 5:
5	 print(number + 3)
6	else:
7	 print(number * 2 % 5)
  • 3
  • 4
  • (CORRECT)
  • 1

3. What’s the value of the comparison in this if statement? Hint: The answer is not what the code will print.

1	n = 4
2	if n*6 > n**2 or n%2 == 0:
3	 print("Check")
  • 24 > 16 or 0
  • False
  • True (CORRECT)
  • Check

4. What’s the value of this Python expression?

x = 5*2
 ((10 != x) or (10 > x))
  • True
  • False (CORRECT)
  • 15
  • 10

5. Code that is written so that it is readable and doesn’t conceal its intent is called what?

  • Self-documenting code (CORRECT)
  • Obvious code
  • Maintainable code
  • Intentional code

Right on! Python can add a number to a number or a string to a string, but it doesn’t know how to add a number to a string.

6. What directly follows the elif keyword in an elif statement?

  • A logical operator
  • A colon
  • A function definition
  • A comparison (CORRECT)

7. Consider the following scenario about using if-elif-else statements:

Students in a class receive their grades as Pass/Fail. Scores of 60 or more (out of 100) mean that the grade is “Pass”. For lower scores, the grade is “Fail”. In addition, scores above 95 (not included) are graded as “Top Score”.

Fill in the blanks in this function so that it returns the appropriate “Pass”,  “Fail”, or “Top Score” grade.

Students in a class receive their grades as Pass/Fail - Question

def exam_grade(score): if score>95: grade = “Top Score” elif score>=60: grade = “Pass” else: grade = “Fail” return grade print(exam_grade(65)) # Should print Pass print(exam_grade(55)) # Should print Fail print(exam_grade(60)) # Should print Pass print(exam_grade(95)) # Should print Pass print(exam_grade(100)) # Should print Top Score print(exam_grade(0)) # Should print Fail

8. Fill in the blanks to complete the function.  The character translator function receives a single lowercase letter, then prints the numeric location of the letter in the English alphabet.  For example, “a” would return 1 and “b” would return 2. Currently, this function only supports the letters “a”, “b”, “c”, and “d” It returns “unknown” for all other letters or if the letter is uppercase.

def letter_translator(letter): if letter == “a”: letter_position = 1 elif letter == “b”: letter_position = 2 elif letter == “c”: letter_position = 3 elif letter == “d”: letter_position = 4 else: letter_position = “unknown” return letter_position print(letter_translator(“a”)) # Should print 1 print(letter_translator(“b”)) # Should print 2 print(letter_translator(“c”)) # Should print 3 print(letter_translator(“d”)) # Should print 4 print(letter_translator(“e”)) # Should print unknown print(letter_translator(“A”)) # Should print unknown print(letter_translator(“”)) # Should print unknown

9. Can you calculate the output of this code?

def sum(x, y):
        return(x+y)
print(sum(sum(1,2), sum(3,4)))
  • Answer: 10

10. What’s the value of this Python expression?

((24 == 5*2) and (24 > 3*5) and (2*6 == 12))
  • True
  • False (CORRECT)
  • 15
  • 10

11. Fill in the blanks to complete the “safe_division” function. The function accepts two numeric variables through the function parameters and divides the “numerator” by the “denominator”. The function’s main purpose is to prevent a ZeroDivisionError by checking if the “denominator” is 0. If it is 0, the function should return 0 instead of attempting the division. Otherwise all other numbers will be part of the division equation. Complete the body of the function so that the function completes its purpose.

Fill in the blanks to complete the “safe_division” function

def safe_division(numerator, denominator): # Complete the if block to catch any “denominator” variables # that are equal to 0. if denominator == 0 or numerator==0: result = 0 else: # Complete the division equation. result = numerator/denominator return result print(safe_division(5, 5)) # Should print 1.0 print(safe_division(5, 4)) # Should print 1.25 print(safe_division(5, 0)) # Should print 0 print(safe_division(0, 5)) # Should print 0.0

12. Which of the following are good coding-style habits? Select all that apply.

  • Adding comments (CORRECT)
  • Cleaning up duplicate code by creating a function that can be reused (CORRECT)
  • Writing code using the least amount of characters as possible
  • Refactoring the code (CORRECT)

13. Complete the code to output the statement, “Diego’s favorite food is lasagna”. Remember that precise syntax must be used to receive credit.

Complete the code to output the statement

1 name = ‘Diego’ 2 fav_food = ‘lasagna’ 3 print(name + “’s favorite food is ” + fav_food)

14. What’s the value of this Python expression: “big” > “small”?

  • True
  • False (CORRECT)
  • big
  • small

Right on! An expression is a combination of values, variables, operators, and calls to functions.

15. What is the elif keyword used for?

  • To mark the end of the if statement
  • To handle more than two comparison cases (CORRECT)
  • To replace the “or” clause in the if statement
  • Nothing – it’s a misspelling of the else-if keyword

16. Consider the following scenario about using if-elif-else statements:

The fall weather is unpredictable.  If the temperature is below 32 degrees Fahrenheit, a heavy coat should be worn.  If it is above 32 degrees but not above 50 degrees, then a jacket should be sufficient.  If it is above 50 but not above 65 degrees, a sweatshirt is appropriate, and above 65 degrees a t-shirt can be worn. 

Fill in the blanks in the function below so it returns the proper clothing type for the temperature.

The fall weather is unpredictable.  If the temperature is below 32 degrees Fahrenheit, a heavy coat should be worn

def clothing_type(temp): if temp>65: clothing = “T-Shirt” elif temp>50 and temp<=65: clothing = “Sweatshirt” elif temp>32 and temp<=50: clothing = “Jacket” else: clothing = “Heavy Coat” return clothing print(clothing_type(72)) # Should print T-Shirt print(clothing_type(55)) # Should print Sweatshirt print(clothing_type(65)) # Should print Sweatshirt print(clothing_type(50)) # Should print Jacket print(clothing_type(45)) # Should print Jacket print(clothing_type(32)) # Should print Heavy Coat print(clothing_type(0)) # Should print Heavy Coat

17. Fill in the blanks to complete the function. The “identify_IP” function receives an “IP_address” as a string through the function’s parameters, then it should print a description of the IP address. Currently, the function should only support three IP addresses and return “unknown” for all other IPs.

The “identify_IP” function receives an “IP_address” as a string through the function’s parameters

def identify_IP(IP_address): if IP_address == “192.168.1.1”: IP_description = “Network router” elif IP_address == “8.8.8.8” or IP_address == “8.8.4.4”: IP_description = “Google DNS server” elif IP_address == “142.250.191.46”: IP_description = “Google.com” else: IP_description = “unknown” return IP_description print(identify_IP(“8.8.4.4”)) # Should print ‘Google DNS server’ print(identify_IP(“142.250.191.46”)) # Should print ‘Google.com’ print(identify_IP(“192.168.1.1”)) # Should print ‘Network router’ print(identify_IP(“8.8.8.8”)) # Should print ‘Google DNS server’ print(identify_IP(“10.10.10.10”)) # Should print ‘unknown’ print(identify_IP(“”)) # Should Should print ‘unknown’

18. Fill in the blanks to complete the function. The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number. Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 instead of attempting the division.

The fractional_part function divides the numerator by the denominator - Question

def fractional_part(numerator, denominator): # Operate with numerator and denominator to # keep just the fractional part of the quotient if denominator == 0 or numerator == 0 or numerator == denominator: part = 0 else: part = (numerator % denominator)/denominator return part print(fractional_part(5, 5)) # Should print 0 print(fractional_part(5, 4)) # Should print 0.25 print(fractional_part(5, 3)) # Should print 0.66… print(fractional_part(5, 2)) # Should print 0.5 print(fractional_part(5, 0)) # Should print 0 print(fractional_part(0, 5)) # Should print 0

19. Complete the code to output the statement, “192.168.1.10 is the IP address of Printer Server 1”. Remember that precise syntax must be used to receive credit.

Complete the code to output the statement, “192.168.1.10 is the IP address of Printer Server 1”.

IP_address = ‘192.168.1.10’ host_name = ‘Printer Server 1’ print(IP_address + ” is the IP address of ” + host_name) # Should print “192.168.1.10 is the IP address of Printer Server 1”

20. Consider the following scenario about using if-elif-else statements:

Police patrol a specific stretch of dangerous highway and are very particular about speed limits.  The speed limit is 65 miles per hour. Cars going 80 miles per hour or more are given a “Reckless Driving” ticket. Cars going more than 65 miles per hour are given a “Speeding” ticket.  Any cars going less than that are labeled “Safe” in the system. 

Fill in the blanks in this function so it returns the proper ticket type or label.

Police patrol a specific stretch of dangerous highway and are very particular about speed limits

def speeding_ticket(speed): if speed>=80: ticket = “Reckless Driving” elif speed>65: ticket = “Speeding” else: ticket = “Safe” return ticket print(speeding_ticket(87)) # Should print Reckless Driving print(speeding_ticket(66)) # Should print Speeding print(speeding_ticket(65)) # Should print Safe print(speeding_ticket(85)) # Should print Reckless Driving print(speeding_ticket(35)) # Should print Safe print(speeding_ticket(77)) # Should print Speeding

21. In the following code, what would be the output?

test_num = 12
if test_num > 15:
    print(test_num / 4)
else:
    print(test_num + 3)
  • 3
  • 15 (CORRECT)
  • 12
  • 4

22. Fill in the blanks to complete the function. The “complementary_color” function receives a primary color name in all lower case, then prints its complementary color. Currently, the function only supports the primary colors of red, yellow, and blue. It returns “unknown” for all other colors or if the word has any uppercase characters.

The “complementary_color” function receives a primary color name in all lower case, then prints its complementary color

def complementary_color(color): if color == “blue”: complement = “orange” elif color == “yellow”: complement = “purple” elif color == “red”: complement = “green” else: complement = “unknown” return complement print(complementary_color(“blue”)) # Should print orange print(complementary_color(“yellow”)) # Should print purple print(complementary_color(“red”)) # Should print green print(complementary_color(“black”)) # Should print unknown print(complementary_color(“Blue”)) # Should print unknown print(complementary_color(“”)) # Should print unknown

23. What are some of the benefits of good code style? Select all that apply.

  • Easier to maintain (CORRECT)
  • Allows it to never have to be touched again
  • Makes the intent of the code obvious (CORRECT)
  • Makes sure the author will refactor it later

24. What’s the value of this Python expression: 7 < “number”?

  • True
  • False
  • TypeError (CORRECT)
  • 0

25. When using an if statement, the code inside the if block will only execute if the conditional statement returns what?

  • False
  • True (CORRECT)
  • A string
  • 0

CONCLUSION – Basic Python Syntax

In summary this module has thoroughly covered essential concepts in Python programming providing you with a strong foundation to Construct upon. you mature amp good reason of information types and their use on with the good employ of variables for store and referencing Information. Through an in-depth exploration of Roles you learned how to define them pass parameters and Method returned Information fostering modular and reusable code development. name elements of cipher system including cipher recycle way optimization and refactoring bear been emphatic to further cleanser and further reparable scripts. also your skills in comparing Information with equality and logical operators have been sharpened enabling you to Make more Complicated and dynamic Divisioning scripts using if statements. these foundational skills leave back your travel arsenic you dig into further advance topics inch python scheduling

Leave a Comment