Programming Fundamentals
The use of variables, constants, inputs, outputs and assignments
Outputs in Python
In Python, you can use the print()
function to display output to the user. This function writes the specified message to the console or standard output device.
Basic Example
# Displaying a message to the user
print("Hello, World!")
each print statement will appear on a new line in your code, if you put two in a sequence they will appear one line after the other
# Displaying a message to the user
print("Hello, World!")
print("Goodbye, World!")
You can put values into a print also like this:
# Displaying a message to the user
print("Hello, World!")
print("Goodbye, World!")
print(64) # this outputs the number 64
If you use mathmatical operators inside a print statement it will perform the calculation and then display the result
print(1+2) # this outputs the number 3
Concatenation
If you use a + between two strings(text values) it will join the strings together
print("Hello"+" "+"world!") # this outputs Hello world!
You will see that this important when we want to output variables with strings to give the user useful feedback about the information being displayed
What is a Variable?
A variable in programming is like a container that holds data which can be changed or used throughout a program. Think of it as a labeled box where you can store information, such as numbers, text, or more complex data types. Variables are fundamental building blocks in any programming language because they allow us to store, retrieve, and manipulate data.
Definition: Variable
A named location in memory that can change during the execution of the program.
Why Use Variables?
Variables make your code more flexible and readable. Instead of hardcoding values directly into your code, you can use variables to represent these values, making your program easier to modify and understand. Here are a few reasons why variables are essential:
- Dynamic Values: Variables allow you to work with data that can change over time.
- Reusability: Use the same variable multiple times without rewriting the data.
- Clarity: Makes your code more understandable by giving meaningful names to data.
Declaring a Variable in Python
In Python, declaring a variable is straightforward. You simply write the variable name, followed by an equals sign (=
), and then the value you want to store. Python is dynamically typed, which means you do not need to specify the type of the variable when declaring it.
Example:
# Declaring variables
age = 25
name = "Alice"
is_student = True
height = 5.9
In this example:
- age is an integer, which is a whole number
- name is a string, which is a group of characters
- is_student is a boolean, which is true or false
- height is a float, which is a real number
You can find out more about types in the next page of this website
What is an Assignment?
In programming, an assignment is the process of storing a value in a variable. The assignment operation assigns a specific value to a variable, effectively placing the value into the memory location associated with that variable. This allows the program to remember and manipulate the value later.
Why Use Assignments?
Assignments are fundamental to programming because they allow you to:
- Store Values: Save data that can be used and manipulated throughout your program.
- Update Values: Change the value stored in a variable as your program runs.
- Make Calculations: Perform operations on variables and store the results.
- Control Logic: Use assigned values to influence the flow of your program.
The Assignment Operator
In most programming languages, including Python, the assignment operator is the equals sign (=
). It assigns the value on the right-hand side to the variable on the left-hand side.
Example in Python
# Assigning values to variables
age = 25
name = "Alice"
is_student = True
height = 5.9
Using Variables
Once you have declared a variable, you can use it in your program. You can print its value, perform operations on it, and update it.
Example:
# Printing variable values
print(age) # Output: 25
print(name) # Output: Alice
print(is_student) # Output: True
print(height) # Output: 5.9
# Updating variable values
age = 26
print(age) # Output: 26
name = "Bob"
print(name) # Output: Bob
Naming Variables
When naming your variables, follow these guidelines to ensure your code is readable and maintainable:
- Descriptive Names: Use names that clearly describe the data the variable holds (e.g., user_name, total_score).
- No Spaces: Variable names cannot contain spaces. Use underscores (e.g., user_name) to separate words.
- Start with a Letter: Variable names should start with a letter or an underscore, not a number.
- Case Sensitivity: Remember that variable names are case-sensitive. age, Age, and AGE are considered different variables. You should always start a variable with a lowercase letter, as uppercase identifiers are usually used for classes in Object Oriented programming (you don't need to worry about what that is yet)
# Good variable naming
user_age = 25
total_score = 95.5
is_logged_in = False
# Bad variable naming
a = 25
ts = 95.5
flag = False
What is a Constant?
A constant in programming is like a variable, but once it's set, its value cannot be changed throughout the execution of the program. Think of it as a labeled box that holds information, but unlike a variable, you can't replace the contents once it's assigned. Constants are used to represent fixed values that shouldn't be altered during the runtime.
Definition: Constant
A named location in memory that cannot change during the execution of the program.
Why Use Constants?
Constants are crucial for several reasons:
- Clarity: Constants give meaningful names to fixed values, making your code more readable and maintainable.
- Maintainability: If a constant value needs to change, you only need to update it in one place.
- Safety: Using constants prevents accidental changes to values that should remain fixed throughout the program.
Declaring a Constant in Python
In Python, constants are typically declared using uppercase letters with underscores separating words. While Python doesn't have a built-in constant type, the convention of using all uppercase letters signals to other developers that the value should not be changed.
Example:
# Declaring constants
PI = 3.14159
MAX_USERS = 100
WELCOME_MESSAGE = "Welcome to the coding class!"
In this example:
- PI represents the mathematical constant Pi.
- MAX_USERS represents the maximum number of users allowed.
- WELCOME_MESSAGE holds a greeting message.
Using Constants
Once you have declared a constant, you can use it just like a variable in your program, but remember that you should not change its value.
# Using constants
print(PI) # Output: 3.14159
print(MAX_USERS) # Output: 100
print(WELCOME_MESSAGE) # Output: Welcome to the coding class!
# Attempting to change a constant (not recommended)
# PI = 3.14 # This should be avoided to maintain the integrity of the constant
Naming Constants
When naming your constants, follow these guidelines to ensure your code is readable and maintainable:
- All Uppercase Letters: Use all uppercase letters with underscores to separate words (e.g., MAX_HEIGHT, DEFAULT_COLOR).
- Descriptive Names: Use names that clearly describe the data the constant holds.
- No Spaces: Constant names cannot contain spaces.
# Good constant naming
MAX_HEIGHT = 250
DEFAULT_COLOR = "blue"
# Bad constant naming
maxheight = 250
defaultcolor = "blue"
Working with Inputs
In programming, inputs are how you get data from the user or another source into your program. Handling inputs allows your program to be interactive and responsive to user actions, making it more dynamic and useful.
Why Use Inputs?
Inputs are essential because they:
- Enable Interactivity: Allow users to provide data that the program can process and respond to.
- Enhance Flexibility: Make programs adaptable to different situations based on user input.
- Collect Data: Gather information from users or other systems for processing.
Getting User Input in Python
In Python, you can use the input()
function to get user input. This function reads a line of text from the user and returns it as a string.
Basic Example:
# Prompting the user for input
name = input("Enter your name: ")
# Using the input value
print("Hello, " + name + "!")
In this example, the program prompts the user to enter their name and then prints a greeting using the input provided by the user.
Converting Input Types
Since the input() function always returns a string, you might need to convert the input to other data types, such as integers or floats, to perform numerical operations.
Example:
# Prompting the user for a number
age = input("Enter your age: ")
# Converting the input to an integer
age = int(age)
# Performing an operation with the input
years_until_30 = 30 - age
# Displaying the result
print("You will be 30 in " + str(years_until_30) + " years.")