In this module you’ll learn about different data types in Python, how to identify them, and how to convert between them. You’ll also learn how to use variables to assign data and to reference variables. You’ll deep dive into functions: how to define them, pass them parameters, and have them return information. You’ll explore the concepts of code reuse, code style, and refactoring complex code, along with effectively using code comments. Finally, you’ll learn about comparing data using equality and logical operators, and leveraging these to build complex 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
Expressions and Variables
Video: Basic Python Syntax introduction
This video is a recap of the previous module and a preview of the next module. In the previous module, you learned about some basic concepts, such as programming and automation. You also learned about the importance of programming language syntax and got a sneak preview of some of the things you could do with Python.
In the next module, you will dive deeper into some basic building blocks of Python syntax, such as variables, expressions, functions, and conditional blocks. You will also learn about data types.
Additional thoughts:
The best way to learn a programming language is to practice. The more you code, the better you will become. Don’t be afraid to make mistakes. Everyone makes mistakes when they are learning to code. The important thing is to learn from your mistakes and keep practicing.
If you are feeling stuck, don’t hesitate to ask for help. There are many online resources and communities where you can get help from other programmers.
I encourage you to continue learning and practicing. With hard work and dedication, you will be able to master Python programming and build amazing things.
Python is a programming language that is known for its simplicity and readability. It is a popular language for beginners, as it is relatively easy to learn.
The basic syntax of Python is as follows:
- Statements are terminated by a semicolon (;)
- Variables are declared using the
var_name = value
syntax - Expressions are evaluated from left to right
- Comments are preceded by a hash (#) symbol
Here is an example of a Python program:
# This is a Python program
name = "Bard"
print("Hello, " + name)
This program declares a variable named name
and assigns it the value “Bard”. It then prints the following message to the console:
Hello, Bard
Here are some of the basic data types in Python:
- Numbers: Integers, floats, and complex numbers
- Strings: Sequences of characters
- Lists: Ordered sequences of objects
- Tuples: Immutable ordered sequences of objects
- Dictionaries: Unordered mappings of keys to values
Here is an example of a Python program that uses data types:
# This program uses data types
number = 10
string = "Hello, world!"
list = [1, 2, 3, 4, 5]
tuple = (1, 2, 3, 4, 5)
dictionary = {"name": "Bard", "age": 100}
This program declares variables of different data types and assigns them values. It then prints the values of the variables to the console.
I hope this tutorial provides you with a basic introduction to Python syntax. For more information, please refer to the official Python tutorial.
Here are some additional resources that you may find helpful:
- Python Tutorial: https://docs.python.org/3/tutorial/
- Python Crash Course: https://www.learnpython.org/
- Automate the Boring Stuff with Python: https://automatetheboringstuff.com/
[MUSIC] Hi there, welcome back, and well done for
completing your first graded assessment. You’re doing a great
job making it this far. Chances are some topics we’ve covered
may have been a little tricky at times, especially if you’re
completely new to programming. Don’t worry if something
wasn’t obvious right away. We went through a lot of new concepts and it might take several passes until
you feel comfortable with them. And that’s totally normal. We all went through it when we
were learning how to code. In the previous module we explored some
basic concepts, like programming and automation. We called out that each programming
language has a specific syntax, which we need to learn so
we can tell the computer what to do. We then got a sneak preview of some of
the things we could do with Python. Up next, we’ll dive deeper into some
basic building blocks of Python syntax, things like variables, expressions,
functions, and conditional blocks. At first glance these pieces
may seem pretty simple, but when we start to combine them
they become a lot more powerful. Understanding a programming language’s
syntax isn’t too different from learning a spoken language. For example, the best way to learn Spanish
is to visit a Spanish speaking country, immerse yourself in the culture,
listen to the people. Then figure out how to arrange the words
to form a sentence that another speaker can understand. The same is true for programming. When you immerse yourself in Python
programming you’ll learn how to formulate statements of code that
the computer can understand. This is called syntax. Okay, so as you go through the next few
videos keep in mind that our main goal is to learn the language’s syntax. So we’ll focus on how to tell
our computer what to do, not on how to get it to
do complicated tasks. Like before, we’ll run through some simple exercises
to help you see the concepts in action. And as you pick up the new skills and get
to grips with different tools we’ll start to write more advanced scripts that
tackle more challenging problems. Again, if at any point you feel confused
or that something just isn’t clear, remember you can watch the videos and take the practice quizzes
as many times as you need. The key to getting good at programming
is practice, practice and practice. You have to keep working your programming
muscles in order to get strong, just like building muscles in the gym. Train hard, train regularly, and you’ll be tackling more weighty
coding problems in no time. All right, ready to jump back in? In the next video we’re going
to learn all about data types. Let’s get started.
Video: Data Types
In this video, you learned about data types in Python. Data types are different ways that Python can represent data. Some common data types in Python include strings, integers, and floats.
Strings are used to represent text. Integers are used to represent whole numbers. Floats are used to represent real numbers, which are numbers with a decimal part.
It is important to use the correct data type for each variable. For example, you should not try to add an integer and a string together. If you do, Python will throw an error.
You can use the type()
function to find out the data type of a variable. For example, to find out the data type of the variable name
, you would type type(name)
.
Here is an example of how to use the type()
function:
name = "Alice"
print(type(name))
Output:
<class 'str'><br>
This tells us that the variable name
is a string.
Additional thoughts:
Data types are an important concept in programming. By understanding data types, you can write more efficient and bug-free code.
It is also important to be able to debug your code. When you get an error, take the time to read the error message carefully and try to understand what it is telling you. This will help you to fix the error quickly and easily.
Don’t be afraid to experiment. The best way to learn is by doing. So try writing some code and see what happens. If you get an error, try to debug it. If you can’t figure it out, ask for help.
There are many resources available to help you learn Python. There are books, tutorials, and online communities. So don’t give up! Keep learning and practicing, and you will eventually become a proficient Python programmer.
Data types are used to represent different kinds of data in Python. The four most common data types are:
- Strings: Strings are sequences of characters. They can be enclosed in single quotes (‘) or double quotes (“).
- Integers: Integers are whole numbers. They can be positive, negative, or zero.
- Floats: Floats are real numbers with a fractional part. They can be positive, negative, or zero.
- Booleans: Booleans represent the values True or False.
In Python, you can use the type()
function to find out the data type of a value. For example:
>>> type("hello")
<class 'str'>
>>> type(10)
<class 'int'>
>>> type(2.5)
<class 'float'>
>>> type(True)
<class 'bool'>
It is important to keep your data types consistent to avoid errors. For example, if you try to add an integer and a string, you will get an error:
>>> 10 + "hello"
TypeError: cannot add str and int
To avoid this error, you can convert the string to an integer first:
>>> int("10") + "hello"
TypeError: cannot concatenate str and int
Or, you can convert the integer to a string:
>>> str(10) + "hello"
'10hello'
Here are some other common data types in Python:
- Lists: Lists are ordered sequences of values. They can be heterogeneous, meaning that they can contain values of different data types.
- Tuples: Tuples are also ordered sequences of values, but they are immutable, meaning that their values cannot be changed.
- Dictionaries: Dictionaries are mappings of keys to values. The keys can be of any data type, but the values must be of a single data type.
I hope this tutorial provides you with a basic understanding of data types in Python. For more information, please refer to the official Python tutorial.
Here are some additional resources that you may find helpful:
- Python Tutorial: https://docs.python.org/3/tutorial/
- Python Crash Course: https://www.learnpython.org/
- Automate the Boring Stuff with Python: https://automatetheboringstuff.com/
In earlier videos, we
called out that text written between quotes in
Python is called a string. In programming terminology, a string is known as a data type, whether it’s a mobile game or a script used to automatically
create user accounts. Most programs need to
manipulate some kind of data, and that data can come in
a lot of different forms, or like we call them data types. A string is only one kind of
data type found in Python. There’s a bunch of others, like an integer which represents whole numbers without
a fraction, like one, and float, which represents real numbers or in other words, a number with a
fractional part like 2.5. Generally, your computer doesn’t know how to mix
different data types. For example, adding
two integers together makes perfect sense to
computers, like this:
print(7+8)
15 Adding together two strings also makes sense:
print(“hello ” + “world”) We just end up with the longer strings that contain the two, like so: hello world
but your computer doesn’t know how to add
an integer and a string. If you tell it to mix these
two different data types: print(7 + “8”) your computer isn’t
going to know what to do and will raise an error.
Check it out: TypeError: unsupported operand type(s) for +: ‘int’ and “str’
Oh, no, our first error, but don’t panic. Errors are a common
part of programming, and you’ll probably have
to deal with them a lot. The trick is to think of
errors as little clues from your computer to help you improve your programming skills. Read the errors carefully, understand what
they’re telling you, and then use that new knowledge to help you fix the mistake. In this example, the last
line of the error message shows us that we’ve encountered something called a TypeError. Then we get a bit of
explanatory text, that tells us that the
plus sign can’t be used between an int type
and an str type, which are short names
for integer and string. Thinking about what we’ve already learned about strings, integers, and mixing data types, can you guess what the
error is trying to tell us? The message unsupported
operand type, tells us that we
can’t add the integer seven and the string eight, because they’re
different data types, but what if you didn’t have an instructor to helpfully
point that out? How would you know? You’d need to use your research skills and the resources we called out earlier in the course to
do some investigating. For example, you could look for information
about the error by pasting the TypeError
message into the search bar of your
favorite search engine. This is a common trick used by almost everyone learning to code, and even by experienced
developers. You’ll usually find that other people on the Internet have reported similar errors
and solved them too. Back to our example. Maybe you’re thinking, aren’t we adding two numbers here?
Looks a bit like it, right? Well, look carefully and
remember that anything wrapped in quotation marks is considered a string in Python. So eight is a string here: “8” while seven is an integer. To the computer, adding
seven plus eight is just as strange as adding
seven plus A is to us, and seven plus A equals
no sense at all. It might be helpful to
think about data types in terms of information
they can represent. For example, the name of a file would be represented as
a string data type, while the size of that file might be an integer data type. If you’re ever not 100 percent sure what data type
a certain value is, Python gives you a
handy way to find out. You can use the type function, to have the computer
tell you the type. This might come in handy when dealing with
code that someone else wrote and you’re not sure what data type it’s using. For example, print (type(“a”))
class ‘str’ Print(type(2))
class ‘int’ print(type(2.5))
class “float”
pretty neat, right? This tells us that A
belongs to str class, which like we said earlier
is short for string. The number 2, belongs
to the int class, which is short for integer, and 2.5 belongs to
the float class. We’ll talk more
about what we mean by class later in the course. For now, you can just use it
as a synonym for data type. So now you know three very
common data types in Python. There are plenty of others
you’ll be using soon, but don’t worry about
them at the moment. As we continue
through the course, we’ll come across more data types and learn how to interact
with each of them. For now, just remember, mixing your data types
will get your computer, well, all mixed up. So keep your strings
with your strings, your integers with your integers, and your floats with your floats, and you shouldn’t get in
too much of a tangle.
Why does this code raise an error:
print("1234"+5678)
Because Python doesn’t know how to add a number to a string.
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.
Video: Variables
Variables are used to store values in Python. They are names that we give to certain values in our programs. Variables can be of any data type, such as numbers, strings, or even the results of operations.
To create a variable, you use the equal sign (=
) to assign a value to it. For example, the following code creates a variable called length
and assigns it the value 10:
length = 10
You can then use the variable name to refer to the value. For example, the following code prints the value of the length
variable to the console:
print(length)
Output:
10
Variables are important in programming because they allow you to perform operations on data that may change. For example, the following code calculates the area of a rectangle using the formula area = length * width
:
length = 10
width = 2
area = length * width
print(area)
Output:
20
If you want to calculate the area of a different rectangle, you can simply change the values of the length
and width
variables. This is much easier than having to rewrite the entire expression.
Variables also allow you to write more reusable code. For example, the following code defines a function that calculates the area of any rectangle:
def calculate_area(length, width):
area = length * width
return area
# Calculate the area of a rectangle with a length of 10 and a width of 2
area = calculate_area(10, 2)
# Print the area to the console
print(area)
Output:
20
This function can now be used to calculate the area of any rectangle, regardless of its size.
Additional thoughts:
Variables are a fundamental concept in programming. By understanding how to use variables, you can write more efficient, reusable, and maintainable code.
Here are some tips for using variables effectively:
- Choose descriptive names for your variables. This will make your code more readable and easier to understand.
- Use variables to store data that may change. This will make your code more flexible and reusable.
- Avoid using global variables. Global variables are accessible to all functions in your program, which can make your code more difficult to debug and maintain.
- Use functions to group together related code and to pass data between different parts of your program. This will make your code more modular and reusable.
I encourage you to practice using variables in your own code. The more you use them, the more comfortable you will become with them.
Introduction
In Python, a variable is a named location in memory that holds a value. Variables are used to store data so that it can be easily accessed and manipulated.
Creating Variables
To create a variable in Python, you use the following syntax:
variable_name = value
For example, the following code creates a variable named name
and assigns it the value "John Doe"
:
name = "John Doe"
Variable Names
Variable names can be any combination of letters, numbers, and underscores. However, variable names must start with a letter or an underscore.
Here are some examples of valid variable names:
name
my_variable
_secret_value
Here are some examples of invalid variable names:
123name
-name
name$
Variable Scope
The scope of a variable is the part of the program in which the variable is accessible. There are three types of scope in Python:
- Local scope: A local variable is defined within a function or a block of code. It is only accessible within the function or block of code in which it is defined.
- Global scope: A global variable is defined outside of any function or block of code. It is accessible throughout the entire program.
- Built-in scope: Built-in variables are predefined variables that are always available in Python. For example, the
print()
function is a built-in variable.
Variable Types
Python has a variety of variable types, each of which stores a different type of data. The most common variable types are:
- Numbers: Integers, floating-point numbers, and complex numbers.
- Strings: Sequences of characters.
- Lists: Ordered sequences of objects.
- Tuples: Immutable ordered sequences of objects.
- Dictionaries: Unordered mappings of keys to values.
Operations on Variables
We can perform a variety of operations on variables, such as:
- Assignment: Assigning a value to a variable.
- Arithmetic operations: Performing arithmetic operations on variables, such as addition, subtraction, multiplication, and division.
- Comparison operations: Comparing variables to each other, such as greater than, less than, equal to, and not equal to.
- Logical operations: Performing logical operations on variables, such as and, or, and not.
- Input/output operations: Reading data from the user and writing data to the screen.
Conclusion
Variables are a fundamental concept in Python programming. They allow us to store data and manipulate it in our programs. By understanding how variables work, we can write more concise and reusable code.
When we ask a computer to
perform an operation for us, we usually need to store values and give them names so that
we can refer to them later. This is where variables
come in handy. Variables are names
that we give to certain values in our programs. Those values can be
of any data type; numbers, strings or even
the results of operations. We already used
variables in some of our initial examples like using them to store a name or a value. Now we are going to
learn exactly how they work and how to
make the most of them. Think of variables as
containers for data. When you create a
variable in your code, your computer reserves a chunk of its own memory to
store that value. This lets the computer access the variable later to read
or modify the value. Let’s see this in action. Imagine a simple script
that calculates the area of a rectangle using the formula area equals length times width. Area, length and width can all be represented by variables like this.
length = 10
width = 2 area = length * width
In this script we are creating three variables and storing
different values in each. The process of storing a value inside a variable is
called assignment. Here we assign the length
variable the value of 10. We assign the width
variable the value of two and we assign the area variable with the result of the expression length times width. An expression is a
combination of numbers, symbols or other variables that produce a result when evaluated. In this example, we are
multiplying the value of two variables to arrive at
the value that we want. Finally, we use our old
friend the print function to display the value of the area
on the screen: print(area)
20 All right. We have just seen how to
assign values to variables, use expressions to calculate more complex values and then print the contents of a variable. Variables are important in
programming because they let you perform operations
on data that may change. For example, if we extended
our rectangle script to accept any input as the value of the length and
width variables, we could calculate the
area of a rectangle of any size or to give a
more IT focused example, say we have a script
that performs a specific operation on a file. We can extend that script to perform the same operation on any file but only if the program used a variable to
store the file name. You might have noticed that we assign a value to a
variable by using the equal sign in the form
of variable equals value. Generally, you can name
variables whatever you like but there are
some restrictions. First, you shouldn’t use
as variable names any of the key words or
functions that Python reserves for its own, like print. Using these reserved
terms will make your program confusing to read
and will result in errors. Python also has some
restrictions on the characters you can
use to define a variable. Variable names can’t have
any spaces and they must start with either a
letter or an underscore. Also, they can only be made up of letters, numbers
and underscores. Let’s check out some examples of valid and invalid variable names to understand this better. I_am_a_variable is the
valid variable name. I_am_a_variable2 is also
a valid variable name. 1_is_a_number is invalid because variable names must start
with a letter or underscore. Apples_&_oranges
is invalid because it uses the special
character ampersand. Last thing, remember that precision is important
when programming. Python variables are case sensitive, so
capitalization matters. Lowercasename,
uppercasename and ALLCAPSNAME are all valid
and different variable names, and that rule on
variables is invariable.
Now, it's your turn to give it a try!
Fill in the blanks to calculate the area of a triangle of base 5, height 3 and output the result. Reminder: the area of a triangle is (base*height)/2.
base = 5
height = 3
area = (base*height)/2
print(area)
Here is your output: 7.5 Awesome! You’re harnessing the power of variables in your scripts!
Video: Expressions, Numbers, and Type Conversions
In this video, you learned about implicit and explicit type conversion in Python.
Implicit type conversion is when Python automatically converts one data type to another. For example, if you add an integer and a float, Python will automatically convert the integer to a float.
Explicit type conversion is when you explicitly tell Python to convert one data type to another. You can do this using a function called str()
, which converts a number to a string.
Example:
# Implicit type conversion
print(7 + 8.5)
# Output: 15.5
# Explicit type conversion
base = 6
height = 3
area = (base * height) / 2
print("The area of the triangle is: " + str(area))
# Output: The area of the triangle is: 9.0
Tips:
- Use implicit type conversion when it is convenient and does not lead to errors.
- Use explicit type conversion when you need to ensure that a value is of a specific data type.
- Be careful not to mix data types when performing operations. This can lead to errors.
Additional thoughts:
Type conversion is an important concept in Python. By understanding how to use type conversion effectively, you can write more efficient and bug-free code.
Introduction
In Python, an expression is a combination of variables, operators, and values that evaluates to a single value. Expressions are used to perform calculations, make comparisons, and control the flow of execution in our programs.
Numbers
Python has four types of numbers: integers, floats, complex numbers, and Booleans.
- Integers are whole numbers, such as 1, 10, and -2.
- Floats are numbers with decimal points, such as 3.14 and -1.5.
- Complex numbers are numbers of the form a + bi, where a and b are real numbers and i is the imaginary unit.
- Booleans are values that can be either True or False.
Type Conversions
In Python, we can convert from one data type to another using type conversion functions. The most common type conversion functions are:
- int(): Converts a string or a float to an integer.
- float(): Converts a string or an integer to a float.
- complex(): Converts a string or two numbers to a complex number.
- str(): Converts a number or a Boolean to a string.
- bool(): Converts a string or a number to a Boolean.
Expressions
Expressions can be made up of numbers, variables, operators, and other expressions. The following are some of the most common operators in Python:
- Arithmetic operators: +, -, *, /, //, %
- Comparison operators: ==, !=, <, >, <=, >=
- Logical operators: and, or, not
- Membership operators: in, not in
- Identity operators: is, is not
Type Conversions in Expressions
When an expression contains numbers of different types, Python will automatically convert the lower-type numbers to the higher-type number. For example, the expression 1 + 2.5
will be evaluated as 3.5
because the integer 1
is automatically converted to a float.
We can also explicitly convert numbers from one type to another using type conversion functions. For example, the expression str(1)
will convert the integer 1
to a string.
Conclusion
Expressions are a fundamental part of Python programming. They are used to perform calculations, make comparisons, and control the flow of execution in our programs. By understanding how expressions work, we can write more concise and efficient code.
Here are some additional tips for writing expressions in Python:
- Use parentheses to group expressions together to make them easier to read and understand.
- Use type conversion functions to explicitly convert numbers from one type to another when necessary.
- Be aware of the different types of operators and how they work.
- Use the Python documentation to learn more about expressions and other aspects of Python programming.
In an earlier video, we saw how we can’t use
the plus operator between an integer and a string because they’re
different data types. But what happens when we try
to operate with an integer and a float instead? Let’s find out:
[typing] print(7+8.5)
[computer response] 15.5 Woohoo! Error-free, Python has no problem performing
this operation. But what’s up with
that? Aren’t integers and floats two
different data types? They sure are but there’s a lot happening
under the hood here. Behind the scenes the computer
is busy automatically converting our integer
seven into a float seven. This lets Python
then add together the values to return a result
that is also a float. We call this process
implicit conversion. The interpreter
automatically converts one data type into another. We’ve called this out before, but it’s worth
highlighting again that Python operations aren’t
just restricted to numbers. You can also use the plus operator
to add together strings. [typing] print(“a”+”b”+”c”)
[computer response] abc This lets you do
things like create sentences from individual words.
[typing] print(“This “+ “is “+ “pretty “ +neat!”)
[computer response] This is pretty neat! Just don’t forget to add spaces to each word. Otherwise, the computer
will run them all together. So what if you really want to combine a string and a
number, is it possible? It sure is but only with
an explicit conversion. In Python, to convert between
one data type and another, we call a function with the name of the type
we’re converting to. Let’s see how this works. Now, things are getting a
little bit more complex. Let’s take a moment to unpack this to make sure it all makes sense.
[on screen] Base = 6
[on screen] Height = 3 In this script, we’re first calculating the area of a triangle,
[on screen] area = (base*height)/2 and when printing it we’re adding it to a string.
[on screen] print(“The area of the triangle is: ” + str(area)) To do this, we need to call the str() function to convert
a number into a string. Let’s execute it and
check out what happens. [computer response] The area of the triangle is: 9.0
Our number got converted to a string and printed together
with the message. Woohoo! We’ve learned a little
bit about variables, values, expressions,
and conversions. Next up, we’ve got a practice quiz to help you
solidify your knowledge. As always, take your time and review the
content if you need. You’ve totally got this. I’ll see you in the next
video once you’re finished.
Practice writing some expressions and conversions yourself.
In this scenario, we have a directory with 5 files in it. Each file has a different size: 2048, 4357, 97658, 125, and 8. Fill in the blanks to calculate the average file size by having Python add all the values for you, and then set the files variable to the number of files. Finally, output a message saying "The average size is: " followed by the resulting number. Remember to use the str() function to convert the number into a string.
total = 2048 + 4357 + 97658 + 125 + 8
files = 5
average = total / files
print("The average size is: " + str(average))
Here is your output: The average size is: 20839.2 Nice job! We’re tackling trickier concepts now and you’re doing great!
Reading: Implicit vs Explicit Conversion
Reading
As we saw earlier in the video, some data types can be mixed and matched due to implicit conversion. Implicit conversion is where the interpreter helps us out and automatically converts one data type into another, without having to explicitly tell it to do so.
By contrast, explicit conversion is where we manually convert from one data type to another by calling the relevant function for the data type we want to convert to. We used this in our video example when we wanted to print a number alongside some text. Before we could do that, we needed to call the str() function to convert the number into a string. Once the number was explicitly converted to a string, we could join it with the rest of our textual string and print the result.
Practice Quiz: Practice Quiz: Expressions and Variables
In this scenario, two friends are eating dinner at a restaurant. The bill comes in the amount of 47.28 dollars. The friends decide to split the bill evenly between them, after adding 15% tip for the service. Calculate the tip, the total amount to pay, and each friend’s share, then output a message saying “Each person needs to pay: ” followed by the resulting number.
bill = 47.28
tip = bill * 0.15
total = bill + tip
share = total / 2
print("Each person needs to pay: " + str(share))
Great work! You’ve given the computer correct instructions at each step, paying attention to every detail, and it paid off!
This code is supposed to take two numbers, divide one by another so that the result is equal to 1, and display the result on the screen. Unfortunately, there is an error in the code. Find the error and fix it, so that the output is correct.
numerator = 10
denominator = 10
result = numerator / denominator
print(result)
You got it!. You caught the error and fixed it! Way to go!
Combine the variables to display the sentence “How do you like Python so far?”
word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"
print(word1 + " " + word2 + " " + word3 + " " + word4 + " " + word5 + " " + word6 + " " + word7)
Nice job! You caught the error and fixed it! Way to go!
This code is supposed to display “2 + 2 = 4” on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct.
print("2 + 2 = " + str(2 + 2))
Way to go! You noticed the missing conversion into string, and fixed it!
What do you call a combination of numbers, symbols, or other values that produce a result when evaluated?
An expression
Right on! An expression is a combination of values, variables, operators, and calls to functions.
Functions
Video: Defining Functions
This video introduces the concept of functions in Python. Functions are blocks of code that can be reused throughout a script. To define a function, you use the def
keyword, followed by the name of the function and its parameters, if any. The body of the function is indented to the right.
In this example, we define a function called greeting()
, which takes two parameters: name
and department
. The function prints a greeting to the user and tells them which department they are part of.
def greeting(name, department):
print("Welcome, " + name)
print("You are part of " + department)
# Call the greeting() function
greeting("Blake", "IT Support")
greeting("Ellis", "Software engineering")
Output:
Welcome, Blake
You are part of IT Support
Welcome, Ellis
You are part of Software engineering
Functions are a powerful tool in Python. By writing functions, you can make your code more reusable and efficient.
Additional thoughts:
Here are some tips for writing functions in Python:
- Give your functions descriptive names. This will make your code more readable and easier to understand.
- Use parameters to pass data into your functions. This will make your functions more reusable.
- Document your functions. This will help other programmers understand what your functions do and how to use them.
- Test your functions. Make sure that your functions work as expected before using them in your production code.
I encourage you to practice writing functions in your own code. The more you write functions, the better you will become at it.
What is a function?
A function is a block of code that performs a specific task. Functions can be used to avoid repeating code, make code more modular and easier to understand, and pass data around.
How to define a function in Python
To define a function in Python, you use the def
keyword. The syntax for defining a function is as follows:
def function_name(parameters):
# Body of the function
function_name
: The name of the function.parameters
: The parameters of the function. Parameters are variables that are passed into the function when it is called.Body of the function
: The body of the function is where the code that performs the task of the function is written. The body of the function must be indented to the right.
Here is an example of a function in Python:
def greeting(name):
print("Welcome, " + name)
This function takes a parameter called name
and prints a greeting to the user.
How to call a function in Python
To call a function, you use its name and pass in any required parameters. The syntax for calling a function is as follows:
function_name(parameters)
For example, the following code calls the greeting()
function and passes in the parameter "Bard"
:
greeting("Bard")
This code will print the following output:
Welcome, Bard
Here are some additional points about defining functions in Python:
- The name of the function should be descriptive of the task that the function performs.
- The parameters of the function should be named in a way that makes it clear what data they represent.
- The body of the function should be well-organized and easy to read.
- Functions should be used to avoid repeating code.
- Functions should be used to make code more modular and easier to understand.
- Functions should be used to pass data around.
You made it through another quiz. You are doing
awesomely, keep it up. So far we’ve been
looking at variables, expressions, and
operations which are the smallest
components of scripts. Up next, we’re going to look at functions which are another crucial programming
building block. We’ve come across a few Python functions
in our examples so far: the print function that
writes text on the screen, the type function which tells us the type of a certain value, and the str function which converts a
number into a string. All those functions come
as a part of the language, and we’ll look into a bunch of other built-in Python functions
throughout this course. But now we’re going to see how to define our own
functions to tell the computer to do things that the language’s built-in
functions don’t. Let’s start with
a simple example. In this piece of code,
[on screen] def greeting(name): we’re defining a function.
[on screen] print(“Welcome, ” + name) Our function takes the parameter, here that parameter is name and prints a
greeting for that name. This snippet is small but
it already shows a lot of important points about how we
define functions in Python. Let’s go through
this step-by-step. To define a function, we use the def keyword. The name of the function is
what comes after the keyword. In this example, the
function’s name is greeting. So to call the function
later in the script, we’ll use the word greeting. After the name, we
have the parameters of the function which are
written between parentheses. In this example, we only
have one parameter, name, followed by a colon
at the end of the line. After the colon, we have
the body of the function. That’s where we state what
we want our function to do. Note how the body is
indented to the right. This is a key characteristic of Python and we’ll come
across it a bunch. For now, just keep in
mind that the body of the function must be to the
right of the definition. In this example,
the body contains just one line that calls
the print function. Looks simple, right? But creating functions can actually
be super powerful. The body of a function can
have as many lines as we want it to and do all
sorts of fun stuff. We’ll find out exactly
what in later videos. But for now, let’s execute
our function and see what happens. [typing] greeting(“Kay”)
[computer response] Welcome, Kay
[typing] greeting(“Cameron”)
[computer response] Welcome, Cameron That’s nice. But it’s not
too interesting yet. Let’s make it do a little more. [on screen]
def greeting(name, department)
print(“Welcome, ” + name)
print(“You are part of ” + department) Our function now receives two parameters
instead of one, name and department. And it writes two separate messages. Again, notice the indentation. We can add as many lines as we’d like to the
body of the function but each line must be indented the same number of
spaces to the right. In this example, we’re
using four spaces. We could use two or eight or any other number as long
as they’re all consistent. Let’s try calling our new and
improved greeting function. [typing] greeting(“Blake”, “IT Support”)
[computer response] Welcome, Blake
You are part of IT Support [typing] greeting(“Ellis”, “Software engineering”)
[computer response] Welcome, Ellis
You are part of Software engineering Nice. That’s more useful, and we’re only just scratching the surface of what we
can do with functions. Remember that these are
just simple examples but a function can do a lot more than just print messages. In this course and throughout
the upcoming courses, we’ll explore a bunch of other
tasks that we can do with Python and usually we’ll
write them inside functions. How are you feeling so far? These new concepts are
coming fast and furious now. Are you starting to get
to grips with it all? If so, awesome, and if some things are
still a little fuzzy, now is a great moment to go back and review everything
we’ve covered up till now. Once you’re feeling good, meet me on over in the next video.
Video: Returning Values
Functions are blocks of code that can be reused throughout a script. To return a value from a function, you use the return
keyword. The return value of a function is the value that is returned to the caller when the function is finished executing.
Functions can return multiple values. To do this, you return a tuple, which is a collection of values.
It is also possible for a function to return nothing. This is done by omitting the return
keyword.
Example:
def calculate_area(base, height):
"""Calculates the area of a triangle.
Args:
base: The base of the triangle.
height: The height of the triangle.
Returns:
The area of the triangle.
"""
area = base * height / 2
return area
# Calculate the area of two triangles.
area_a = calculate_area(10, 5)
area_b = calculate_area(6, 3)
# Add the areas of the two triangles together and print the result.
sum = area_a + area_b
print(sum)
# Output: 32.5
def convert_seconds_to_hms(seconds):
"""Converts a number of seconds to hours, minutes, and seconds.
Args:
seconds: The number of seconds to convert.
Returns:
A tuple containing the number of hours, minutes, and seconds in the given
number of seconds.
"""
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
return hours, minutes, seconds
# Convert 10,000 seconds to hours, minutes, and seconds.
hours, minutes, seconds = convert_seconds_to_hms(10000)
# Print the result.
print(f"{hours}:{minutes}:{seconds}")
# Output: 2:46:40
# Define a function that prints a message but doesn't return anything.
def say_hello():
print("Hello!")
# Call the function.
say_hello()
# Try to assign the return value of the function to a variable.
result = say_hello()
# Print the variable.
print(result)
# Output: None
Additional thoughts:
Return values are a powerful feature of Python functions. By using return values, you can write code that is more reusable, efficient, and readable.
Here are some tips for using return values effectively:
- Think about what data your function needs to produce and return.
- Use descriptive names for your return values.
- Document your functions so that other programmers understand what your functions do and what data they return.
- Test your functions to make sure that they return the correct values.
I encourage you to practice writing functions with return values in your own code. The more you practice, the better you will become at it.
What is a return value?
A return value is the value that a function returns to the caller. The return value can be any data type, including numbers, strings, lists, dictionaries, and objects.
How to return a value from a function
To return a value from a function, you use the return
keyword. The syntax for returning a value from a function is as follows:
return value
value
: The value that you want to return from the function.
Here is an example of a function that returns a value:
def get_greeting(name):
"""This function returns a greeting for the given name."""
return "Hello, " + name
This function takes a parameter called name
and returns a greeting for the given name.
How to call a function that returns a value
To call a function that returns a value, you use the function’s name and pass in any required parameters. The syntax for calling a function that returns a value is as follows:
value = function_name(parameters)
value
: The variable that you want to store the return value in.function_name
: The name of the function that you want to call.parameters
: The parameters that you want to pass to the function.
For example, the following code calls the get_greeting()
function and stores the return value in the variable greeting
:
greeting = get_greeting("Bard")
This code will print the following output:
Hello, Bard
Here are some additional points about returning values from functions:
- A function can only return one value.
- If you do not want to return a value from a function, you can use the
return
keyword without any arguments. - The
None
data type can be used to represent a value that is empty or has no value.
We’ve seen how we can pass values into a function
as parameters by passing values like the name or department in the
example earlier. But what about getting
values out of a function? This is where the concept of
return values comes into play. The work that functions do
can produce new results. Sure, we can print the
results on the screen, but what if we wanted to
use those results later in our script or didn’t want
to print them at all? We can do this by returning values from the functions
we define ourselves. Let’s go back to calculating
the area of a triangle. Do you remember our
triangle example from our earlier exercise? The area of the
triangle is calculated as base times height
divided by 2. Imagine we need to calculate this value several
times in our code. It would be useful
to have a function that does this for us. Check out how this would look. We use the keyword return to tell Python that this is the
return value of a function. When we call the function, we store that value
in a variable. Let’s say we have the
two triangles and we want to add up the
sum of both areas. Here’s what we
would do. First, we calculate the two
areas separately. Then, we add the sum of
both areas together. Finally, we print the result,
converting it to a string. As you can see in this example, the area_triangle
function returns a value which is not surprisingly
the area of the triangle. We store that value in a different variable for
each call to the function. In this case, area_a and area_b. Then we operate with those values adding them into the variable called sum and only
printing this final result. This shows the power of
the return statement. It allows us to combine
calls to functions and to more complex operations which makes your code more reusable. Return statements in
Python are even more interesting because we can use them to return more
than one value. Let’s say you have a duration of time in seconds and you want to convert that to the
equivalent number of hours, minutes, and seconds. Here’s how to do that in Python. Did you spot the new
operator in this function? That double slash operator
is called floor division. A floor division divides a number and takes the integer part of
the division as the result. For example, five slash slash
two is two instead of 2.5. In our example, the first
operation is calculating how many hours are in a
given amount of seconds. While the second works out how many minutes are left once we subtract the hours and then how many seconds remain
after subtracting minutes. We end up with three
numbers as a result. So the function returns
all three of them. Let’s see what this looks like when we’re calling a function. Because we know that the
function returns three values, we assign the result of the function to three
different variables. There’s one last thing we should call out about returning values. It is possible to return nothing and that’s
perfectly okay. Let’s look at an example
from an earlier video. Here the function just printed a message and
didn’t return anything. What do you think would
happen if we try to assign the value of this
function to a variable? Let’s try it out and see. Here when we called the function, it printed a message just
like we expected. We stored the return value
in the result variable, but there was no return
statement in the function. So the value of results is none. None is a very special data
type in Python used to indicate that things are empty or that they
return nothing. Wow. That was a lot to learn about functions and
the return values. Remember that the key to
getting this right is to practice writing the code you’ve just learned as many
times as you need. Functions and return values can be tricky concepts to master, but they let us do a
bunch of cool stuff. So put the time and
effort in to learn it for some really valuable returns.
Video: The Principles of Code Reuse
Functions are a powerful way to organize and reuse code. They can be used to perform calculations, manipulate data, and print messages.
To define a function in Python, you use the def
keyword, followed by the name of the function and its parameters. The body of the function is indented to the right.
To call a function, you simply type its name followed by parentheses. If the function has parameters, you must pass values to those parameters when you call the function.
Functions can also return values. To do this, you use the return
keyword. The return value of a function is the value that is returned to the caller when the function is finished executing.
Example:
def lucky_number(name):
"""Calculates the lucky number for a given name.
Args:
name: The name of the person.
Returns:
The lucky number for the given name.
"""
length = len(name)
lucky_number = length * 2
print(f"The lucky number for {name} is {lucky_number}.")
# Call the function twice, once with each name.
lucky_number("Alice")
lucky_number("Bob")
Output:
The lucky number for Alice is 10.
The lucky number for Bob is 8.
Functions are a valuable tool for Python programmers. By using functions, you can write code that is more reusable, efficient, and readable.
Additional thoughts:
Here are some tips for using functions effectively:
- Give your functions descriptive names. This will make your code more readable and easier to understand.
- Use parameters to pass data into your functions. This will make your functions more reusable.
- Document your functions. This will help other programmers understand what your functions do and how to use them.
- Test your functions to make sure that they work as expected before using them in your production code.
I encourage you to practice writing functions in your own code. The more you practice, the better you will become at it.
Tutorial on the Principles of Code Reuse in Python
What is code reuse?
Code reuse is the practice of using existing code for a new function or software. This can be done by copying and pasting code, or by using functions and modules.
Why is code reuse important?
Code reuse has a number of benefits, including:
- Reduced development time: When you reuse code, you don’t have to write the same code over and over again. This can save you a lot of time and effort.
- Improved code quality: When you reuse code that has already been tested and debugged, you can be more confident that your code is correct and reliable.
- Increased maintainability: Reusable code is easier to maintain because you only need to update one copy of the code when you make a change.
How to reuse code in Python
There are a number of ways to reuse code in Python, including:
- Functions: Functions are a great way to reuse code because they allow you to group together related code and give it a name. You can then call the function whenever you need to perform the operation that it encapsulates.
- Modules: Modules are collections of related functions and variables. You can import modules into your code to reuse the code that they contain.
- Object-oriented programming (OOP): OOP is a programming paradigm that allows you to create reusable classes and objects. Classes are blueprints for creating объектов, and objects are instances of classes.
Tips for reusing code effectively
Here are some tips for reusing code effectively:
- Choose the right level of abstraction: When you reuse code, it is important to choose the right level of abstraction. This means that you should reuse code at a level that is high enough to be generalizable, but low enough to be useful.
- Document your code: It is important to document your code so that other programmers can understand what it does and how to use it. This is especially important when you are reusing code that you have written yourself, or when you are using code that has been written by others.
- Test your code: It is important to test your code to make sure that it works as expected. This is especially important when you are reusing code, as you may be introducing new bugs into your code.
Examples of code reuse in Python
Here are some examples of code reuse in Python:
# Define a function to calculate the area of a triangle
def calculate_triangle_area(base, height):
area = base * height / 2
return area
# Calculate the area of two triangles
triangle_1_area = calculate_triangle_area(10, 5)
triangle_2_area = calculate_triangle_area(6, 3)
# Print the area of the two triangles
print(triangle_1_area)
print(triangle_2_area)
In this example, we define a function called calculate_triangle_area()
to calculate the area of a triangle. We then reuse this function to calculate the area of two different triangles.
# Import the math module
import math
# Calculate the square root of a number
square_root = math.sqrt(16)
# Print the square root
print(square_root)
In this example, we import the math
module to reuse the sqrt()
function to calculate the square root of a number.
# Define a class to represent a person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create two Person objects
person_1 = Person("Alice", 25)
person_2 = Person("Bob", 30)
# Print the name and age of each person
print(person_1.name, person_1.age)
print(person_2.name, person_2.age)
In this example, we define a class called Person
to represent a person. We then reuse this class to create two different Person objects.
Conclusion
Code reuse is a powerful technique that can help you write better code faster. By following the tips in this tutorial, you can effectively reuse code in your own Python projects.
[MUSIC] As we’ve called out before, functions are
powerful because you can create your own. You can use them to organize the code
in your scripts into logical blocks, which makes the code you write
easier to use and reuse. Check out this example. This script uses the len function,
which returns the length of a string. In this example the script then uses
that length to calculate a number, which we’re calling the lucky number here. And finally, it prints a message
with the name and the number. Each time you want to
perform the calculation, we change the values of the variables and
write the formula. Then, print a greeting
followed by the lucky number. See how there are exactly
two lines that are the same, in the first and second part of the code. When you find code
duplication in your scripts, it’s a good idea to check if you can clean
things up a bit by using a function. How about we rewrite this code creating a
function to group all the duplicated code into just one line. The updated script gives us the exact
same result as the original one, but it looks a lot cleaner. First, we’ve defined a function
called lucky number, which carries out our calculation and
prints it for us. Then we call the function twice,
once with each name. Since we’ve grouped the calculation and
print statements into a function, our code is not only easier to read but
it’s also now reusable. We can execute the code inside the lucky
number function as many times as we need it, by just calling it
with a different name. So we don’t have to write it out
again and again for each new name, does that make sense? Hopefully, these examples have helped
explain how functions are used and defined. And also demonstrated
how useful they can be. Did you notice that we’re feeding
information into our functions through their parameters? This is one of the many ways that
we can input data into our code. The values for those parameters may come
from different places, like a file on our computer or through a form on a
website, but that doesn’t impact our code. The result of the function
is still the same, no matter where the parameters come from. Functions are your friends. They can help clean up your code and
do math so you don’t have to. You’ll be using them a lot both in this
course and in your programming life. So get ready to get real
friendly with functions.
Video: Code Style
Good programming style is important because it makes code more readable and maintainable for everyone who has to interact with it. This includes the code author, IT specialists, system administrators, and other programmers.
Here are some principles of good programming style:
- Write self-documenting code. This means using descriptive variable names and writing clear and concise expressions.
- Refactor your code. This means rewriting your code to make it more self-documenting and readable.
- Use comments. Comments are used to explain tricky bits of code or to leave notes for yourself or other programmers.
- Follow a style guide. A style guide is a set of guidelines for writing code in a consistent and readable way.
By following these principles, you can write code that is more stylish and easier to work with.
Additional thoughts:
Good programming style is a skill that takes time and practice to develop. Don’t be discouraged if your code doesn’t look perfect at first. Just keep practicing and following the principles above, and you will eventually develop good coding style habits.
Tutorial on Code Style in Python
What is code style?
Code style is the way in which code is written. It includes things like indentation, whitespace, variable naming, and commenting.
Why is code style important?
Good code style makes code more readable and maintainable. This is important for the following reasons:
- It makes it easier for other programmers to understand and modify your code.
- It makes it easier for you to debug your code and find errors.
- It makes your code look more professional and polished.
Python code style guide
The Python community has developed a style guide called PEP 8. PEP 8 provides a set of recommendations for writing Python code in a consistent and readable way.
Some of the key recommendations in PEP 8 include:
- Use four spaces for indentation.
- Use one space after keywords and operators.
- Use two spaces before and after colons.
- Use consistent variable naming conventions.
- Use comments to explain tricky bits of code or to leave notes for yourself or other programmers.
Here are some tips for writing Python code in good style:
- Use descriptive variable names. This will make it easier for other programmers to understand what your code is doing.
- Write short, concise lines of code. This will make your code easier to read and understand.
- Use whitespace to make your code more readable. This includes using indentation, blank lines, and spaces around operators and keywords.
- Use comments to explain tricky bits of code or to leave notes for yourself or other programmers.
Example of good code style:
def greet(name):
"""Greets the user by name.
Args:
name: The name of the user.
Returns:
A string greeting the user by name.
"""
greeting = f"Hello, {name}!"
return greeting
# Example usage:
print(greet("Alice"))
print(greet("Bob"))
This code is well-styled because it follows the recommendations in PEP 8. The variable names are descriptive, the lines of code are short and concise, and the code is well-indented and uses whitespace effectively. There is also a comment at the top of the function that explains what the function does and what its arguments and return value are.
Conclusion
Writing Python code in good style is an important skill for every Python programmer to have. By following the tips in this tutorial, you can write code that is more readable, maintainable, and professional.
So far, we’ve looked into how the Python syntax is
used for variables, expressions, and defining
and using functions. There’s a lot more
syntax to come. But before we dive into that, let’s talk a bit about a different side of
programming: style. On the whole, having good or bad style
when you write code doesn’t make much
difference between a script succeeding or crashing, but it can make a
big difference for the people who use it
and contribute to it. Poor programming style can make life difficult for
the IT specialists or system administrators
who have to read the script after it’s written
or make changes to it so it works with a new system. Bad style can even give the script’s author a headache if it’s been awhile
since they wrote it. Imagine having to rewrite your own code because it’s
too messy to understand. Yikes! On the flip side,
good style can make a script look almost like
natural human language. It can make the
script’s intent and construction immediately
clear to the reader. Goods style makes life easier for people
who have to maintain the code and helps them understand what it does
and how it does it. It can also reduce errors since it makes
updating the code easier and more straightforward. And, most importantly, good style makes you look cool, right? So we agree, our code
should be stylish. But what makes the style of
a piece of code good or bad? Although there are no
hard and fast rules that apply to every programming
language and situation, keeping a few principles
in mind will go a long way to creating
good, well-styled code. First off, you want your code to be as self-documenting as possible. Self-documenting code is
written in a way that’s readable and doesn’t
conceal its intent. This principle can be applied to all aspects of writing code from picking your variable names to writing clear
concise expressions. Take this code
snippet for example. It’s hard to
determine the purpose of this code by
just looking at it. The names of the variables
don’t give the reader much information. And, although you can likely work out the
result of the calculation, there are no clues to what
that result might be used for. In programming lingo, when we re-write code to be
more self-documenting, we call this process refactoring. So how would it look if
we refactored this code? With this refactored code, the intent should
now be more clear. The names of the variables and the function reflect
their purpose, which helps the reader understand
the code more quickly. You should always aim for your code to be self-documenting. But even then, sometimes
you may need to use a particularly tricky bit
of code in your script. When good naming and clean organization can’t
make the code clear, you can add a bit of
explanatory texts to the code. You do this by adding
what we call a comment. In Python, comments are
indicated by the hash character. When your computer
sees a hash character, it understands that
it should ignore everything that comes after that character on that line.
Check out how this looks. Using comments lets you explain why a function does
something a certain way. It also allows you to leave
notes to your future self or other programmers
to remind you of what needs to be
improved and why. Obviously, it’s much easier to read your own code
than someone else’s. But in my job, I work on code
that was written by lots of different people and everybody designs things a
little differently. This is why it’s so important to comment and document
your code well. More often than not, your code will eventually be used by someone other than you. So be a good neighbor. Use the style guide to structure your code in a way
that’s readable by others, or by you
in six months when you’ve forgotten why you wrote that code in the first place. In upcoming exercises
in this course, we’ll use comments to let you know what you need
to do with the code. You can always write as many
extra comments as you need. Coming up, a quiz to consolidate your newly acquired
knowledge about functions. Don’t worry. You’ve got this.
Practice Quiz: Functions
This function converts miles to kilometers (km). Complete the function to return the result of the conversion Call the function to convert the trip distance from miles to kilometers Fill in the blank to print the result of the conversion Calculate the round-trip in kilometers by doubling the result, and fill in the blank to print the result
# 1) Complete the function to return the result of the conversion
def convert_distance(miles):
return miles * 1.6 # approximately 1.6 km in 1 mile
# 2) Convert my_trip_miles to kilometers by calling the function above
my_trip_km = convert_distance(55)
# 3) Fill in the blank to print the result of the conversion
print("The distance in kilometers is " + str(my_trip_km))
# 4) Calculate the round-trip in kilometers by doubling the result,
# and fill in the blank to print the result
print("The round-trip in kilometers is " + str((my_trip_km)*2))
Woohoo! You’ve figured out how to make the functions do what they need to do, and remembered some things from the previous lessons. Way to go!.
This function compares two numbers and returns them in increasing order. Fill in the blanks, so the print statement displays the result of the function call in order. Hint: if a function returns multiple values, don’t forget to store these values in multiple variables
# This function compares two numbers and returns them
# in increasing order.
def order_numbers(number1, number2):
if number2 > number1:
return number1, number2
else:
return number2, number1
# 1) Fill in the blanks so the print statement displays the result
# of the function call
smaller, bigger = order_numbers(100, 99)
print(smaller, bigger)
Nice! You remembered how to accept multiple return values from a function. You’re ready for the next lesson!
What are the values passed into functions as input called?
Parameters
Nice job! A parameter, also sometimes called an argument, is a value passed into a function for use within the function.
Let’s revisit our lucky_number function. We want to change it, so that instead of printing the message, it returns the message. This way, the calling line can print the message, or do something else with it if needed. Fill in the blanks to complete the code to make it work.
def lucky_number(name):
number = len(name) * 9
return "Hello " + name + ". Your lucky number is " + str(number)
print(lucky_number("Kay"))
print(lucky_number("Cameron"))
Way to go! The function now returns the message, for the calling line to use it in any way it wants to.
What is the purpose of the def keyword?
Used to define a new function
Awesome! When defining a new function, we must use the def keyword followed by the function name and properly indented body.
Conditionals
Video: Comparing Things
Python has comparison operators that allow you to compare values and logical operators that allow you to combine multiple comparisons.
Comparison operators:
>
greater than<
less than==
equal to!=
not equal to>=
greater than or equal to<=
less than or equal to
Logical operators:
and
both expressions must be true for the result to be trueor
either expression must be true for the result to be truenot
inverts the result of the expression
Examples:
# Comparison operators
print(10 > 1) # True
print("cat" == "dog") # False
print(1 != 2) # True
# Logical operators
print("Yellow" > "Cyan" and "Brown" > "Magenta") # False
print(25 > 50 or 1 != 2) # True
print(not 42 == "Answer") # True
Additional thoughts:
Comparison and logical operators are essential for writing Python code. They allow you to make decisions and control the flow of your program.
If you are new to Python, I recommend practicing with comparison and logical operators until you feel comfortable using them. You can find many practice exercises online.
Introduction
In Python, you can compare two things using comparison operators. The comparison operators are:
- Greater than (>)
- Less than (<)
- Equal to (==)
- Not equal to (!=)
- Greater than or equal to (>=)
- Less than or equal to (<=)
The result of a comparison is a Boolean value, which can be either True
or False
.
Examples
print(1 > 2) # This will print False
print(1 < 2) # This will print True
print(1 == 2) # This will print False
print(1 != 2) # This will print True
print(1 >= 2) # This will print False
print(1 <= 2) # This will print True
Logical operators
Python also has logical operators, which can be used to combine multiple comparisons. The logical operators are:
- And (and)
- Or (or)
- Not (not)
The and
operator returns True
if both expressions are True
. The or
operator returns True
if either expression is True
. The not
operator inverts the value of the expression.
print(1 > 2 and 2 < 3) # This will print False
print(1 > 2 or 2 < 3) # This will print True
print(not 1 == 2) # This will print True
Using comparison operators in code
Comparison operators can be used in a variety of ways in Python code. For example, you can use them to:
- Check if a value is within a range:
age = 18
if age >= 18:
print("You are an adult.")
- Sort a list of values:
numbers = [1, 5, 3, 2, 4]
numbers.sort()
print(numbers) # This will print the list sorted in ascending order
- Make a decision:
if age >= 18:
can_vote = True
else:
can_vote = False
Conclusion
Comparison operators are a powerful tool that can be used to compare values and make decisions in Python code. By understanding how to use comparison operators, you can write more efficient and effective code.
[MUSIC] We’ve seen a few arithmetic expressions so
far, like addition, subtraction, and division. Remember when we turned
Python into a calculator? Well, Python can also compare values. This lets us check whether something
is smaller than, equal to, or bigger than something else. This allows us to take the result
of our expressions and use them to make decisions. Check out these three examples. In the first example 10 is greater than 1.
[typing] print(10>1)
So, the value true is printed as a result. True is a value that belongs to
another data type called the Boolean. Booleans represent one of two possible
states, either true or false. Every time you compare things in
Python the result is a Boolean of the appropriate value. In the second example we can see
our very first equality operator,
[typing] print(“cat” == “dog”) which is formed by putting
two equal signs == together. We use this operator to test whether
two things are equal to each other. In this example the string cat is
not equal to the string dog, so the Boolean that’s printed is false. In our third example we’re
doing the opposite comparison. By pairing an exclamation mark and
an equal sign we’re using the not equals operator,
[typing] print(1 != 2) which is the negated
form of the equality operator. In this particular line of code the
operator checks that 1 isn’t equal to 2.
[computer response] True We call out before that the plus operator
doesn’t work between integers and strings. What do you think will happen if we
try to compare an integer and string?
[typing] print(1 < “1”) Let’s find out by seeing if the number 1 is smaller than the string 1. [computer response] TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’ Wha, wha, wha, we get a type error. That’s the same error we got before. This happens because Python doesn’t know how to check if a number is smaller than a string. And what about the equality operator? [typing] print(1 == “1”) [computer response] False In this case the Interpreter has no problem telling us that the integer 1 and the string 1 aren’t the same. So what gives? Basically although they may seem similar to us because they both contain the same number, it’s clear to the computer that one is a number and the other is a string. For the computer it’s obvious that they are completely different entities. On top of the comparison and equality operators, Python also has a set of logical operators. These operators allow you to connect multiple statements together and perform more complex comparisons. In Python the logical operators are the words and, or, and not. Let’s look at some examples. [typing] print(“Yellow” > “Cyan” and “Brown” > “Magenta”)
[computer response] False To evaluate as true the and operator would need both expressions
to be true at the same time here. Here we’re comparing strings,
and the bigger and smaller operators refer
to alphabetical order. Yellow comes after cyan, but
brown doesn’t come after magenta. So this means that the first statement
is true, but the second one isn’t, which makes the result of
the whole expression false. If we use the or operator, instead,
the expression will be true if either of the expressions are true, and false
only when both expressions are false. Let’s try it out. [typing] print(25 > 50 or 1 != 2)
25 is definitely not bigger than 50,
but 1 is different than 2. So in the end the whole
expression is true. Last up, the not operator inverts the value of
the expression that’s in front of it. If the expression is true,
it becomes false. If it’s false, it becomes true. Just like this.
[typing] print(not 42 == “Answer”)
[computer response] True Logical operators are important because
they help us write more complex expressions. We’ll see this in action
in the next few videos. If this is the first time you’ve come
across these operators it might seem like there’s a lot to remember. But don’t worry, you’ll learn most of
them very quickly just by practicing. And in the next reading we
have a cheat sheet that lists all the operators available and
what each one does. It’s a handy resource you’re sure to find
useful when writing your own scripts.
Reading: Comparison Operators
Reading
In Python, we can use comparison operators to compare values. When a comparison is made, Python returns a boolean result, or simply a True or False.
- To check if two values are the same, we can use the equality operator: ==
- To check if two values are not the same, we can use the not equals operator: !=
We can also check if values are greater than or lesser than each other using > and <. If you try to compare data types that aren’t compatible, like checking if a string is greater than an integer, Python will throw a TypeError.
We can make very complex comparisons by joining statements together using logical operators with our comparison operators. These logical operators are and, or, and not. When using the and operator, both sides of the statement being evaluated must be true for the whole statement to be true. When using the or operator, if either side of the comparison is true, then the whole statement is true. Lastly, the not operator simply inverts the value of the statement immediately following it. So if a statement evaluates to True, and we put the not operator in front of it, it would become False.
Video: Branching with if Statements
Branching is the ability of a program to alter its execution sequence based on conditions. This is a key component in making programs useful.
Python uses the if
statement to control branching. The if
statement takes a condition as an argument, and if the condition is true, the body of the if
statement is executed. Otherwise, the body of the if
statement is skipped.
Here is an example of an if
statement:
def hint_username(username):
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
# Example usage:
hint_username("Alice") # Prints nothing
hint_username("Bob") # Prints "Invalid username. Must be at least 3 characters long"
You can also use the else
statement to specify what code should be executed if the condition in the if
statement is false.
Here is an example of an if
statement with an else
statement:
def hint_username(username):
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
else:
print("Valid username")
# Example usage:
hint_username("Alice") # Prints "Valid username"
hint_username("Bob") # Prints "Invalid username. Must be at least 3 characters long"
Branching is a powerful tool that can be used to write complex and useful programs. By understanding how to use if
and else
statements, you can control the flow of your programs and make them more dynamic.
What is branching?
Branching is the ability of a program to alter its execution sequence based on the values of its expressions. It is a fundamental concept in programming, and it is used to make programs more versatile and powerful.
How do if statements work?
An if statement is a conditional statement that executes a block of code only if a certain condition is met. The syntax of an if statement is as follows:
if condition:
# block of code to be executed if the condition is met
The condition is an expression that evaluates to a Boolean value, such as True or False. If the condition is True, the block of code inside the if statement will be executed. Otherwise, the block of code will be skipped.
Here is an example of an if statement:
username = "hello"
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
In this example, the condition is len(username) < 3
. This expression evaluates to True if the length of the username
variable is less than 3 characters. If the condition is True, the print statement will be executed. Otherwise, the print statement will be skipped.
What is an else statement?
The else statement is used to execute a block of code if the condition in the if statement is False. The syntax of the else statement is as follows:
if condition:
# block of code to be executed if the condition is met
else:
# block of code to be executed if the condition is False
Here is an example of an if-else statement:
username = "hello"
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
else:
print("Valid username")
In this example, the if statement checks if the length of the username
variable is less than 3 characters. If the condition is True, the print statement inside the if statement will be executed. Otherwise, the print statement inside the else statement will be executed.
How to use branching with if statements in Python
Branching with if statements can be used to make programs more versatile and powerful. Here are some examples of how branching can be used in Python:
- To check if a user entered a valid username
- To check if a number is even or odd
- To check if a file exists
- To check if a condition is met before executing a block of code
Now that we’re armed
with knowledge of Python’s expressions,
comparators, and variables, we can dive right into
how to use them in our scripts to perform different actions
based on their values. The ability of a program to alter its execution sequence
is called branching, and it’s a key component in
making your scripts useful. You probably use the idea of branching a bunch in
your everyday life. For example, if it’s before noon, you might greet someone
by saying good morning instead of good afternoon
or good evening. If it’s raining outside, you might choose to take an umbrella. If it’s cold, you
probably wear a jacket. In your scripts, you can instruct your computer to make
decisions based on inputs too. Let’s take a look at
an IT-focused example. In many companies, new
employees can choose the username they’ll use to
access the company’s systems, and usually, the chosen username needs to fit with a
given set of guidelines. Companies can set
different criteria for what a valid
username looks like. For now, let’s assume
that at your company, a valid username has to have
at least three characters. You’ve been tasked with writing
a program that will tell the user if their
choices are valid or not. To do that, you could write a function like this.
[on screen] Def hint_username(username): This function checks
whether the length of the username is smaller than three.
[on screen] If len(username) < 3: If it is, the function prints a message saying that the username is invalid.
[on screen] print(“Invalid username. Must be at least 3 characters long”) Look closely at how the
if statement is written. We write the keyword if followed by the condition
that we want to check for, and then followed by a colon. After that, comes the
body of the if block, which is indented
further to the right. You may notice that there are
some similarities between how an if block and the
function are defined. The keyword, either def or if, indicates the start
of a special block. At the end of the first
line, we use a colon, and then the body
of the function or the if block is
indented to the right. But there’s also an
important difference between how an if block and
a function are defined. The body of the if block
will only execute when the condition evaluates to
true; otherwise, it skipped. Of course, you can do a
lot more things inside the body of the if block
than just printing stuff. As we expand our
programming abilities, we’ll learn how to do things like shorten text that’s too long, delete a file if it exists, start a service if it’s not
running, and a bunch more. If your code is
inside a function, you could also choose
to return a value depending on whether a
certain condition is met. Can you imagine how
that would look? By now, you know how
to define functions, and inside those functions, you can now make your program do something only when certain
conditions are met. Ready to branch out and make our branches even more
interesting with else statements? Then hop on over
to the next video, or else, you’ll miss out.
The is_positive function should return True if the number received is positive, otherwise it returns None. Can you fill in the gaps to make that happen?
def is_positive(number):
if number > 0:
return True
is_positive(-5) returned None is_positive(0) returned None is_positive(13) returned True Congrats! You’ve now written your first conditional block. Great work!
Video: else Statements
The else
statement is used to specify what code should be executed if the condition in the if
statement is false.
Here is an example of an if
statement with an else
statement:
def hint_username(username):
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
else:
print("Valid username")
However, the else
statement is not always needed. For example, if you are returning a value inside the if
statement, then the code after the if
block will only be executed if the condition in the if
statement was false.
Here is an example:
def is_even(number):
if number % 2 == 0:
return True
else:
return False
# Example usage:
print(is_even(10)) # True
print(is_even(11)) # False
In this example, the is_even()
function returns True
if the number is even and False
if the number is odd. The else
statement is not needed, because the code after the if
block will only be executed if the number is odd.
Additional thoughts:
The if
and else
statements are powerful tools that can be used to control the flow of your programs. By understanding how to use these statements, you can write more complex and useful programs.
Here are some tips for using if
and else
statements effectively:
- Use descriptive variable names and comments to make your code more readable and maintainable.
- Use indentation to make your code more visually appealing and easier to read.
- Test your code thoroughly to make sure that it works as expected.
If you are new to programming, I recommend practicing with if
and else
statements until you feel comfortable using them. You can find many practice exercises online.
Introduction
An else statement in Python is used to execute a block of code when the condition in an if statement is false. The else statement is optional, but it can be helpful to make your code more readable and concise.
Syntax
The syntax for an else statement is as follows:
if condition:
# Do something
else:
# Do something else
The condition
is a Boolean expression that evaluates to either True or False. If the condition is True, the code in the if
block is executed. Otherwise, the code in the else
block is executed.
Example
The following code checks if a number is even. If the number is even, the code prints “The number is even”. Otherwise, the code prints “The number is odd”.
number = 10
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
In this example, the condition number % 2 == 0
is True because 10 is even. Therefore, the code in the if
block is executed and the message “The number is even” is printed.
When to use else statements
Else statements can be used in a variety of situations, such as:
- To provide an alternative outcome when a condition is not met.
- To make your code more readable and concise.
- To avoid having to use multiple if statements.
When not to use else statements
Else statements should not be used if the code in the else
block will never be executed. For example, the following code will never execute the code in the else
block because the condition in the if
statement is always True:
if True:
print("The code in the else block will never be executed")
else:
print("This message will never be printed")
Conclusion
Else statements are a useful tool for controlling the flow of your code. They can be used to make your code more readable and concise, and to avoid having to use multiple if statements.
[MUSIC] The if statement is already
a pretty useful construct, but we can extend it to make
it even more powerful. Think about the username
example from the last video. What if we also wanted to print
a message when the username was valid? Here, we’ve included an else
statement to achieve this. The program can now go in one of two
directions depending on the length of the username. If it’s not long enough, we get a message
indicating that the username is invalid. But if the program verifies that
the username is long enough, it will print a message
saying it is valid. Pay attention to how the else
statement is written. It uses the else keyword followed by
a colon to indicate the beginning of the else block. Once again, the body of the block
is further indented to the right. As we’ve called out before these
blocks can contain multiple lines and do more than just print messages. They can do calculations, modify values,
return values, and a lot more. And remember that you can choose to use
as many or as few spaces as you want for the indentation, but
you always need to indent and you always need to use
the same number of spaces. The else statement is very useful,
but we don’t always need it. Say we want to have a function that
checks if a value is even or odd. We could do that with a piece of code like this. Here, we’re using a new operator so
let’s first explain that. The modulo operator is represented
by the percentage sign and returns the remainder of the integer
division between two numbers. The integer division is an operation
between integers that yields two results which are both integers,
the quotient and the remainder. So if we do an integer division
between 5 and 2, the quotient is 2 and the remainder is 1. If we do an integer
division between 11 and 3, the quotient is 3 and the remainder is 2. Even numbers are all multiples of 2
which means the remainder of the integer division between an even number and
2 is always going to be 0. In this function, we’re using this principle to decide whether a number is even or not. So how come we have these two return
statements, one below the other, without an else statement? The trick is that when a return
statement is executed, the function exits so that the code
that follows doesn’t get executed. This means that if the number is even, the computer will reach the return
true statement and exit the function. Anything that comes after that will only
be executed if the condition in the if statement was false. In other words, once the function
reaches the return false line, we know for sure that the if condition
was false which means the number was odd. At first, you might feel more comfortable
including the else statement, even if it’s not needed and
that’s totally okay. It’s important to know that both
ways of writing this are correct. And remember that this technique
can only be used when you’re returning a value inside the if statement. To recap, the if statement allows
us to branch the execution based on a specific condition being true. The else statement lets us set a piece of
code to run only when the condition of the if statement was false. If you return a value inside an if block
then the code after the block will only be executed if the condition was false. All make sense? If all these ifs and elses are starting
to get a little confusing, that’s okay. There’s a lot to soak up here and the best
way to do that is yeah, you guessed it, practice. So review the content and
practice on your own as much as you need. Once you’re done,
meet me over in the next video.
The is_positive function should return True if the number received is positive and False if it isn’t. Can you fill in the gaps to make that happen?
def is_positive(number):
if number > 0:
return True
else:
return False
is_positive(-5) returned False is_positive(0) returned False is_positive(13) returned True Well done, you! You’re starting to master conditional expressions!
Video: elif Statements
The elif
statement is used to specify what code should be executed if the condition in the if
statement is false and the condition in the current elif
statement is true.
Here is an example of an if
statement with an else
statement and an elif
statement:
def hint_username(username):
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
elif len(username) > 15:
print("Invalid username. Must be no more than 15 characters long")
else:
print("Valid username")
# Example usage:
hint_username("Alice") # Prints "Valid username"
hint_username("Bob") # Prints "Invalid username. Must be at least 3 characters long"
hint_username("Charlie") # Prints "Invalid username. Must be no more than 15 characters long"
The elif
statement can be used to chain together multiple conditions. This allows you to write more complex and useful programs.
Additional thoughts:
The if
, elif
, and else
statements are powerful tools that can be used to control the flow of your programs. By understanding how to use these statements, you can write more complex and useful programs.
Here are some tips for using if
, elif
, and else
statements effectively:
- Use descriptive variable names and comments to make your code more readable and maintainable.
- Use indentation to make your code more visually appealing and easier to read.
- Test your code thoroughly to make sure that it works as expected.
If you are new to programming, I recommend practicing with if
, elif
, and else
statements until you feel comfortable using them. You can find many practice exercises online.
Introduction
In Python, the elif statement is used to execute a block of code if a certain condition is met. It is short for “else if” and is used as an extension to the if statement.
Syntax
The syntax for an elif statement is as follows:
if condition1:
# Do something
elif condition2:
# Do something else
else:
# Do something else
The condition1 and condition2 are expressions that can be evaluated to a Boolean value. If condition1 is true, the code in the first block will be executed. If condition1 is false, the code in the second block will be executed. If both condition1 and condition2 are false, the code in the else block will be executed.
Example
The following example shows how to use an elif statement to check if a number is even or odd:
number = 10
if number % 2 == 0:
print("The number is even.")
elif number % 2 == 1:
print("The number is odd.")
else:
print("The number is not an integer.")
In this example, the number variable is first assigned the value 10. Then, the if statement checks if the number is even. If it is, the code in the first block will be executed, which prints the message “The number is even.” If the number is not even, the code in the elif statement will be executed, which prints the message “The number is odd.” If the number is not an integer, the code in the else block will be executed, which prints the message “The number is not an integer.”
How elif statements work
When an elif statement is executed, the conditions are evaluated in order. The first condition that evaluates to True will cause the code in the corresponding block to be executed. If none of the conditions evaluate to True, the code in the else block will be executed.
It is important to note that the elif statement is not required. If you only have two conditions to check, you can use an if statement instead. However, if you have more than two conditions, it is more efficient to use an elif statement.
Conclusion
The elif statement is a powerful tool that can be used to make your programs more flexible and efficient. It is easy to use and can be combined with other control flow statements to create complex programs.
[MUSIC] The if and else blocks allow us to
branch execution depending on whether a condition is true or false. But what if there are more
conditions to take into account? This is where the elif statement, which
is short for else if, comes into play. But before we jump into how to use it, let’s take a look at why we
need it in the first place. Let’s go back to our trusty
username validation example. Now, what if your company also had a rule
that usernames longer than 15 characters aren’t allowed? How could we let the user know if
their chosen username was too long? We could do it like this. In this case, we’re adding an extra
if block inside the else block. This works, but the way the code is
nested makes it kind of hard to read. To avoid unnecessary nesting and make
the code clearer, Python gives us the elif keyword, which lets us handle
more than two comparison cases. Take a look. The elif statement looks very
similar to the if statement. It’s followed by a condition and
a colon, and a block of code indented to
the right that forms the body. The condition must be true for
the body of the elif block to be executed. The main difference between elif and if statements is we can only write an elif
block as a companion to an if block. That’s because the condition of the elif
statement will only be checked if the condition of the if
statement wasn’t true. So in this example, the program
first checks whether the username is less than three characters long, and
prints a message if that’s the case. If the username has at
least three characters, the program then checks if it’s
longer than 15 characters. If it is,
we get a message to tell us that. Finally, if none of the above
conditions were met, the program prints a message
indicating that the username is valid. There’s no limit to how many
conditions we can add, and it’s easy to include new ones. For example, say the company decided that
the username shouldn’t include numbers. We could easily add an extra elif
condition to check for this. Cool, right? You now know how to compare things and use
those comparisons for your if, elif, and else statements. And you are using all of
them inside functions. Using branching to determine
your program’s flow opens up a whole new realm of
possibilities in your scripts. You can use comparisons to pick between
executing different pieces of code, which makes your script pretty flexible. Branching also helps you do all kinds
of practical things like only backing up files with a certain extension, or only allowing login access to a server
during certain times of the day. Any time your program
needs to make a decision, you can specify its behavior
with a branching statement. Are you starting to notice tasks in
your day-to-day that could be made more efficient with scripting? There’s so many possibilities, and
we’re only just getting started with all the cool stuff programming
can help you do. Wow, we’ve covered a lot
in these last few videos. Remembering all these concepts
can take some time, and the best way to learn them is to use them. So we’ve put together a cheat sheet for
you in the next reading. You’ll find all these operators and branching blocks listed
there in one handy resource. It’s super useful when you
need a quick refresher. So no skipping the reading.
Reading: Conditionals Cheat Sheet
Reading
In earlier videos, we took a look at some of the built-in Python operators that allow us to compare values, and some logical operators we can use to combine values. We also learned how to use operators in if-else-elif blocks.
It’s a lot to learn but, with practice, it gets easier to remember it all. In the meantime, this handy cheat sheet gives you all the information you need at a glance.
Comparison operators
- a == b: a is equal to b
- a != b: a is different than b
- a < b: a is smaller than b
- a <= b: a is smaller or equal to b
- a > b: a is bigger than b
- a >= b: a is bigger or equal to b
Logical operators
- a and b: True if both a and b are True. False otherwise.
- a or b: True if either a or b or both are True. False if both are False.
- not a: True if a is False, False if a is True.
Branching blocks
In Python, we branch our code using if, else and elif. This is the branching syntax:
if condition1:
if-block
elif condition2:
elif-block
else:
else-block
Remember: The if-block will be executed if condition1 is True. The elif-block will be executed if condition1 is False and condition2 is True. The else block will be executed when all the specified conditions are false.
Practice Quiz: Practice Quiz: Conditionals
What’s the value of this Python expression: (2**2) == 4?
True
Complete the script by filling in the missing parts. The function receives a name, then returns a greeting based on whether or not that name is “Taylor”.
def greeting(name):
if name == "Taylor":
return "Welcome back Taylor!"
else:
return "Hello there, " + name
print(greeting("Taylor"))
print(greeting("John"))
Great work! You’re getting the hang of conditionals in Python.
What’s the output of this code if number equals 10?
if number > 11:
print(0)
elif number != 10:
print(1)
elif number >= 20 or number < 12:
print(2)
else:
print(3)
2
Right on! Our number is 10, which is smaller than 12, so it matches that condition.
Is “A dog” smaller or larger than “A mouse”? Is 9999+8888 smaller or larger than 100*100? Replace the plus sign in the following code to let Python check it for you and then answer.
print("A dog" > "A mouse")
print(9999+8888 > 100*100)
“A dog” is smaller than “A mouse” and 9999+8888 is larger than 100*100
You got it! Keep getting Python to do the work for you.
If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size?
def calculate_storage(filesize):
block_size = 4096
# Use floor division to calculate how many blocks are fully occupied
full_blocks = filesize // block_size
# Use the modulo operator to check whether there's any remainder
partial_block_remainder = filesize % block_size
# Depending on whether there's a remainder or not, return
# the total number of bytes required to allocate enough blocks
# to store your data.
if partial_block_remainder > 0:
return block_size + (full_blocks * block_size)
return full_blocks * block_size
print(calculate_storage(1)) # Should be 4096
print(calculate_storage(4096)) # Should be 4096
print(calculate_storage(4097)) # Should be 8192
print(calculate_storage(6000)) # Should be 8192
Awesome! Those were some complicated calculations that you needed to do, but you did it!
Module Review
Video: Basic Syntax Wrap Up
Summary:
In this module, we learned about the following Python syntax:
- Data types: integers, floats, strings, and booleans
- Variables and expressions
- Functions
- Branching with
if
,elif
, andelse
statements
These are powerful tools that allow us to write complex and useful Python programs.
Additional thoughts:
It is normal to feel overwhelmed after learning about so much new syntax. The best way to solidify your understanding is to practice writing Python code. You can find many practice exercises online, or you can come up with your own projects.
Don’t be afraid to make mistakes. Everyone makes mistakes when they are learning to program. The important thing is to learn from your mistakes and keep practicing.
I am excited to see what you create with the Python skills you have learned so far. Good luck with your next graded assessment!
You just completed
your second module and learned a whole lot
about Python syntax. Congrats. We’ve learned
how to operate with different data types and how to create our own variables
and expressions. We’ve defined our first functions
and learned how to make them return values so that
they’re more reusable. We then dove into creating branches in our
scripts which lets them act in different ways depending on the values
of our variables. We learned a lot of new
and very powerful stuff. Knowing how to
structure your code and functions and how to
make your code act in different ways depending
on values is what allows us to tell our
computer what to do. We’ll keep using these
tools throughout the course as we move on to more complex
and interesting things. Next step, you can put
everything you’ve learned to the test in the next
graded assessment. Don’t worry if you
don’t feel ready yet. Remember that you can re-watch the videos and do the
practice quizzes as many times as you
need to make sure you fully understand
everything we’ve covered. When you’re ready for the test, take your time and best of luck. I’ll catch you after you’ve
finished in the next module, where we’ll learn all about
loops. See you there.
Video: In Marga’s Words: Why I Like Python
Python is a popular programming language for writing scripts to maintain operating systems and other software. It is a readable language with a large library of modules that can be used to perform common tasks. However, Python is not a compiled language, so errors may not be detected until late in the development process. This can be mitigated by writing good tests.
Additional thoughts:
Python is a versatile language that can be used for a variety of tasks, including web development, data science, and machine learning. It is a popular choice for beginners because it is relatively easy to learn.
Here are some of the key benefits of using Python for writing scripts:
- Readability: Python code is generally easy to read and understand, even for people who are not familiar with programming.
- Standard library: Python comes with a large library of modules that can be used to perform common tasks, such as file I/O, networking, and web development.
- Versatility: Python can be used for a variety of tasks, from writing simple scripts to developing complex software applications.
- Community support: Python has a large and active community of users and developers who are always willing to help.
If you are looking for a language for writing scripts, Python is a great option. It is easy to learn, versatile, and has a large library of modules.
My team is responsible for
maintaining the operating system of a bunch of computers in
the fleet of Google. And many of the things that we do
are done through Python scripts. For example, we have a script that
keeps the computer up to date and the software is updated everyday and
that’s written in Python. We also have a script that
checks that the computer doesn’t have any specific problems, and
if there is a problem raises an alert for the user so that the user can take action. That one is also written in Python. We have a bunch of other scripts like that
that run in the computers of our users that are all written in Python. One of the things I like the most
about Python is that the code is really readable. You can give a piece of Python
code to someone that doesn’t even know how to program and
most of the time, they will have at least some
idea of what is going on. The other thing I like about Python is
that it comes with a lot of modules that do a lot of the things that
we want to do already. It’s been around for a while. There’s a lot of people that have
contributed to all of these modules. So it’s very likely that the thing you
want to do, it’s already in a module, and you only have to import it and use it. No computer language is perfect. Every computer language has its
advantages and disadvantages. In the case of Python, the one thing
that I find the most annoying is that because it’s not a compiled language,
there could be errors in the code that only get detected very
late in the development process. And while, it’s not good that all these
hidden errors could be in the code, it can be mitigated by writing good tests. If you write tests and
then the tests can test all of the code, even if it’s not hit every day, then you can be assured that your
code is working successfully. That’s why I think Python is great for writing small scripts that
are self-contained and not for big software projects that
have a lot of infrastructure on them.
Quiz: Module 2 Graded Assessment
Complete the function by filling in the missing parts. The color_translator function receives the name of a color, then prints its hexadecimal value. Currently, it only supports the three additive primary colors (red, green, blue), so it returns “unknown” for all other colors.
def color_translator(color):
if color == "red":
hex_color = "#ff0000"
elif color == "green":
hex_color = "#00ff00"
elif color == "blue":
hex_color = "#0000ff"
elif color == "black" or "yellow" or "":
hex_color = "unknown"
return hex_color
print(color_translator("blue")) # Should be #0000ff
print(color_translator("yellow")) # Should be unknown
print(color_translator("red")) # Should be #ff0000
print(color_translator("black")) # Should be unknown
print(color_translator("green")) # Should be #00ff00
print(color_translator("")) # Should be unknown
Well done! You’re breezing through the if-else clauses!
What’s the value of this Python expression: “big” > “small”
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. Alphabetically, “big” is less than “small”.
What is the elif keyword used for?
To handle more than two comparison cases
You got it! The elif keyword is used in place of multiple embedded if clauses, when a single if/else structure is not enough.
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 this function so that it returns the proper 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 be Pass
print(exam_grade(55)) # Should be Fail
print(exam_grade(60)) # Should be Pass
print(exam_grade(95)) # Should be Pass
print(exam_grade(100)) # Should be Top Score
print(exam_grade(0)) # Should be Fail
Good job! You’re getting the hang of it!.
What’s the value of this Python expression: 11 % 5?
1
Excellent! “%” is the modulo operator, which returns the remainder of the integer division between two numbers. 11 divided by 5 equals 2 with remainder of 1.
Complete the body of the format_name function. This function receives the first_name and last_name parameters and then returns a properly formatted string.
Specifically:
If both the last_name and the first_name parameters are supplied, the function should return like so:
print(format_name("Ella", "Fitzgerald"))
Name: Fitzgerald, Ella
If only one name parameter is supplied (either the first name or the last name) , the function should return like so:
print(format_name("Adele", ""))
Name: Adele
or
print(format_name("", "Einstein"))
Name: Einstein
Finally, if both names are blank, the function should return the empty string:
print(format_name("", ""))
Implement below:
def format_name(first_name, last_name):
if first_name != '' and last_name != '':
return ("Name: " + last_name + ", " + first_name)
elif first_name != '' or last_name != '':
return ("Name: " + last_name + first_name)
else:
return ''
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))
# Should return an empty string
Awesome! You’re getting the hang of the multiple and embedded “if” clauses!
The longest_word function is used to compare 3 words. It should return the word with the most number of characters (and the first in the list when they have the same length). Fill in the blank to make this happen.
def longest_word(word1, word2, word3):
if len(word1) >= len(word2) and len(word1) >= len(word3):
word = word1
elif len(word2) >= len(word1) and len(word2) >= len(word3):
word = word2
else:
word = word3
return(word)
print(longest_word("chair", "couch", "table"))
print(longest_word("bed", "bath", "beyond"))
print(longest_word("laptop", "notebook", "desktop"))
You got it! You’ve figured out how to use an elif clause, well done!
What’s the output of this code?
def sum(x, y):
return(x+y)
print(sum(sum(1,2), sum(3,4)))
10
You nailed it! We’re calling the sum function 3 times: returning 3, then 7, then adding up 3 plus 7 for the total of 10.
What’s the value of this Python expression?
((10 >= 52) and (10 <= 52))
True
Right on! When using the “and” operator, a statement is True if both parts of the conditional are True.
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):
if numerator > 0 and denominator > 0:
return (numerator % denominator) / denominator
return 0
print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0
Well done! You’re handling the math operations, as well as division by 0, perfectly!