TECHNOLOGY 

Published on

KembaraXtra - Computer Science: Variables in Programming

I. What is a Variable?

Definition: A named storage location in memory.

Purpose:
• Provides a way to access data at a specific memory address using a name.
• Abstracts away the need to manage specific memory addresses directly.

Properties of Variables:
Name: The identifier used to refer to the variable (e.g., points, age).
Type: Specifies the kind of data the variable can hold (e.g., integer, string).
Value: The actual data stored in the variable's memory location (e.g., 27, 2020).
Address: The memory location where the variable's value is stored.
Scope: The region of the program where the variable can be accessed.

II. Variables in C

Declaration and Assignment:
int points = 27;
int: Declares the variable points to be of type integer.
points: The name of the variable.
= 27: Assigns the integer value 27 to the variable points.

Type Specificity:
• C is a statically typed language.
• Once a variable is declared with a specific type (e.g., int), it can only hold values of that type. Attempting to assign a value of a different type will result in a compilation error.

Memory Allocation:
• The compiler allocates memory for the variable based on its type.
• Example: int typically occupies 4 bytes (32 bits) in modern C compilers.
• Variables declared sequentially are often stored contiguously in memory (but this isn't guaranteed by the C standard).

Changing Variable Values:
points = 31; // Changing the value of the points variable
• The type does not need to be respecified.

III. Variables in Python

Dynamic Typing:
• Python is a dynamically typed language.
• You do not explicitly declare the type of a variable. The type is inferred at runtime based on the assigned value.

Declaration and Assignment:
age = 22
• Creates a variable named age and assigns it the integer value 22.
• Python infers the type of age to be an integer.

Type Flexibility:
age = 22
age = 'twenty-two'
• First, age refers to an integer value (22).
• Then, age is reassigned to refer to a string value ('twenty-two').

Values have Types, Not Variables:
• The value to which a Python variable refers has a type.
• The variable itself doesn't have a fixed type.
• When you assign a new value to a variable, you are binding the variable to a new value (which may have a different type).

Key Difference from C: C variables have a fixed type, while Python variables do not.

Picture
0 Comments