A variable is a reserved space in a computer's memory that can hold a specific value which is referenced by a specific name in the program.
Variables can be declared with a unique name as a place holder to store a specific value.
Unlike other languages you do not need to declare the variable type.
Variables should start with a lower case letter, cannot include spaces, and if their name is more than one word should be written like this: userName, playerID, difficultyLevel etc.
String
Integer
Float
Boolean
Lists (similar to arrays in other languages)
See examples of variables below:
name = "john smith" #String
address = " 34 red st" #String
age = 10 #integer / number
height = 1.82 #float / number with a decimal
alive = True #boolean (true or false)
All code should be clearly commented with instructions, hints, and reminders to the programmer(s) about what the code actually does.
#This is a comment and will not be executed in the code when run
The text in the brackets will be printed to the console. The text known as a string needs be surrounded with quotation marks " "
print("Hello World!")
#\n adds a new line, the code below prints an adventure game title with underlining on the next line.
print("Welcome to my dungeon adventure game! \n ----------------------------------")
The word concatenate simply means 'to join' or 'to link'.
We can concatenate strings with variables and strings using the '+' symbol.
print("Hello my name is " + name)
If you try to concatenate variable which are numbers, you MUST cast each variable to a string in the output / print code using the str() command. See the examples below:
print("Hi, I am " + str(age) + " years old. I am " + str(height) + " metres tall.")
print("To improve to level " + str(level) + " in weightlifting, I must increase the number of repetitions of 50kg I lift to " + str(reps) + ". "
There is another method of printing numbers without casting to a string. This method uses commas. See the examples below:
print("Hi, I am",str(age),"years old. I am",str(height)",metres tall.")
print("To improve to level",str(level),"in weightlifting, I must increase the number of repetitions of 50kg I lift to",str(reps),". "
Print Statements and Variables Video