Constants
What are Constants? ๐โ
Constants are like permanent markersโonce you write something, it stays that way! These are values in your program that never change.
In pseudo-code, constants are declared using the CONSTANT keyword. Letโs see how they work and how to convert them to Python.
Syntax in Pseudo-Codeโ
Hereโs how constants are declared in pseudo-code:
CONSTANT ConstantName โ Value
Examples:โ
CONSTANT Pi โ 3.14159
CONSTANT SchoolName โ "Greenwood High"
CONSTANT MaxScore โ 100
Conversion to Python ๐โ
In Python, we donโt have a special CONSTANT keyword. Instead, we use uppercase variable names as a convention to show they shouldnโt be changed.
Hereโs how the above pseudo-code converts to Python:
PI = 3.14159 # Constant for Pi
SCHOOL_NAME = "Greenwood High" # Name of the school
MAX_SCORE = 100 # Maximum score
Why Use Constants? ๐คโ
- Prevent Mistakes: Keeps important values from being accidentally changed.
- Improve Readability: Makes your code easier to understand.
- Consistent Naming: Ensures everyone knows these values wonโt change.
In Python, thereโs nothing stopping you from changing a "constant" value. But just because you can, doesnโt mean you should. Stick to the rules for cleaner code!
Letโs Practice ๐โ
Convert these pseudo-code constants into Python:
CONSTANT SpeedOfLight โ 299792458
CONSTANT GoldenRatio โ 1.618
CONSTANT WelcomeMessage โ "Hello, World!"
Python Solution:
SPEED_OF_LIGHT = 299792458
GOLDEN_RATIO = 1.618
WELCOME_MESSAGE = "Hello, World!"
Well done, future coding genius! ๐โจ