In Python programming, a variable can be viewed as a named location in memory used to hold a value (Storage Location). It is like a label for a specific piece of data. Unlike other programming languages, Python does not require the explicit declaration of variable data types. The interpreter automatically assigns the type based on the value you assign to it. This process is known as dynamic typing.
Naming Conventions
Python follows a naming convention that requires that a variable name:
- Be case-sensitive. For example, variable_1 is different from Variable_1.
- Use only letters, numbers, or underscores. Special characters ( #, !, @, etc.), are not allowed.
- Use snake_case (Use of lowercase letters and separate words with underscores (e.g., my_variable).
- A variable name cannot begin with a number.
- Use descriptive names.
How to Assign Values to Variables
Use the assignment operator (=).
For;
- Integer, use age = 75
- String, use name = "Aggrey"
- Float, use pi = 3.14
To assign the same value to multiple variables in a single line, use
a = b = c = 60
Re-assignment of Variable Value
Once a variable is created, it takes on the last value it is assigned.
age = 50
print(age)
We now reassign
age = 75
print(age) # Output: the latest age assigned
In addition, the variable can take on a value related to the previous value. For example, it can take on a value 1 more than the previous.
count = 10
count = count + 1 # The new value of count is 10+1 = 11
This can alternatively be done using augmented assignment operators such as +=, -=, *=, and /=, as follows;
count = 10
count += 1
print(count) # Output should yield 11
Variable scope refers to the region of a code where a variable is accessible. There are two main types of scope: Global variables defined and accessed from outside a function and Local variables defined and accessed only within a function.
Example
Creating the variable outside the function
x = "At FAST BlocK"
def myfunc():
print("Our first Python script was at" + x)
myfunc()
Creating the variable within the function
x = "At FAST BlocK"
def myfunc():
x = "At FCI BlocK"
print("Our first Python script was at" + x)
myfunc()
print("Our first Python script was at" + x)
Therefore, to make the locally defined variable global, use the keyword “global” as follows;
x = "At FAST BlocK"
def myfunc():
global x
def myfunc():
x = "At FCI BlocK"
print("Our first Python script was at" + x)
myfunc()
print("Python is " + x)
DATA TYPES
In Python, every piece of data is referred to as an object. Each of these pieces of information or data determines how Python stores it and what type of operations can be performed on it. For example, a square root will not be performed on a string data type.
Primarily, Python data types can be categorized as primitive and advanced data types.
Primitive (Fundamental) Data Types
These are the most basic building blocks of data. They include;
1. Numeric Types: Used to represent numerical values.
o Integer (
o Floats: Numbers containing a decimal point (e.g., 3.00, -4.22).
2. Boolean (
o Represents only two values: True or False or 0 and 1
3. String (
o They are defined using single quotes ('Peter') or double quotes ("Uganda").
Advanced Data Types
These are collections or structures designed to hold multiple items often of different types, together. They are used when dealing with complex data.
1. List: An ordered, changeable collection that allows duplicate members. Lists are defined using square brackets []. A List allows for the addition, removal, and reordering of items.
Example:
A list of colors
Colors = ['red', 'green', 'blue']
2. Tuple: A tuple is an ordered, unchangeable (immutable) collection of characters that allows duplicates. Tuples are defined using parentheses (). Note that tuples cannot be changed once set.
Example:
Coordinate = (10, 20)
3. Dictionary: A dictionary is an unordered collection that stores data in key: value pairs. The respective keys are unique and are used to locate only their corresponding value. Dictionaries are defined using curly braces {}.
Example
An employee experience book where the name (key) points to the age (value).
employee_experience_record = {'name': 'Peter', 'experience': 20}
Converting Data Type
The input() function in Python is meant to facilitate interaction between a program and the user by allowing the program to receive data entered by the user. It prompts the User: It can display a message (the prompt) to the user, guiding them on what kind of input is expected. This prompt is passed as an argument to the input() function.
However, by default, the input() function always reads data as a String. One may therefore want to convert the string read by the function to another data type. Use Type Casting to convert strings into a numeric type (like int or
Conversion Purpose Example Answer
int(value) Converts to Integer int("15") 15Error! Filename not specified.
str(value) Converts to String str(4.15) "4.15"
float(value) Converts to Float float("40") 40.0
Activity
1. Your first Python program is intended to store a list of 10 students in a class. The list may require modifications later to accommodate student scores in a Python programming end-of-term examination. Which Python data type will be the most suitable for this task?
a) Dictionaryb) Int
c) Tuple
d) List
Hint: Mutability
2. Which of the following variable names are valid identifiers in Python?
a) student_names
b) _student_names
c) student_names_1
d) 1st_student_name
Hint: Naming of variables
3. What is the data type of the variable `is_active` after running the following code?
x = 10
y = 500
score = (x > y)
a) True
c) String
d) False
e) Boolean
Hint: Comparison operator
4. Which of the following is the correct way to convert the text 500 to an integer?
a) str(500)
b) That is not a text
c) float('500')
d) int('500')
Hint: Type conversion
No comments:
Post a Comment