Python
Functions
Think about the short instructions you gave others, such that when you provide the instruction, they know they must perform multiple subtasks to achieve that objective. One such example is telling someone to “get dressed.” When you instruct someone to get dressed, they know, thankfully, that they must put on underwear, socks, pants, shirt, etc. It would be cumbersome to provide the complete instruction set every single time. It is also possible to modify the instructions by providing extra information. For instance, we may tell them to “get dressed for prom.” In this case, they will follow a different set of subinstructions than previously, as they will choose a nice dress and corsage.

A function is a named block of code that you can reuse in your program. It’s like a mini-program within your program. You call a function by using its name, followed by parentheses. You can provide arguments (inputs) to the function as a comma-separated list in the parentheses. The function then processes these arguments and may perform some action or return a value. If the function returns a value, you can store it in a variable for later use.
For example, suppose we have a function called calculate_area that takes the length and width of a rectangle as arguments. It multiplies the arguments inside the function to find the area and returns the calculated area. Note this example will not run in Google Colab as the calculate_area function is not included in the Python standard library and does not exist in your program. Below is an example of how we would use this function if it did exist.
# Initialize variables for the length and width values
rectangle_length = 2
rectangle_width = 3
# Store the result in a variable for future usage
rectangle_area = calculate_area(rectangle_length, rectangle_width)
In a future chapter, we will discuss how you could create this caclulate_area function yourself.
Outputting Information to the User
It’s time to make our program more interactive by outputting information to the user. In Python 3, we can do this with the print function. This function is a powerful tool that can take any number of arguments (of any data type), each of which will be displayed on the screen with a space between them. It’s important to note that the print function doesn’t return a value; it’s purely for displaying information. While you may encounter f-strings in other sources, we won’t cover them in this course and prohibit using them in your programs.
It’s time for a tradition that dates back to 1978: We will make our program display “Hello, world!” to the user. This is typically considered the start of someone’s programming journey. We will use the print function to accomplish this using a single argument, which will be a string literal.
print(“Hello, world!”) # Outputs: Hello, world!
We could have used multiple string literal arguments to accomplish as shown below:
print(“Hello,”, “world!”) # Outputs: Hello, world!
Be careful when using multiple arguments to the print function, as it will always add a space between them. In a future chapter, we will introduce string concatenation, which will give us finer control over combining multiple text strings.
Receiving User Input
While one-way communication with our program is functional, embracing two-way communication can significantly enhance our programs. This interactive approach allows our program to adapt and change with each execution, making it more dynamic. As programmers, we often seek this dynamism, enabling users to provide information to our program, thereby enriching the user experience.
The input function allows us to provide a prompt to the user that they can respond to. The input function takes a single, string literal argument, which will be the prompt the user sees; this will typically be a question. You will get a return value from the function, whatever the user typed, in the form of a text literal (even if they enter numbers). You will typically store the return value in a variable.
Here is an example of using the input function to receive and store the user’s full name:
name = input(“Please enter your name: ”)
In the above example, the user will be presented with the prompt “Please enter your name: ” and provided with an input box to respond. When the user types their name and hits enter, their response will be stored as a string literal to the variable name. Thus, in our program, we can use the name variable anywhere below the input line, and Python will replace it with the users’ response.
When using the input function in Python, carefully consider the prompt you present to the user. The way you frame the question influences their response. Craft clear and explicit prompts and provide instructions, examples, and formatting guidelines to guide users. Anticipate ambiguities, address them in the prompt, and minimize unexpected or incorrect input. Thoughtful prompts improve reliability and accuracy. Remember, prompt clarity ensures user understanding and appropriate responses.
We should make two changes to our example to make it clearer since we want the user’s full name, and currently, future programmers and users would not know that and may answer “Jane” when we are looking for “Jane Doe”. First, we should update our variable from name to full_name or similar. Second, we should update our prompt to say “full name” explicitly.
user_full_name = input(“Please enter your full name: ”)
The above version is now much clearer to future programmers and program users.
Chapter Questions
Develop a program that asks the user for their favorite color using the input function. Then, use the print function to display a message incorporating their favorite color, such as “Your favorite color is blue. Mine is green!”
Write a program that prompts the user for their name, age, and favorite food using the input function. Store each response in separate variables and print a personalized message incorporating their inputs.
Chapter Solutions
Answer
user_fav_color = input(“What is your favorite color? ”)
print(“Your favorite color is”, user_fav_color, ”. Mine is green!”)
Revealed content has ended.
Answer
[Python] Mathematical Expressions, String Concatenation, and Data Type Conversions
Mathematical Expressions
In Python, mathematical operators are powerful tools that allow us to perform a wide range of computations. These operators enable us to manipulate numbers and variables, perform arithmetic operations, and solve mathematical equations. Understanding how to use these operators is essential for effectively expressing and executing mathematical calculations in Python.
Addition (+): The addition operator (+) adds two numbers. For example, the expression 2 + 3 evaluates to 5.
Subtraction (-): The subtraction operator (-) subtracts one number from another. For example, the expression 5 - 3 evaluates to 2.
Multiplication (*): The multiplication operator (*) multiplies two numbers. For example, the expression 2 * 3 evaluates to 6.
Division (/): The division operator (/) divides one number by another. It returns the quotient as a floating-point number. For example, the expression 10 / 3 evaluates to 3.3333333333333335.
Modulo (%): The modulo operator (%) returns the remainder of the division between two numbers. For example, the expression 10 % 3 evaluates to 1. This concept is often among the most confusing to students, so please play around in Google Colab to familiarize yourself with it.
Exponentiation (**): The exponentiation operator (**) is used to raise a number to a power (the number multiplied by itself power times). For example, the expression 2 ** 3 evaluates to 8.
Floor Division (//): The floor division operator (//) divides one number by another and returns the integer part of the quotient. It discards the decimal part of the result. For example, the expression 10 // 3 evaluates to 3.
You can combine any of these operations to create more complex calculations. For example, say we wanted to get the result of twenty plus four all divided by two. In Python, we can calculate this like so:
result = 20 + 4 / 2
print(result)
However, when you run this code, the result is 22.0. The result should have been 12.0.
It’s important to note that when performing calculations, Python follows the order of operations, commonly known as PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction). This means that expressions within parentheses are evaluated first, followed by exponentiation, multiplication, division, addition, and subtraction.
So, in the above example, Python did 4 / 2 first, resulting in 2, and then 20 + 2, resulting in 22.0. But, we wanted the addition to be processed first, so we needed to add parentheses to our equation to get the result we were looking for like so:
result = (20 + 4) / 2
print(result)
Which will result in 12.0, as we expected.
Generally, if you have more than one mathematical operator in the equation, use parentheses to control the order in which they are executed. This will guarantee success and avoid confusion, even if the equation would work without them.
It is always advisable to store the results of your calculations in a variable so you may reference the value later in your program without doing the calculation repeatedly, which could lead to errors. The other benefit of saving the result in a variable is that we can manipulate the result stored in it and overwrite the saved value. Consider the below example of manipulating the value stored in the variable x:
x = 5 # Initialize the variable x with a value of value 5
print(x) # Output the current value of x => 5
x = x + 5 # Get the current value of x, add 5 to it, and save it as x
print(x) # Output the current value of x => 10
String Concatenation
String concatenation is the process of combining multiple strings into a single string. It allows you to merge different strings to create a longer or more meaningful string. In Python, you can perform string concatenation using the + operator. It’s crucial to note that this operator is the same as our addition operator, so you must be careful with your data types to avoid errors. Both sides of the + operator must be the same data type, except for the case where you can mix integers and floating points.
When you use the + operator between two string literals, it joins them together in the order they appear. For example:
first_name = “Jane”
last_name = “Doe”
print(first_name + last_name) # Output: JaneDoe
In the above example, the variables first_name and last_name are concatenated using the + operator, resulting in the string “JaneDoe”. The two strings are merged without any space or separator between them. If we wanted it to be correctly spaced, we have three options:
Change “Jane” to “Jane ”,
Change “Doe” to “ Doe”,
Or concatenate a space string (“ ”) between “Jane” and “Doe”.
You can concatenate as many string literals together as you would like.
Data Type Conversions
When receiving user input in Python, it is important to note that the data is initially treated as a string by default. However, in many cases, it is necessary to convert the input into either an integer (int) or a floating-point number (float) to perform mathematical operations accurately. Thankfully, Python offers convenient built-in functions to facilitate this conversion process. When converting user input, it is crucial to select the appropriate data type based on the nature of the input. The integer data type is recommended if the input always consists of whole numbers without decimals. This is because Python (like most programming languages) handles integer arithmetic more efficiently than floating-point arithmetic. On the other hand, if the input may include decimal values, opting for the floating-point data type would be appropriate to ensure an accurate representation of the numbers. Making the right choice to ensure precision and consistency when performing mathematical computations with user-provided data is crucial.
You can use the int function to convert user input to an integer. This function takes a string as its argument and attempts to convert it into an integer. If successful, the int function returns the corresponding integer value. Here’s an example:
user_age = int(input(“How old are you? ”))
age_in_days = user_age * 365.25
print(age_in_days)
In this example, the input function prompts the user to enter an integer. The user’s input is then passed to the int function to convert it into an integer. The converted input is stored in the user_age variable that we can then use for mathematical calculations.
The float function can convert user input to a floating point number. Like the int function, the float function takes a string as its argument and tries converting it into a floating-point number. If the conversion is successful, the float function returns the corresponding floating-point value. Here’s an example:
user_loan_balance = float(input(“What is your current loan balance?”))
user_interest_rate = float(input(“What is your current interest rate in decimal form (5% is 0.05)?”))
loan_interest = user_loan_balance * user_interest_rate
print(loan_interest)
In this example, the input functions prompt the user to enter floating-point numbers. The user’s inputs are then passed to the float functions to convert them into floating-point numbers. The converted inputs are stored in the user_loan_balance and user_interest_rate variables that we can then use for mathematical calculations.

It’s important to note that if the user enters invalid input that cannot be converted to the desired numeric type, a ValueError will occur. To handle such cases, you can use exception-handling techniques, such as try-except blocks, to gracefully handle conversion errors and provide appropriate error messages to the user. However, this is beyond the scope of this course.
Concatenating string literals and numeric literals
Suppose we had the following program, which converts a user-inputted Fahrenheit measurement into Celcius. Ideally, the output would be “XX°F converts to XX°C.” The program has two output prints, but neither matches the ideal output.
fahrenheit_input = float(input(“Fahrenheit: ”))
celcius_output = (fahrenheit_input - 32) * (5 / 9)
print(fahrenheit_input, “°F converts to”, celcius_output, “°C”) # Output: XX °F converts to XX °C
print(fahrenheit_input + “°F converts to ” + celcius_output + “°C”) # TypeError: unsupported operand type(s) for +: ‘float’ and ‘str’
So, multiple arguments to the print function lead to unwanted spaces between the numbers and the units of measures, and the version using concatenation leads to a TypeError. We are receiving this error because string concatenation can only concatenate two strings, and the addition operator can only add two numbers. Thus, we must convert the string to a number or the number to a string. Since we are not trying to do numeric addition here, we want all components to be strings. Let us introduce the necessary built-in function.
Concatenating String Literals and Numeric Literals
In Python 3, the str function is a built-in function that converts various data types, such as numbers, into a string representation. It takes a single argument and returns the string literal representation. We do not recommend saving the result of this function and only using it within the print function when doing string concatenation. So, to fix our example, we can adjust the code to the following:
fahrenheit_input = float(input(“Fahrenheit: ”))
celcius_output = (fahrenheit_input - 32) * (5 / 9)
print(str(fahrenheit_input) + “°F converts to ” + str(celcius_output) + “°C”) # Output: XX°F converts to XX°C
We have now wrapped the numeric values with the str function to convert them to string literals so that the string concatenation will work.
Chapter Questions
You are designing a program to calculate the area of a trapezoid. Request the required inputs from the user and then implement the formula below. Remember PEMDAS. Display the result with appropriate context.
Design a program that asks the user for their current loan balance and the interest rate in decimal form (e.g., 5% as 0.05). Convert the user input to floating-point numbers and calculate the interest accrued on the loan using the formula loan_balance * interest_rate. Print the computed interest with an appropriate message.