CRASH COURSE ON PYTHON
Module 2: Basic Python Syntax
GOOGLE IT AUTOMATION WITH PYTHON PROFESSIONAL CERTIFICATE
Complete Coursera Study Guide
Last updated:
INTRODUCTION – Basic Python Syntax
In this module, you will gain insights into various data types in Python, understanding their identification and conversion processes. The use of variables will be explored, covering both assigning data to them and referencing variables in your code. A detailed exploration of functions will follow, encompassing the definition process, passing parameters, and receiving returned information. Additionally, you will delve into important concepts such as code reuse, code style, and the refactoring of complex code, along with the effective use of code comments for clarity. The module will conclude with a focus on comparing data through equality and logical operators, empowering you to construct intricate branching scripts using if statements.
Learning Objectives
- Differentiate and convert between different data types utilizing variables
- Define and call functions utilizing parameters and return data
- Refactor code and write comments to reduce complexity and enhance code readability and code reuse
- Compare values using equality operators and logical operators
- Build complex branching scripts utilizing if, else and elif statements
PRACTICE QUIZ: EXPRESSIONS AND VARIABLES
1. What do you call a combination of numbers, symbols, or other values that produce a result when evaluated?
- 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.
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.
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
Correct. Adding comments is part of creating self-documenting code. Using comments allows you to leave notes to yourself and/or other programmers to make the purpose of the code clear.
Correct. Writing self-documenting code is also called refactoring the code. Refactoring should make the intent of the code clear.
Correct. You can combine duplicate code in one reusable function to make the code easier to read.
2. What are the values passed into functions as input called?
- Variables
- Return values
- Parameters (CORRECT)
- Data types
Nice job! A parameter, also sometimes called an argument, is a value passed into a function for use within the function.
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 defining a new function, we must use the def keyword followed by the function name and properly indented body.
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 conditional operator == checks if two values are equal. The result of that operation is a boolean: 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
- 7 (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.
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.
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.
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.
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.
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.
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.
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.
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.
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 conclusion, this module has provided a comprehensive exploration of fundamental concepts in Python programming. You’ve gained proficiency in understanding and manipulating different data types, utilizing variables to store and reference data efficiently. The in-depth coverage of functions has equipped you with the ability to define, pass parameters, and handle returned information, promoting modular and reusable code. Crucial aspects of code organization, such as code reuse, style considerations, and refactoring complex code, have been addressed, contributing to the development of cleaner and more maintainable scripts. Lastly, you’ve acquired the skills to compare data using equality and logical operators, paving the way for constructing sophisticated branching scripts with the utilization of if statements. As you move forward, these foundational skills will serve as a solid basis for more advanced Python programming endeavors.
Subscribe to our site
Get new content delivered directly to your inbox.
Quiztudy Top Courses
Popular in Coursera
- Google Advanced Data Analytics
- Google Cybersecurity Professional Certificate
- Meta Marketing Analytics Professional Certificate
- Google Digital Marketing & E-commerce Professional Certificate
- Google UX Design Professional Certificate
- Meta Social Media Marketing Professional Certificate
- Google Project Management Professional Certificate
- Meta Front-End Developer Professional Certificate
Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!