Topics on Variables
Topics on Variables
Introduction to Formatting Value Display
String Interpolation
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 value or the name of the variable must be included between { and }. Also, the string must be preceded by f. Here is an example:
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 . . .
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. Sometimes, you want the value to be displayed with a fixed number of digits on the right side of the decimal separator. To control this, start by writing "f" on the right side of the colon in the string of print(). Here is an example:
a = 75.279418573
print(f"Number: {a:f}")
print("==================================================")
This would produce:
Number: 75.279419 ================================================== Press any key to continue . . .
The number on the right side of the decimal separator is called a precision. If you want to control the number of digits of precision, on the left side of "f", first type a period (.). Between that period and the "f", type the desired number. Here are examples:
a = 75.279418573 print(f"Number: {a:f}") print(f"Number: {a:.1f}") print(f"Number: {a:.3f}") print(f"Number: {a:.5f}") print(f"Number: {a:.7f}") print(f"Number: {a:.12f}") print(f"Number: {a:.15f}") print(f"Number: {a:.20f}") 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 . . .
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 . . .
Formating the Width of Data Display
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-2022, FunctionX | Monday 16 August 2021 | Next |
|