4 Names and Variables
In programming, names and variables are fundamental concepts that form the building blocks of a program. They enable us to store, manipulate, and access data within our code, making it possible to write flexible and efficient programs. This chapter will delve into these essential concepts, exploring their significance and how they are used in Python.
4.1 Names
Names in programming are identifiers used to label and reference entities such as variables, functions, classes, and modules. They serve as a means to access stored data and functionality, making code more readable and maintainable. For instance, instead of repeatedly using a complex expression or value, we can assign it a name and refer to it using that name.
4.1.1 Rules for Naming
In Python, there are specific rules and conventions for naming identifiers:
- Alphabetic Characters and Underscores: Names must begin with a letter (a-z, A-Z) or an underscore (_), followed by letters, digits (0-9), or underscores.
- Case Sensitivity: Names are case-sensitive, meaning
Variable
,variable
, andVARIABLE
are distinct identifiers. - Reserved Keywords: Names cannot be Python reserved keywords, such as
if
,else
,for
,while
,class
,def
, etc.
4.2 Variables
Variables are names assigned to data values stored in memory. They act as containers holding information that can be manipulated and accessed throughout a program. Variables allow for dynamic and flexible data handling, making it possible to perform computations, store results, and manage state.
Variable Assignment
In Python, variable assignment is straightforward. Use the assignment operator (=
) to assign a value to a variable:
= 10
x = "Alice"
name = True is_student
Variable Scope
The scope of a variable determines its accessibility within different parts of a program. There are two primary types of scope in Python:
- Global Scope: Variables defined outside any function (functions will be discussed in sec-functions) or block have global scope and can be accessed anywhere in the program.
- Local Scope: Variables defined within a function or block have local scope and can only be accessed within that function or block.
= "I am global"
global_var
def my_function():
= "I am local"
local_var print(global_var) # Accessible
print(local_var) # Accessible
my_function()print(global_var) # Accessible
print(local_var) # Error: NameError
Constants
Constants are variables whose values are intended to remain unchanged throughout the program. While Python does not have built-in constant types, by convention, we use all uppercase letters to indicate constants:
= 3.14159
PI = 50 MAX_STUDENTS
4.2.1 Examples and Applications
To solidify our understanding of names and variables, let’s explore some practical examples and applications:
Example: Simple Calculator
# Simple Calculator Program
= 10
num1 = 5
num2
# Performing arithmetic operations
= num1 + num2
sum_result = num1 - num2
difference = num1 * num2
product = num1 / num2
quotient
print("Sum:", sum_result)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
Example: Temperature Conversion
# Temperature Conversion Program (Celsius to Fahrenheit)
= 25
celsius = (celsius * 9/5) + 32
fahrenheit
print(celsius, "Celsius is", fahrenheit, "Fahrenheit")
Understanding names and variables is crucial for effective programming. Names provide a way to reference and access data, while variables store the data we work with. By adhering to naming conventions and understanding variable scope and types, we can write clearer, more maintainable code. As we progress, these fundamental concepts will underpin more complex programming tasks and techniques.
4.3 Exercises
Exercise 1: Variable Assignment
- Assign the value
50
to a variable namedmy_age
and useprint
to display the variable. - Assign the string
"Hello, Python!"
to a variable namedgreeting
and useprint
to display the variable. - Assign the boolean value
False
to a variable namedis_raining
and useprint
to display the variable.
Exercise 2: Variable Reassignment
- Assign the value
10
to a variable namednumber
and useprint
to display the variable. - Reassign the value of
number
to20
and useprint
to display the variable. - Reassign the value of
number
to the string"twenty"
and useprint
to display the variable.
Exercise 3: Basic Arithmetic
- Create two variables
a
andb
, and assign them the values8
and3
respectively. - Perform the following operations and print the results:
- Sum of
a
andb
- Difference between
a
andb
- Product of
a
andb
- Quotient of
a
divided byb
- Sum of
Exercise 4: Temperature Conversion
- Create a variable
fahrenheit
and assign it the value86
. - Convert the temperature to Fahrenheit using the formula:
celsius = (fahrenheit - 32) * 5/9
. - Print the Celsius value.
Exercise 5: Constants
- Define a constant
PI
with the value3.14159
. - Define a constant
MAX_SPEED
with the value120
. - Print both constants.