Topics on Variables
Topics on Variables
String Interpolation
Introduction
We have already seen that, to display a value on the computer screen, you can write the value or its variable in the parentheses of print(). Here are examples:
firstName = 'Robert Ellis'
hourlySalary = 28.93
print(firstName)
print(hourlySalary)
print("=============")
This would produce:
Robert Ellis 28.93 ============= Press any key to continue . . .
We already know that you can create a string and include it in the parentheses of print(). Here is an example:
print("Welcome to Python programming.")
As one way to display a value or a variable, you can include it in the string used in the parentheses of print(). The string must be preceded by F or f. The value or the name of the variable in the string must be included between { and }. Here are examples:
name = "Gertrude Allen" number = 952 print(f"Full Name: {name}") print(f"Number: {number}") print("=================================")
This technique is referred to as string interpolation. The {} combination is referred to as a placeholder. If you have many values to display, you can create as many placeholders as you want and include the desired variable in each.
Practical Learning: Introducing Variables
full_name : str h_sal : float time_worked : float net_pay : float first_name: str last_name : str mon : float tue : float wed : float thu : float fri : float print("FUN DEPARTMENT STORE") print("==============================================") print("Payroll Preparation") print("----------------------------------------------") print("Enter the following pieces of information") print("----------------------------------------------") print("Employee Information") first_name = input("First Name: ") last_name = input("Last Name: ") h_sal = float(input("Hourly Salary: ")) print("----------------------------------------------") print("Timed worked") mon = float(input("Monday: ")) tue = float(input("Tuesday: ")) wed = float(input("Wednesday: ")) thu = float(input("Thursday: ")) fri = float(input("Friday: ")) time_worked = mon + tue + wed + thu + fri net_pay = h_sal * time_worked print("==============================================") print("FUN DEPARTMENT STORE") print("==============================================") print("Payroll Evaluation") print("==============================================") print("Employee Information") print("----------------------------------------------") print(f"Full Name: {first_name} {last_name}") print(f"Hourly Salary: {h_sal}") print("==============================================") print("Time Worked") print("----------------------------------------------") print(f"Monday: {mon}") print(f"Tuesday: {tue}") print(f"Wednesday: {wed}") print(f"Thursday: {thu}") print(f"Friday: {fri}") print("----------------------------------------------") print(f"Total Time: {time_worked}") print(f"Net Pay: {net_pay}") print("==============================================")
First Name: | Roberta |
Last Name: | Jenkins |
Hourly Salary: | 19.47 |
Monday: | 9 |
Tuesday: | 8.5 |
Wednesday: | 7.5 |
Thursday: | 10 |
Friday: | 8.5 |
FUN DEPARTMENT STORE ============================================== Payroll Preparation ---------------------------------------------- Enter the following pieces of information ---------------------------------------------- Employee Information First Name: Roberta Last Name: Jenkins Hourly Salary: 19.47 ---------------------------------------------- Timed worked Monday: 9 Tuesday: 8.5 Wednesday: 7.5 Thursday: 10 Friday: 8.5 ============================================== FUN DEPARTMENT STORE ============================================== Payroll Evaluation ============================================== Employee Information ---------------------------------------------- Full Name: Roberta Jenkins Hourly Salary: 19.47 ============================================== Time Worked ---------------------------------------------- Monday: 9.0 Tuesday: 8.5 Wednesday: 7.5 Thursday: 10.0 Friday: 8.5 ---------------------------------------------- Total Time: 43.5 Net Pay: 846.9449999999999 ============================================== Press any key to continue . . .
The Width to Display a Value
Sometimes, when displaying a numeric value, you may want to control how the number appears. You have many options. One way to control how a number displays is through string interpolation. In that string, after the value or the name of the variable, first type a colon (:). If you want to specify the number of places for the number, type a positive number. Here are examples:
a = 7507 print(f"Number: {a:5}") print(f"Number: {a:10}") print(f"Number: {a:15}") print(f"Number: {a:20}") print("==================================================")
This would produce:
Number: 7507 Number: 7507 Number: 7507 Number: 7507 ================================================== Press any key to continue . . .
Displaying a String
Introduction
In the previous lesson and previous sections, we saw various ways to display values and all those values were treated as strings. We saw that, to display a string, you can type the string directly in the parentheses of print(). An alternative is to type the name of a striing variable in the parentheses of print().
Introduction to Formatting a String
One way to display a value in the computer screen is to treat that value as a string. The formula to display such a value is:
print("...%s..." % value-or-variable)
Start by writing print(). In the parentheses, create two double-quotes. Inside the quotes, type %s. On both sides of %s, you can write anything you want. After the second quote, type % followed by the value or the variable that holds the value you want to display. Here are examples:
firstName = 'Robert Ellis' hourlySalary = 28.93 print("First Name: %s" % firstName) print("Hourly Salary: %s" % hourlySalary) print("============================")
This would produce:
First Name: Robert Ellis Hourly Salary: 28.93 ============================ Press any key to continue . . .
Interpolating a String
As we saw already, another way to display a string is by using interpolation. To do this, start a print() string with f or F. In the double-quote of print(), type the name of the string variable surrounded by { and }. We also saw that you can provide a number for the amount of space you want to use for the string.
Introduction to Formatting an Integer Display
One of the types of values you usually use in an application is a natural number, which is also referred to as a round number. The formula to display such a value is:
print("...%i..." % value-or-variable)
print("...%d..." % value-or-variable)
Start with print(""). In the double-quotes. Inside the quotes, type %i or %d (both have the same effect). On both sides of %i or %d, you can write anything you want. After the second quote, type % followed by the value or the integral variable. Here are examples:
age = 28 distance = 449 unit = 93_784 print("Age:%d" % age) print("Displance:%i" % distance) print("Number:%d" % unit) print("===============================")
This would produce:
Age:28 Displance:449 Number:93784 =============================== Press any key to continue . . .
The Width to Display a Formatted Integer
When displaying an integral variable, you can specify the ammount of space that will be allocated to the value. to do that, after the % symbol, enter a (positive) number. Here are examples:
age = 28 distance = 449 unit = 93_784 print("Age:%d" % age) print("Age:%5d" % age) print("------------------------------") print("Displance:%i" % distance) print("Displance: %10i" % distance) print("------------------------------") print("Number: %d" % unit) print("Number: %20d" % unit) print("===============================")
This would produce:
Age:28 Age: 28 ------------------------------ Displance:449 Displance: 449 ------------------------------ Number: 93784 Number: 93784 =============================== Press any key to continue . . .
String Interpolation
As seen already, string interpolation allows you to use the name of a variable directly in the double-quotes of print(""). The operation is also valid for a variable that holds a natural number. Here are examples:
age = 28 distance = 449 unit = 93_784 print(f"Age:{age}") print(F"distance:{distance}") print(f"Number:{unit}")
This would produce:
Age:28 Displance:449 Number:93784 =============================== Press any key to continue . . .
If you want, you may want a certain amount of space to be used when displaying a number. To do this, as we saw already, in the {} placeholder, after the name of the variable, type a colon and the desired number. Here are examples:
age = 28 distance = 449 unit = 93_784 print(f"Age:{age}") print(F"Age:{age:10}") print("-------------------------------") print(F"Distance:{distance}") print(F"Distance:{distance:10}") print("-------------------------------") print(f"Number:{unit}") print(F"Number:{unit:10}") print("===============================")
This would produce:
Age:28 Displance:449 Number:93784 =============================== Press any key to continue . . .
Displaying a Decimal Value
As seen so far, you can display on the screen by treating that value as a string. If the value you want to display is a decimal number stored in a variable, in the double quotes of print(""), use %f. After the double-quotes, type % followed by the name of the variable. Here are examples:
ruthenium = 101.07 hydrogen = 1.008 beryllium = 9.0122 print("Ruthenium:%f" % ruthenium) print("Hydrogen:%f" % hydrogen) print("Beryllium:%f" % beryllium) print("===============================")
This would produce:
Ruthenium:101.070000 Hydrogen:1.008000 Beryllium:9.012200 =============================== Press any key to continue . . .
The Width to Display a Formatted Number
You can indicate the amount of space that should be used to display the variable of a decimal number. To do this, in the double-quotes, between the % synbol and f or F, type a (positive integer). Here are examples:
ruthenium = 101.07 hydrogen = 1.008 beryllium = 9.0122 print("Ruthenium:%12f" % ruthenium) print("Hydrogen:%13f" % hydrogen) print("Beryllium:%12f" % beryllium) print("===============================")
This would produce:
Ruthenium: 101.070000 Hydrogen: 1.008000 Beryllium: 9.012200 =============================== Press any key to continue . . .
String Interpolation
You can use string interpolation to include the name of a variable directly in the double-quotes of print(""). Here are examples:
ruthenium = 101.07 hydrogen = 1.008 beryllium = 9.0122 print(f"Ruthenium:{ruthenium}") print(F"Hydrogen:{hydrogen}") print(f"Beryllium:{beryllium}") print("===============================")
This would produce:
Ruthenium:101.07 Hydrogen:1.008 Beryllium:9.0122 =============================== Press any key to continue . . .
If you want to use a certain amount of space to display the decimal number, between the name of the variable and }, type a colon and a number. Here are examples:
ruthenium = 101.07 hydrogen = 1.008 beryllium = 9.0122 print(f"Ruthenium:{ruthenium:8}") print(F"Hydrogen:{hydrogen:10}") print(F"Beryllium:{beryllium:10}") print("===============================")
This would produce:
Ruthenium: 101.07 Hydrogen: 1.008 Beryllium: 9.0122 =============================== Press any key to continue . . .
The Precision of a Decimal Number
If you provide a decimal value to print(), the compiler would display that value "as is". If the value is coming from a calculation, print() would display the number as large as possible. Consider the following examples:
height = 373.9727 width = 1557.4268 area = width * height print("Displaying by Formatting") print("-------------------------------") print("Width: %f" % width) print("Height: %f" % height) print("Area: %f" % area) print("===============================") print("String Interpolation") print("-------------------------------") print(f"Width: {width}") print(F"Height: {height}") print(F"Area: {area}") print("==================================================")
This would produce:
Displaying by Formatting ------------------------------- Width: 1557.426800 Height: 373.972700 Area: 582435.105448 =============================== String Interpolation ------------------------------- Width: 1557.4268 Height: 373.9727 Area: 582435.10544836 =============================== Press any key to continue . . .
Sometimes, you want the value to be displayed with a fixed number of digits on the right side of the decimal separator. To take care of this, if you are using string formatting, inside the double-quotes of print(""), between the % symbol and f or F, type a decimal number. You can use 0. followed by the number of digits you want. Here are examples:
number = 75.279418573 print("Number: %f" % number) print("Number: %0.1f" % number) print("Number: %0.3f" % number) print("Number: %0.5f" % number) print("Number: %0.7f" % number) print("Number: %0.12f" % number) print("Number: %0.15f" % number) print("Number: %0.20f" % number) print("=================================")
This would produce:
Number: 75.279419 Number: 75.3 Number: 75.279 Number: 75.27942 Number: 75.2794186 Number: 75.279418573000 Number: 75.279418573000001 Number: 75.27941857300000094710 ================================================== Press any key to continue . . .
If you are using the string interpolation technique, in the {} placeholder, between the colon and f or F, type a decimal value. Here are examples:
number = 75.279418573 print(f"Number: {number:f}") print(f"Number: {number:0.1f}") print(f"Number: {number:0.3f}") print(f"Number: {number:0.5f}") print(f"Number: {number:0.7f}") print(f"Number: {number:0.12f}") print(f"Number: {number:0.15f}") print(f"Number: {number:0.20f}") print("==================================================")
Practical Learning: Setting the Precision of a Number
. . . print("==============================================") print("FUN DEPARTMENT STORE") print("==============================================") print("Payroll Evaluation") print("==============================================") print("Employee Information") print("----------------------------------------------") print(f"Full Name: {first_name} {last_name}") print(f"Hourly Salary: {h_sal:.2f}") print("==============================================") print("Time Worked") print("----------------------------------------------") print(f"Monday: {mon:.2f}") print(f"Tuesday: {tue:.2f}") print(f"Wednesday: {wed:.2f}") print(f"Thursday: {thu:.2f}") print(f"Friday: {fri:.2f}") print("----------------------------------------------") print(f"Total Time: {time_worked:.2f}") print(f"Net Pay: {net_pay:.2f}") print("==============================================")
FUN DEPARTMENT STORE ============================================== Payroll Preparation ---------------------------------------------- Enter the following pieces of information ---------------------------------------------- Employee Information First Name: Roberta Last Name: Jenkins Hourly Salary: 19.47 ---------------------------------------------- Timed worked Monday: 9 Tuesday: 8.5 Wednesday: 7.5 Thursday: 10 Friday: 8.5 ============================================== FUN DEPARTMENT STORE ============================================== Payroll Evaluation ============================================== Employee Information ---------------------------------------------- Full Name: Roberta Jenkins Hourly Salary: 19.47 ============================================== Time Worked ---------------------------------------------- Monday: 9.00 Tuesday: 8.50 Wednesday: 7.50 Thursday: 10.00 Friday: 8.50 ---------------------------------------------- Total Time: 43.50 Net Pay: 846.94 ============================================== Press any key to continue . . .
The Width to Display Data
You can combine the width feature and precision format to control the width and alignment of a value to display. To do that, after the colon, type the desired width value followed by the format for the precision side.
Practical Learning: Formating the Width of Data Display
. . . print("==============================================") print("FUN DEPARTMENT STORE") print("==============================================") print("Payroll Evaluation") print("==============================================") print("Employee Information") print("----------------------------------------------") print(f"Full Name: {first_name} {last_name}") print(f"Hourly Salary: {h_sal:5.2f}") print("==============================================") print("Time Worked") print("----------------------------------------------") print(f"Monday: {mon:5.2f}") print(f"Tuesday: {tue:5.2f}") print(f"Wednesday: {wed:5.2f}") print(f"Thursday: {thu:5.2f}") print(f"Friday: {fri:5.2f}") print("----------------------------------------------") print(f"Total Time: {time_worked:5.2f}") print(f"Net Pay: {net_pay:6.2f}") print("==============================================")
FUN DEPARTMENT STORE ============================================== Payroll Preparation ---------------------------------------------- Enter the following pieces of information ---------------------------------------------- Employee Information First Name: Roberta Last Name: Jenkins Hourly Salary: 19.47 ---------------------------------------------- Timed worked Monday: 9 Tuesday: 8.5 Wednesday: 7.5 Thursday: 10 Friday: 8.5 ============================================== FUN DEPARTMENT STORE ============================================== Payroll Evaluation ============================================== Employee Information ---------------------------------------------- Full Name: Roberta Jenkins Hourly Salary: 19.47 ============================================== Time Worked ---------------------------------------------- Monday: 9.00 Tuesday: 8.50 Wednesday: 7.50 Thursday: 10.00 Friday: 8.50 ---------------------------------------------- Total Time: 43.50 Net Pay: 846.94 ============================================== Press any key to continue . . .
Topics on Variables
Declaring Variables in a Series
A typical application uses many variables. You can declare each variable on its own line. Here are examples:
salary = 22.38 time = 39.50 fname = "Patrick" middle = 'J' lname = "Forester" print("First Name:") print(fname) print('---------------------------------') print("Middle Initial:") print(middle) print('---------------------------------') print("Last Name:") print(lname) print('---------------------------------') print("Hourly Salary:") print(salary) print('---------------------------------') print("Time Worked:") print(time) print('=================================')
This would produce:
First Name: Patrick --------------------------------- Middle Initial: J --------------------------------- Last Name: Forester --------------------------------- Hourly Salary: 22.38 --------------------------------- Time Worked: 39.5 ================================= Press any key to continue . . .
As an alternative, you can declare many variables on the same line. To do this, write the names of variables, separating them with commas. This is followed by the assignment operator (=), followed by a list of the values of the variables. The values must be separated by commas. The order of the values must be those of the variables. Here are two examples:
salary, time = 22.38, 39.50 fname, middle, lname = "Patrick", 'J', "Forester"
The variables you declare in a series don't have to be same type. The only rule is that, when you initialize the group, you should make sure that the values follow the order of the variables. Here is an example:
fname, salary, lname, time = "Patrick", 22.38, "Forester", 39.50
middle = 'J'
Declaring a Variable When You Need it
It is a common habit to declare variables in the top section of a document. Here are examples:
type_of_car = "Car: Sedan" ship_style = "Ship: Canoe" bike_type = "Cycle-Based Vehicle: Bicycle" print(type_of_car) print("------------") print("A sedan is a style of regular car with four doors and a trunk. The trunk has its own door.") print("-------------------------------------------------------------------------------------------") print(ship_style) print("------------") print("A canoe is a type of water vehicle with two narrow sides, to the front and the back, while the middle section is larger.") print("-------------------------------------------------------------------------------------------") print(bike_type) print("------------------------------") print("A bicycle is a vehicle with two wheels. A human being operates on such a vehicle to make it start, advance, and stop.") print("====================================================================================================")
Notice that some variables are used for the first time far from where they are declared. Instead of declaring all variables in the top section of the document, it is suggested that you declare a variable only where you start using it. This makes the program easier to read.
Practical Learning: Declaring Variables You Need
print("FUN DEPARTMENT STORE") print("==============================================") print("Payroll Preparation") print("----------------------------------------------") print("Enter the following pieces of information") print("----------------------------------------------") print("Employee Information") first_name : str= input("First Name: ") last_name : str = input("Last Name: ") h_sal : float = float(input("Hourly Salary: ")) print("----------------------------------------------") print("Timed worked") mon : float = float(input("Monday: ")) tue : float = float(input("Tuesday: ")) wed : float = float(input("Wednesday: ")) thu : float = float(input("Thursday: ")) fri : float = float(input("Friday: ")) time_worked : float = mon + tue + wed + thu + fri net_pay : float = h_sal * time_worked print("==============================================") print("FUN DEPARTMENT STORE") print("==============================================") print("Payroll Evaluation") print("==============================================") print("Employee Information") print("----------------------------------------------") print(f"Full Name: {first_name} {last_name}") print(f"Hourly Salary: {h_sal:5.2f}") print("==============================================") print("Time Worked") print("----------------------------------------------") print(f"Monday: {mon:5.2f}") print(f"Tuesday: {tue:5.2f}") print(f"Wednesday: {wed:5.2f}") print(f"Thursday: {thu:5.2f}") print(f"Friday: {fri:5.2f}") print("----------------------------------------------") print(f"Total Time: {time_worked:5.2f}") print(f"Net Pay: {net_pay:6.2f}") print("==============================================")
print("FUN DEPARTMENT STORE")
print("=======================================================")
print("Payroll Preparation")
print("-------------------------------------------------------")
print("Enter the following pieces of information")
print("-------------------------------------------------------")
print("Employee Information")
first_name : str= input("First Name: ")
last_name : str = input("Last Name: ")
h_sal : float = float(input("Hourly Salary: "))
print("-------------------------------------------------------")
print("Timed worked")
print("-------------------------------------------------------")
mon : float = float(input("Monday: "))
tue : float = float(input("Tuesday: "))
wed : float = float(input("Wednesday: "))
thu : float = float(input("Thursday: "))
fri : float = float(input("Friday: "))
time_worked : float = mon + tue + wed + thu + fri
net_pay : float = h_sal * time_worked
print("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+")
print("FUN DEPARTMENT STORE")
print("=======================================================")
print("Payroll Evaluation")
print("=======================================================")
print("Employee Information")
print("-------------------------------------------------------")
print(f"Full Name: {first_name} {last_name}")
print(f"Hourly Salary: {h_sal:5.2f}")
print("=======================================================")
print("Work Preparation")
print('--------+---------+-----------+----------+-------------')
print(" Monday | Tuesday | Wednesday | Thursday | Friday")
print('--------+---------+-----------+----------+-------------')
print(f" {mon:5.2f}{tue:8.2f}{wed:12.2f}{thu:12.2f}{fri:10.2f}")
print("=======================================================")
print("\t\t\tPay Summary")
print("-------------------------------------------------------")
print(f"\t\t\tTotal Time:\t{time_worked:5.2f}")
print(f"\t\t\tNet Pay: \t{net_pay:6.2f}")
print("=======================================================")
First Name: | Henry |
Last Name: | Fadden |
Hourly Salary: | 22.26 |
Monday: | 8 |
Tuesday: | 6.5 |
Wednesday: | 7 |
Thursday: | 8.5 |
Friday: | 6.5 |
FUN DEPARTMENT STORE ======================================================= Payroll Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Employee Information First Name: Henry Last Name: Fadden Hourly Salary: 22.26 ------------------------------------------------------- Timed worked ------------------------------------------------------- Monday: 8 Tuesday: 6.5 Wednesday: 7 Thursday: 8.5 Friday: 6.5 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Payroll Evaluation ======================================================= Employee Information ------------------------------------------------------- Full Name: Henry Fadden Hourly Salary: 22.26 ======================================================= Work Preparation --------+---------+-----------+----------+------------- Monday | Tuesday | Wednesday | Thursday | Friday --------+---------+-----------+----------+------------- 8.00 6.50 7.00 8.50 6.50 ======================================================= Pay Summary ------------------------------------------------------- Total Time: 36.50 Net Pay: 812.49 ======================================================= Press any key to continue . . .
Updating a Variable
Sometimes, you want to change the value that a variable is currently holding. To do that, simply assign the new value to the variable. This is referred to as updating a variable. Here are examples:
type_of_vehicle = "Car: Sedan" print(type_of_vehicle) print("------------") print("A sedan is a style of regular car with four doors and a trunk. The trunk has its own door.") print("-------------------------------------------------------------------------------------------") type_of_vehicle = "Ship: Canoe" print(type_of_vehicle) print("------------") print("A canoe is a type of water vehicle with two narrow sides, to the front and the back, while the middle section is larger.") print("-------------------------------------------------------------------------------------------") type_of_vehicle = "Cycle-Based Vehicle: Bicycle" print(type_of_vehicle) print("------------------------------") print("A bicycle is a vehicle with two wheels. A human being operates on such a vehicle to make it start, advance, and stop.") print("====================================================================================================")
Assigning a Common Value to Variables
Sometimes you want various variables to hold the same value. To make this happen, you can simply assign the same value to the variables. Here are examples:
item_name = "Premium No Iron Khaki" sale_price = 45 waist = 40 length = 34 print("Fun Department Store") print("-----------------------") print("Item Name:") print(item_name) print("Sale Price:") print(sale_price) print("Waist:") print(waist) print("Length:") print(length) print("=========================================") item_name = "Cool Right® Performance Flex Pant" sale_price = 65 waist = 32 length = 32 print("Fun Department Store") print("-----------------------") print("Item Name:") print(item_name) print("Sale Price:") print(sale_price) print("Waist:") print(waist) print("Length:") print(length) print("------------------------------------------") item_name = "The Active Series™ Tech Pant" sale_price = waist = length = 34 print("Fun Department Store") print("-----------------------") print("Item Name:") print(item_name) print("Sale Price:") print(sale_price) print("Waist:") print(waist) print("Length:") print(length) print("====================================================================================================")
This would produce:
Fun Department Store ----------------------- Item Name: Premium No Iron Khaki Sale Price: 45 Waist: 40 Length: 34 ========================================= Fun Department Store ----------------------- Item Name: Cool Right® Performance Flex Pant Sale Price: 65 Waist: 32 Length: 32 ------------------------------------------ Fun Department Store ----------------------- Item Name: The Active Series™ Tech Pant Sale Price: 34 Waist: 34 Length: 34 ==================================================================================================== Press any key to continue . . .
As an alternative, you can type the names of variable, put = between them, and assign the common value to the last variable in the section.
Practical Learning: Ending the Leson
|
|||
Previous | Copyright © 2021-2024, FunctionX | Monday 16 August 2021 | Next |
|