Introduction to Variables
Introduction to Variables
Fundamentals of Variables
Introduction
So far, when we needed a value, we wrote it in the parentheses of print(). Such a value is used only once. If you need that value, you must type it again, which could result in an error. As an alternative, you can use an area of the computer memory (the random-access memory or RAM) to store a value so that, whenever you need that value, you can simply get it from the memory area where the value is stored.
Practical Learning: Introducing Variables
print("=================================")
Declaring a Variable
To reserve an area of the computer memory, you must communicate your intention to the computer. This is referred to as declaring a variable.
The Name of a Variable
To declare a variable, in the Code Editor, type a name that will be used to refer to the reserved area of the computer memory. Here is an example:
price
There are various policies you can use to name your variables. You have many options:
There are restrictions:
There are suggestions also. For example, although the name of a variable can start with two underscores, avoid doing that (avoid starting the name of a variable with two underscores). Also avoid starting and ending the name of a variable with two underscores (because, as we will see later, the Python language includes many built-in variables that use names like that; this avoidance would reduce some confusion).
Practical Learning: Declaring Variables
first_name
last_name
print("=================================")
Keywords
A computer language has some words for its internal use. These words are called keywords. When naming your variables, you should (must) avoid using those words for your variables.
and | as | assert | async | await |
break | class | continue | def | del |
elif | else | except | False | finally |
for | from | global | if | import |
in | is | lambda | None | nonlocal |
not | or | pass | raise | return |
True | try | while | with | yield |
Initializing a Variable
A computer deals with various types of values. Each category of value uses a certain amount of memory. When you declare a variable, the computer wants to know how much memory would be necessary for a certain variable. To provide this information, assign the appropriate value to the variable. This primary assignment is referred to as initialization. This means that, when you declare a variable and assign a value to it, you are said to initialize the variable.
Practical Learning: Initializing Variables
# Variable: First Name first_name = "Peter" # Variable: First Name last_name = 'Naughton' print("=================================")
Python is an Inferred Language
When you declare a variable, you must initialize it. This is because, unlike many other computer languages (examples are C/C++, Pascal, etc) where you must specify a data type for the variable, in Python, you indicate the type of variable by the value you assign to it. It is when you initialize a variable that the compiler figures out what type that variable is. When a language behaves like that, that is when a language must "figure out" the type of a variable, that language is said to be an inferred language. Python is an inferred language (some languages also use this feature of inferred languages but they require that you use a certain keyword when you declare a variable, that required keyword doesn't specify the type of the variable; therefore, like in Python, you must initialize the variable so the compiler of that language would figure out (or infer) the type of that variable; examples of those languages are C++ that uses the auto keyword, Visual Basic that uses the Dim keyword, and C# that uses the var keyword, etc (JavaScript also uses the var keyword but, although JavaScript also is an inferred language, it doesn't require that you initialize its variables).
Primary Topics on String Variables
Introduction to Data Types
We have just seen that Python is an inferred language, which means the value you assign to a variable allows the compiler to know the type of that variable. Sometimes, when you declare a variable, you may not have a value for the variable. If you want, when declaring a variable, you can indicate its type. This is done by applying a certain keyword to the variable. The keyword you apply is called a data type. The formula to indicate the type of a variable is:
variable-name : data-type
When it comes to data types, there is a specific keyword for each. If you are declaring a variable for a string, the keyword to use is str. Here are examples:
first_name : str last_name : str
If you want to initialize the variable, you can assign the desired value after the data type.
Practical Learning: Indicating a Data Type
first_name : str = "Peter" last_name : str = "Naughton" print("=================================")
Introduction to Mutability and Immutability
The mutability of an object (consider some creatures such as larva, snake, etc) is the ability for that object to change its state (or appearance). The opposite is immutability, which is the inability for an existing object to change its state or situation.
In some areas in computer programming, once you create an object, you cannot change that object. In the world of Python programming, strings are immutable.
Introduction to Value Display
After declaring and initializing a variable, the most fundamental thing you can do with it is to display its value to the screen. To do this, you can include the name of the variable in the parentheses of print().
Practical Learning: Displaying Variables
first_name: str = "Peter"
last_name: str = 'Naughton'
print()
print(first_name)
print(last_name)
print("=================================")
Peter Naughton =================================
first_name: str = "Peter" last_name: str = 'Naughton' print("First Name:") print(first_name) print("Last Name:") print(last_name) print("=================================")
First Name: Peter Last Name: Naughton =================================
Adding Strings
You can combine one or more strings to get a new string that includes the other strings. This operation can be performed with the + operator.
Practical Learning: Adding Strings
first_name : str = "Peter"
last_name : str = 'Naughton'
fn = "First Name: " + first_name
ln = "Last Name: " + last_name
print()
print(fn)
print(ln)
print("=================================")
First Name: Peter Last Name: Naughton =================================
first_name : str = "Peter" last_name : str = 'Naughton' print("First Name: " + first_name) print("Last Name: " + last_name) print("=================================")
first_name : str = "Peter"
last_name : str = 'Naughton'
print()
print("Full Name: " + first_name + " " + last_name)
print("=================================")
Displaying One Value
As we have already seen, to display the value of a variable, you can pass the name of the variable to the print() function. Here are two examples:
name = "Gertrude Allen" number = 952 print("Full Name:") print(name) print("---------------") print("Number:") print(number) print("=================================")
This would produce:
Full Name: Gertrude Allen --------------- Number: 952 =================================
If you to display a string and a variable as a combination, in the parentheses of print(), type the string (in single or double-quotes), followed by a comma, and followed by the name of the variable.
Practical Learning: Displaying Values
first_name : str = "Peter" last_name : str = 'Naughton' print() print("First Name:", first_name) print("Last Name: ", last_name) print("=================================")
Displaying a Chain of Values
If you have a series of values you want to display, in the parentheses of print(), write each value but separate them with commas. Here is an example:
fname = "Gertrude"
mname = "Stéphanie"
lname = "Allen"
print()
print("Full Name: ", fname, mname, lname)
print("=================================")
This would produce:
Full Name: Gertrude Stéphanie Allen =================================
Practical Learning: Displaying Values
first_name : str = "Peter" mi = 'R' last_name : str = 'Naughton' print("Full Name:", first_name, mi, last_name) print("=================================")
Full Name: Peter R Naughton =================================
Requesting a Value from the User
So far, when we needed a value in an application, we provided that value. Application interactivity consists of letting a user provide a value and letting the computer deal with that value however necessary. To request a value from a user, you use input(). An example is:
input()
Normally, when you request a value from a user, it is because you want to involve that value in an operation. One way you do this is to first store the value produced by input() in a variable. To do that, you can assign input() to a variable. Here is an example:
first_name = input()
When you use input(), a pulsing caret would display in the window, but it doesn't tell the user anything. To let the user know what you are expecting, you can formulate a message and put it in the parentheses of input(). Here is an example:
first_name = input("Enter the Employee's Name:")
After using input() and assigning it to a variable, you can then use the variable as holding the value provided by the user.
Practical Learning: Requesting User Input
print("Watts' A Loan") print('===================================================') print('Enter the information about the loan applicant') fname = input("First Name: ") lname = input("Last Name: ") print("==================================================") print("Loan Applicant") print("----------------------") print("First Name:", fname) print("Last Name: ", lname) print("==================================================")
Watts' A Loan =================================================== Enter the information about the loan applicant First Name: Alexandra Last Name: Colson ================================================== Loan Applicant ---------------------- First Name: Alexandra Last Name: Colson ==================================================
print("Depreciation: Straight-Line Method") print("==============================================") mc = "6500" sv = "500" el = "5" print("Depreciation - Straight-Line Method") print("----------------------------------------------") print("Machine Cost: ", mc) print("Salvage Value: ", sv) print("Estimated Life: ", el, "Years") print("==============================================")
Depreciation: Straight-Line Method ============================================== Depreciation - Straight-Line Method ---------------------------------------------- Machine Cost: 6500 Salvage Value: 500 Estimate Life: 5 Years ==============================================
Introduction to Data Types
We have just seen that Python is an inferred language, which means the value you assign to the variable allows the compiler to know the type of that variable. Sometimes, when you declare a variable, you may not have a value for the variable. If you want, when declaring a variable, you can indicate its type. This is done by applying a certain keyword to the variable. The keyword you apply is called a data type. The formula to indicate the type of a variable is:
variable-name : data-type
When it comes to data types, there is a specific keyword for each. If you are declaring a variable for a string, the keyword to use is str. Here are examples:
student_name : str home_address : str
If you want to initialize the variable, you can assign the desired value after the data type. Here are examples:
student_name : str = "Rose Akumba" home_address : str ="8244 Granite Road print(student_name) print(home_address) print("=================================")
This would produce:
Rose Akumba 8244 Granite Road =================================
Variables for Natural Numbers
Introduction
In the previous lesson, we were introduced to numbers. You can declare a variable that holds a numeric value. Python supports integers. To use a variable that can hold natural numbers, declare a variable and assign a number with digits only. Here is an example:
a = 248
If the number is large, you can separate the thousands with underscores. Here are examples:
a = 248 b = 82_794 c = 5_795_749
An Integral Type
The data type that supports natural numbers is named int. When declaring a variable, if you want to indicate that the variable is for a natural number, apply this data type. Here are examples:
a : int = 248 b : int = 82_794 c : int = 5_795_749
Converting a Value to an Integer
By default, the primary values you get in an application are string. If you want to treat the value as an integral number, you must first convert the value from a string to an integer. To do this, write int(). In the parentheses, type the value you want to convert. You can then use that value. For example, you can assign that conversion to a variable. Here are examples:
print("Depreciation: Straight-Line Method") print("----------------------------------------------") mc = "6500" sv = "500" el = "5" machine_cost = int(mc) salvage_value = int(sv) estimated_life = int(el) print("==============================================") print("Depreciation - Straight-Line Method") print("----------------------------------------------") print("Machine Cost: ", machine_cost) print("Salvage Value: ", salvage_value) print("Estimated Life: ", estimated_life, "Years") print("==============================================")
This would produce:
Depreciation: Straight-Line Method ---------------------------------------------- ============================================== Depreciation - Straight-Line Method ---------------------------------------------- Machine Cost: 6500 Salvage Value: 500 Estimate Life: 5 Years ==============================================
Requesting a Value from a User
We have already seen that, to request a value from a user, you can use input(). We have already seen that, by default, input() produces a string value. Then, we saw that, to convert a value, you can put it into int().
Practical Learning: Converting and Requesting an Integral Value
estimated_life : int
machine_cost : int
salvage_value : int
print("Depreciation: Straight-Line Method")
print("----------------------------------------------")
print("Enter the values for the machine depreciation")
mc = input("Machine Cost: ")
sv = input("Salvage Value: ")
el = input("Estimated Life (in Years): ")
machine_cost = int(mc)
salvage_value = int(sv)
estimated_life = int(el)
print("==============================================")
print("Depreciation - Straight-Line Method")
print("----------------------------------------------")
print("Machine Cost: ", machine_cost)
print("Salvage Value: ", salvage_value)
print("Estimated Life: ", estimated_life, "Years")
print("==============================================")
Depreciation: Straight-Line Method ---------------------------------------------- Enter the values for the machine depreciation Machine Cost: 6500 Salvage Value: 500 Estimated Life (in Years): 5 ============================================== Depreciation - Straight-Line Method ---------------------------------------------- Machine Cost: 6500 Salvage Value: 500 Estimate Life: 5 Years ==============================================
estimated_life : int
machine_cost : int
salvage_value : int
print("Depreciation: Straight-Line Method")
print("----------------------------------------------")
print("Enter the values for the machine depreciation")
machine_cost = int(input("Machine Cost: "))
salvage_value = int(input("Salvage Value: "))
estimated_life = int(input("Estimated Life (in Years): "))
print("==============================================")
print("Depreciation - Straight-Line Method")
print("----------------------------------------------")
print("Machine Cost: ", machine_cost)
print("Salvage Value: ", salvage_value)
print("Estimated Life: ", estimated_life, "Years")
print("==============================================")
Depreciation: Straight-Line Method ---------------------------------------------- Enter the values for the machine depreciation Machine Cost: 6850 Salvage Value: 750 Estimated Life (in Years): 8 ============================================== Depreciation - Straight-Line Method ---------------------------------------------- Machine Cost: 6850 Salvage Value: 750 Estimate Life: 8 Years ==============================================
Operations on Natural Numbers
As seen in the previous lesson, Python supports all types of arithmetic operations, including the addition, the subtraction, and the multiplication. When it comes to the division, Python supports a special way to divide. When dividing numbers, by default, you get a decimal number. In some cases, you want the result of the division to be a natural number. In this case, to perform the division, use the // operator.
Practical Learning: Converting and Requesting an Integral Value
estimated_life : int machine_cost : int salvage_value : int print("Depreciation: Straight-Line Method") print("----------------------------------------------") print("Enter the values for the machine depreciation") machine_cost = int(input("Machine Cost: ")) salvage_value = int(input("Salvage Value: ")) estimated_life = int(input("Estimated Life (in Years): ")) depreciatiable_amount = machine_cost - salvage_value; depreciation_rate = 100 // estimated_life yearly_depreciation = depreciatiable_amount // estimated_life print("==============================================") print("Depreciation - Straight-Line Method") print("----------------------------------------------") print("Machine Cost: ", machine_cost) print("Salvage Value: ", salvage_value) print("Estimated Life: ", estimated_life, "Years") print("Depreciation Rate: ", depreciation_rate, "%") print("----------------------------------------------") print("Depreciable Amount: ", depreciatiable_amount) print("Yearly Depreciation: ", yearly_depreciation) print("==============================================")
Depreciation: Straight-Line Method ---------------------------------------------- Enter the values for the machine depreciation Machine Cost: 6500 Salvage Value: 500 Estimated Life (in Years): 5 ============================================== Depreciation - Straight-Line Method ---------------------------------------------- Machine Cost: 6500 Salvage Value: 500 Estimate Life: 5 Years Depreciation Rate: 20 % ---------------------------------------------- Depreciable Amount: 6000 Yearly Depreciation: 1200 ==============================================
full_name = "" first_name: str last_name : str print("FUN DEPARTMENT STORE") print("==============================================") first_name = "Roberta" last_name = "Jenkins" full_name = first_name + " " + last_name print("Payroll Evaluation") print("==============================================") print("Employee Information") print("----------------------------------------------") print("Full Name: ", full_name) print("==============================================")
Variables for Decimal Numbers
Introduction
A floating-point number is a number that displays either as a natural number or with a decimal part. To store such a value in the computer memory, declare a variable and assign a decimal number to it. You can then use the variable normally. For example, you can involve it in any arithmetic operation. You can also display the value using any of the techniques we have used so far.
Practical Learning: Introducing Decimal Variables
full_name = "" first_name: str last_name : str print("FUN DEPARTMENT STORE") print("==============================================") first_name = "Roberta" last_name = "Jenkins" h_sal = 19.47 mon = 9 tue = 8.5 wed = 7.5 thu = 10 fri = 8.5 full_name = first_name + " " + last_name time_worked = mon + tue + wed + thu + fri net_pay = h_sal * time_worked print("Payroll Evaluation") print("==============================================") print("Employee Information") print("----------------------------------------------") print("Full Name: ", full_name) print("Hourly Salary: ", h_sal) print("==============================================") print("Time Worked") print("----------------------------------------------") print("Monday: ", mon) print("Tuesday: ", tue) print("Wednesday: ", wed) print("Thursday: ", thu) print("Friday: ", fri) print("----------------------------------------------") print("Total Time: ", time_worked) print("Net Pay: ", net_pay) print("==============================================")
FUN DEPARTMENT STORE ============================================== Payroll Evaluation ============================================== Employee Information ---------------------------------------------- Full Name: Roberta Jenkins Hourly Salary: 19.47 ============================================== Time Worked ---------------------------------------------- Monday: 9 Tuesday: 8.5 Wednesday: 7.5 Thursday: 10 Friday: 8.5 ---------------------------------------------- Total Time: 43.5 Net Pay: 846.9449999999999 ==============================================
A Floating Type
Decimal numbers are supported with a data type named float. When you declare a variable, you may not have a value for the variable. When declaring a variable that would hold a decimal number, if you want, you can apply that data type. Here are examples:
full_name : str h_sal : float time_worked : float net_pay : float
Converting a Value to Float
Remember that, by default, values are given to you as strings. If you have such a value and need to involve it in a calculation, you must first convert it. To do this, type float(). In the parentheses, write the value or the name of a variable that must be converted.
Also remember that, if you request a value from a user using input, that value is typically a string. If you want to treat the value as a decimal number, you must first convert it. To do this, type float() and, in the parentheses, type the value to be converted.
Practical Learning: Converting a Value to Float
full_name = "" first_name: str last_name : str mon : float tue : float wed : float thu : float fri : float h_sal : float time_worked : float net_pay : 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: ")) full_name = first_name + " " + last_name 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("Full Name: ", full_name) print("Hourly Salary: ", h_sal) print("==============================================") print("Time Worked") print("----------------------------------------------") print("Monday: ", mon) print("Tuesday: ", tue) print("Wednesday: ", wed) print("Thursday: ", thu) print("Friday: ", fri) print("----------------------------------------------") print("Total Time: ", time_worked) print("Net Pay: ", net_pay) print("=============================================="): float
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 ==============================================
|
|||
Previous | Copyright © 2021-2024, FunctionX | Monday 29 July 2024, 12:46 | Next |
|