English:Programming with Variables and Data Types

Programming with Variables and Data Types
Introduction
Programming becomes powerful when a program can remember information, give that information a meaningful name, and use it later. A game can remember your score, a weather program can store a temperature, and a school app can keep a student's name and attendance status. In programming, these named pieces of information are commonly handled with variables, while data types describe what kind of values are being represented and which operations make sense for them.
This aiMOOC is designed for Grades 9–10. You will use beginner-friendly Python examples because Python makes variables and common data types easy to see, but the core ideas also apply to languages such as Java, JavaScript, C#, C++, and many others. By the end of the course, you should be able to create variables, select suitable data types, update values, convert between compatible types, predict the effect of expressions, and explain common type-related programming errors.
The diagram above illustrates a basic programming-variable idea: a name is connected with a value that the program can later access. Different languages describe the details differently, but the central purpose is the same: a program needs a reliable way to refer to data.
The Khan Academy video above gives a short introduction to variables and assignment in Python. While you watch, focus on what changes in memory when an assignment statement is executed.
Learning Goals
After working through this course, you should be able to explain the difference between a variable name, a value, and a data type; identify integers, floating-point numbers, strings, and Booleans; use assignment and reassignment correctly; choose descriptive identifiers; predict results of simple expressions; perform safe type conversion; identify type mismatches; and apply these ideas in small programs.
| Area | What you should be able to do |
|---|---|
| Variables | Create, read, update, and explain named values in a program. |
| Data types | Distinguish common types and choose an appropriate type for a situation. |
| Assignment | Explain what an assignment statement does and trace changes step by step. |
| Type conversion | Convert compatible values when a program needs another representation. |
| Debugging | Recognize and correct common mistakes involving names, values, and types. |
Variables: Names for Program Data
A variable is a programming name associated with a value. In many beginner explanations, a variable is compared with a labeled box. The label is the variable name, and the content is the value. This model is useful as long as you remember that real programming languages may implement variables differently. For example, in Python, assignment binds a name to an object rather than creating a simple physical box with the value written inside it.
Consider this Python code:
score = 10 player_name = "Maya" is_active = True
Here, score, player_name, and is_active are variable names. Their current values are 10, "Maya", and True. The equals sign in this context is an assignment operator: it tells Python to associate the name on the left with the value produced on the right.
Assignment Is Not the Same as a Mathematical Equation
In mathematics, the statement x = 5 usually expresses equality. In programming, x = 5 often means "assign the value 5 to the name x." This becomes especially clear when a variable is updated:
score = 10 score = score + 5
The second line is not a sensible algebraic equation, because a number cannot equal itself plus five. In programming, however, it means: read the current value of score, add 5, and assign the new result back to score. After the second line, score has the value 15.
Flowcharts and visual programming tools can make declaration and assignment more visible. The image above shows how a variable-related step can be represented in a flow-oriented programming environment.
Reassignment and State
A program's state is the information it currently holds. Reassignment changes part of that state. Trace this example carefully:
lives = 3 lives = lives - 1 lives = lives + 2
The values of lives are 3, then 2, then 4. Being able to trace these changes is essential for understanding loops, games, simulations, counters, and many algorithms.
A useful tracing method is to make a small table:
| Step | Statement | Current value of lives
|
|---|---|---|
| Start | lives = 3
|
3 |
| Update | lives = lives - 1
|
2 |
| Update | lives = lives + 2
|
4 |
Choosing Good Variable Names
Good names make code easier to read and maintain. Compare x = 17 with student_age = 17. The second name communicates purpose. Naming rules vary by language, but most languages require identifiers to follow specific syntax rules and prevent you from using reserved keywords as ordinary variable names.
In Python, names can contain letters, digits, and underscores, but they cannot start with a digit. Python names are case-sensitive, so score and Score are different names. For school projects, prefer clear names such as average_temperature, attempts_left, or user_message instead of vague names such as a, b, or thing.
Data Types: What Kind of Value Is It?
A data type classifies values according to the kind of information they represent and the operations that make sense for them. A programming language may use the type to decide how data should be interpreted, stored, checked, or combined.
For beginners, four types are especially important:
| Type | Example value | Typical use | Python name |
|---|---|---|---|
| Integer | 42
|
Counts, ages, whole-number scores | int
|
| Floating-point number | 19.75
|
Measurements, averages, approximate decimal values | float
|
| String | "Hello"
|
Names, messages, labels, other text | str
|
| Boolean | True
|
Conditions with two truth values | bool
|
The CS50 video above explores data types in more depth. As you watch, compare the idea of a type with the examples in the table.
Integers
An integer represents a whole number without a fractional part. Examples include -12, 0, and 2048. Integers are useful for quantities that are counted exactly, such as the number of students, goals scored, attempts remaining, or items in a cart.
students = 28 goals = 3 balance_change = -5
Many languages have several integer types with different ranges. Python's built-in integers can grow to very large magnitudes as long as enough memory is available, so a beginner usually does not need to choose a fixed integer size in Python.
Floating-Point Numbers
A floating-point number is commonly used for values with a fractional part, such as 3.5, -0.25, or 98.6. Floating-point representation is efficient and widely used, but many decimal fractions cannot be represented exactly in binary. This means some calculations can contain tiny rounding effects.
price = 2.99 temperature = 21.6 average = 7.5
For example, a computer may store an approximation to a decimal fraction rather than the exact mathematical fraction. This is why money, scientific measurement, and high-precision calculations sometimes require special numeric strategies.
The diagram above illustrates how a value can be encoded in a 32-bit floating-point representation. You do not need to memorize the bit layout at this level, but you should understand the key idea: a floating-point value is a finite computer representation of a mathematical number.
Strings
A string represents text. In Python, string literals can be written with single or double quotation marks.
first_name = "Lina" subject = 'Computer Science' message = "Variables can store useful information."
Quotation marks matter. The value 25 is an integer, but the value "25" is a string containing two text characters. That difference affects what operations are valid.
number = 25 text = "25"
If you add 5 to number, you are doing arithmetic. If you combine text with another string, you are joining text. In Python, joining strings with the plus operator is called concatenation.
Computers represent characters using numeric encodings. ASCII is a historically important character encoding that maps characters to numeric codes. Modern Python strings use Unicode, which can represent a far larger range of writing systems and symbols, but ASCII remains useful for understanding that text ultimately has a machine representation.
Booleans
A Boolean has two truth values: True or False in Python. Booleans are central to decisions.
is_logged_in = True has_permission = False temperature_high = 31 > 30
The expression 31 > 30 evaluates to True. Comparisons such as greater than, less than, or equality produce Boolean results that can guide an if statement.

Boolean logic combines truth values with operations such as and, or, and not. These operations become especially important when a program must check more than one condition.
The Crash Course video above connects Boolean logic with the way digital systems make decisions using true/false states.
Literals, Expressions, and Operators
A literal is a value written directly in source code, such as 12, 3.5, "hello", or False. An expression combines values, variables, and operators to produce another value.
subtotal = 12.50 tax_rate = 0.08 tax = subtotal * tax_rate total = subtotal + tax
The right side of an assignment is evaluated first. Its result is then assigned to the name on the left.
Common operators include arithmetic operators such as +, -, *, and /; comparison operators such as ==, !=, <, and >; and Boolean operators such as and, or, and not.
The Same Symbol Can Behave Differently by Type
The meaning of an operator can depend on the types of its operands. In Python:
3 + 4 "3" + "4"
The first expression produces the integer 7. The second produces the string "34". This is a major reason why understanding types matters: the program needs to know whether data should be treated as numbers, text, truth values, or something else.
Type Conversion
Sometimes data arrives in one type but must be used as another. Input from a keyboard, for example, is commonly received as text. If you want to calculate with a number typed by the user in Python, you usually convert the string.
age_text = input("Enter your age: ")
age = int(age_text)
next_year = age + 1
The function int() attempts to create an integer. The functions float(), str(), and bool() perform other conversions.
whole_number = int("42")
decimal_number = float("3.5")
message = str(2026)
Conversion only works when the source value can be meaningfully interpreted as the target type. The string "42" can become an integer, but the string "forty-two" cannot be converted to an integer by int() directly.
Conversion Can Lose Information
Some conversions change information. In Python, converting a floating-point value to an integer removes the fractional part rather than performing ordinary rounding.
value = 8.9 whole = int(value)
The value of whole is 8. If you need mathematical rounding, use an appropriate rounding operation instead of assuming that conversion will do it.
Dynamic and Static Typing
Programming languages differ in how they connect variables and types. In a statically typed language, type rules are largely checked before the program runs, and variables or expressions are usually constrained by declared or inferred types. In a dynamically typed language such as Python, values have types and names can be rebound to values of different types while the program runs.
Python allows:
item = 12 item = "twelve"
This flexibility can be convenient, but changing the meaning and type of the same name without a clear reason can make code harder to understand. Good programmers choose names and structures that communicate intent.
Compare a Java-style declaration:
int score = 12;
with Python:
score = 12
The syntax differs, but both examples involve a name, a value, and a type concept.
Variables and Computer Memory
When a program runs, values must be represented somewhere in the computer's working memory or in processor registers. High-level programming languages protect you from many low-level details, but the memory idea explains why variables matter: programs need organized ways to retrieve and update information.
The program-memory diagram above shows that running programs can organize information into different memory areas. Beginners do not need to manage these regions directly in Python, but the image helps connect high-level variables with the physical fact that a computer stores information using electronic memory.
Scope: Where a Variable Can Be Used
The scope of a variable is the part of a program in which its name is available. Scope becomes important when you write functions.
def greet():
message = "Hello"
print(message)
greet()
Here, message is created inside the function. In Python, a name assigned inside a function is normally local to that function unless special rules are used. Understanding scope prevents accidental name conflicts and helps you organize larger programs.
The CS50P lecture above covers variables, strings, integers, floating-point values, type conversion, and scope in a broader introduction to Python programming. Use it as an extended review or enrichment resource.
Constants and Values That Should Not Change
Some programs contain values that should remain fixed while a program runs, such as a conversion factor or maximum number of attempts. Languages provide different ways to express this idea. In Python, programmers often use uppercase names by convention to signal that a value should be treated as a constant.
MAX_ATTEMPTS = 3 SECONDS_PER_MINUTE = 60
This is a convention rather than an absolute enforcement mechanism in ordinary Python code. In other languages, a keyword such as const or final can place stronger restrictions on reassignment.
Common Errors and How to Debug Them
Variable and type mistakes are among the most common beginner programming errors. A good debugging process asks: What is the current value? What is its type? Which operation is being attempted? What type should the result have?
| Problem | Example | Why it happens | Possible fix |
|---|---|---|---|
| Undefined name | print(total) before total exists
|
The variable has not been assigned in the current scope | Assign the value first or correct the name |
| Type mismatch | Adding a number to text | The operator cannot combine those values in that way | Convert one value or change the intended operation |
| Invalid conversion | int("blue")
|
The text does not represent an integer | Validate the input before conversion |
| Typo in an identifier | score versus scroe
|
The program treats them as different names | Use consistent spelling and meaningful names |
| Unexpected reassignment | A useful value is overwritten | The same name is reused carelessly | Trace assignments and choose clearer names |
Debugging with type() in Python
Python's type() function can help you inspect a value during learning and debugging.
score = 42 name = "Ari" print(type(score)) print(type(name))
A program should not depend on printing types everywhere, but temporary checks can help you understand what the interpreter is doing.
A Worked Example: Simple Ticket Calculator
Suppose you are writing a small program that records a visitor's name, age, ticket price, and membership status.
visitor_name = "Noah"
age = 15
ticket_price = 8.50
is_member = True
if is_member:
ticket_price = ticket_price * 0.9
print(visitor_name, age, ticket_price)
This example uses four data types with different roles. visitor_name is text, age is an integer, ticket_price is a floating-point number, and is_member is Boolean. The if statement uses the Boolean value to decide whether to change the price.
A useful design question is: What kind of information does each value represent? Choosing the correct type makes the purpose of the code clearer and reduces errors.
Improving the Example with User Input
A user-input version must handle the fact that input() returns text in Python.
visitor_name = input("Name: ")
age = int(input("Age: "))
ticket_price = float(input("Ticket price: "))
print("Visitor:", visitor_name)
print("Age next year:", age + 1)
print("Ticket price:", ticket_price)
If the user enters text that cannot be converted to the requested numeric type, the program will raise an error unless you add input validation. Later courses can extend this example with exception handling.
Good Programming Habits
Choose variable names that explain purpose. Keep the same name for the same kind of concept. Convert input deliberately instead of guessing its type. Test expressions with small known values. Trace reassignment when a result surprises you. Use Boolean names that read naturally, such as is_ready or has_access. Avoid hiding important meaning in vague names. Add comments only when they explain something that the code itself does not make clear.
Interactive Tasks
Quiz: Test Your Knowledge
What does an assignment statement usually do in an imperative program? (It associates a variable name with a value) (!It permanently deletes a value) (!It turns every value into text) (!It compares two programs)
Which value is an integer in Python? (42) (!42.5) (!forty two) (!True)
Which data type is most suitable for a person's name? (String) (!Integer) (!Boolean) (!Floating point)
Which Python value is Boolean? (False) (!False as text) (!Zero point five) (!Letter F)
After score starts at 10 and is reassigned to score plus 5, what is its value? (15) (!10) (!5) (!105)
Why can the string value 25 not always be used like the integer value 25? (They have different data types) (!Strings are always negative) (!Integers cannot be stored) (!Both values are identical in every operation)
What is type conversion? (Changing a value into another compatible type) (!Renaming every variable in a program) (!Deleting all decimal values) (!Running the program twice)
Which name is clearest for storing a student's age? (student_age) (!x) (!thing) (!data1)
What does a comparison such as 8 greater than 3 produce? (A Boolean value) (!A string value) (!A file) (!A variable name)
Why can floating-point calculations sometimes show tiny rounding effects? (Many decimal fractions cannot be represented exactly in binary) (!Floating point values are always strings) (!Computers cannot store numbers) (!Variables cannot contain decimals)
Memory Game
| Variable | A programming name associated with a value |
| Integer | A whole-number data type |
| String | A type used for textual data |
| Boolean | A type with true and false truth values |
| Assignment | The act of binding or setting a name to a value |
| Conversion | Changing a value into another compatible representation |
Drag and Drop
| Match the correct terms. | Topic |
|---|---|
| Integer value | Whole-number quantity such as a score count |
| String value | Textual information such as a person's name |
| Boolean value | Truth information used for a condition |
| Floating-point value | Approximate numeric measurement with a fractional part |
| Assignment statement | Instruction that sets or updates a named value |
...
Crossword Puzzle
| Variable | What programming name can refer to a value that may change? |
| Integer | Which data type represents whole numbers? |
| String | Which data type represents text? |
| Boolean | Which data type represents truth values? |
| Float | Which common type represents approximate decimal values in Python? |
| Assignment | What operation sets or updates the value associated with a name? |
LearningApps
Cloze Text
Open-Ended Tasks
Easy
- Variable tracing: Create a three-column trace table for a five-line program that repeatedly changes one score variable, then explain each change in one sentence.
- Data type poster: Design an image or digital poster that teaches integer, floating-point, string, and Boolean values using original everyday examples.
- Naming variables: Rewrite ten vague variable names from a small program into descriptive names and justify your three most important changes.
- Programming interview: Interview a classmate, teacher, or programmer about how meaningful variable names help when reading code, then summarize the main ideas in a short English text.
Standard
- Input and conversion project: Write a small Python program that asks for a name, age, and height, converts numeric inputs correctly, and prints a clear summary.
- Debugging experiment: Create four intentional variable or type errors, record the error messages, repair the code, and explain what each error taught you.
- Boolean decision video: Produce a short screen-recorded video that demonstrates a Boolean variable controlling a simple program decision.
- Computer lab investigation: Visit your school computing lab or another supervised programming environment, identify two languages or tools in use, and compare how they represent variables or data types.
Advanced
- Type comparison study: Compare variable declarations and common types in Python and one statically typed language, then present the similarities and differences in a concise report.
- Floating-point experiment: Investigate at least three decimal calculations that reveal floating-point approximation, document the outputs, and explain why exact-looking decimals can behave unexpectedly.
- Mini application: Build a small grade calculator, game score tracker, or budget simulator that uses at least four meaningful variables and at least three different data types.
- Code review project: Exchange a short program with a partner, review variable names and type choices, suggest improvements, revise the code, and write a reflection on how the revision improved clarity.
Learning Assessment
- Trace and justify: Given a short program with several reassignments, determine the final values and explain the reasoning step by step rather than giving only the answer.
- Choose the type: For a real application such as a fitness tracker or school registration form, select suitable types for at least eight pieces of data and justify each choice.
- Repair a mixed-type program: Debug a program that combines strings and numbers incorrectly, then explain why each repair works.
- Transfer between languages: Translate a small Python variable example into another programming language and identify which concepts stay the same even though the syntax changes.
- Design for reliability: Improve a user-input program so that type conversion is deliberate, names are descriptive, and invalid input is handled or clearly reported.
- Explain representation limits: Use an example to explain why floating-point values are useful even though some decimal fractions cannot be represented exactly.
Evidence of Learning
Strong evidence of learning includes accurate explanations of variables, values, assignment, and types; correct identification and use of integers, floating-point numbers, strings, and Booleans; trace tables that show how values change; programs with descriptive identifiers; successful type conversions; debugging notes that identify the cause of errors; a working small application; and the ability to transfer the same concepts to a second programming language.
You should also be able to explain why a value's type affects which operations are meaningful, why input often requires conversion, why Boolean values are central to program decisions, and why floating-point arithmetic can be approximate. High-quality evidence combines correct code with reasoning: you can explain not only what the program does, but why your variable names and type choices are appropriate.
OERs on the Topic
The following open resources can extend your learning. Use them to compare definitions, examples, and explanations with what you have learned in this course.
Python documentation: Built-in Types
CS50's Introduction to Programming with Python
Linked Learning Areas
Variables and data types connect directly to Programming, Algorithm, Control flow, Boolean algebra, Computer memory, Input/output, Debugging, Type system, and Software development. These topics build the foundation for larger programs in which information is collected, transformed, tested, stored, and displayed.
aiMOOC Projects
MOOCwiki · Deutsch
Nach dem Lernen ist vor dem Lernen
Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.
Zur MOOCwiki-HauptseiteMediathek
Mediathek
Mediathek wird aus dem Wiki geladen ...
Keine passenden Inhalte gefunden. Bitte ändere Suche oder Filter.
NEWSLernweltNOAH fragen