11. Variables
rectangle_length = 2.3
, the variable names is rectangle_length
, the type is float
(decimal) and the value is 2.3
.user_name = Annie
, the variable names is user_name
, the type is str
(string) and the value is Annie
.- Rules for Python variable names:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores ( _ )
Variable names are case-sensitive (
age
,Age
andAGE
are three different variables)
11.1. Python Reserved Words
Reserved Words are keywords that have a set meaning and can’t be used for other purposes such as for variable names. Reserved words are case-sensitive and must be used exactly as shown. They are all entirely lowercase, except for False, None, and True.
print(help("keywords"))
.import keyword
print(keyword.kwlist)
11.2. Python conventions
height
instead of x
for the height of an object.11.3. Snake case
11.4. ALL_CAPS
PI = 3.14
, GRAVITY = 9.8
, MILES_TO_METRES = 1609
.11.5. CapWords
AnimalFeatures
, are used for Class names in python.11.6. camelCase
playerScore
, are not recommended in python.11.7. KebabCase
player-score
, are not recommended in python.11.8. Sample code
print('Federer has won 20 Grand Slams.')
Generalised to:
player_name = 'Federer'
wins = '20'
print(player_name + ' has won ' + wins + ' Grand Slams.')
11.9. Tasks
Questions
Write
AGE
in snake case.Write
MyName
in snake case.Write
MyFirstNameLastName
in snake case.Write
rectangleArea
in snake case.Write
cm_in_an_inch = 2.14
as ALL_CAPS.Write
lbs_in_a_kg = 2.2
as ALL_CAPS.A program asks for a person’s age and stores it. What would be a good variable to use:
x
,variable1
,AGE
,age
,Years_Old
?A program uses a person’s first name and last name. What would be a good variable to use for their last name:
x
,variable1
,SURNAME
,last_name
,Name
?A program calculates the area of a rectangle. What would be two good variables to use for the length and width of the rectangle:
x
,y
,LENGTH
,length
,Width
,width
?
Write AGE
in snake case.
age
Write MyName
in snake case.
my_name
Write MyFirstNameLastName
in snake case.
my_first_name_last_name
Write rectangleArea
in snake case.
rectangle_area
Write cm_in_an_inch = 2.14
as ALL_CAPS.
CM_IN_AN_INCH = 2.14
Write lbs_in_a_kg = 2.2
as ALL_CAPS.
LBS_IN_A_KG = 2.2
A program asks for a person’s age and stores it. What would be a good variable to use: x
, variable1
, AGE
, age
, Years_Old
?
age
A program uses a person’s first name and last name. What would be a good variable to use for their last name: x
, variable1
, SURNAME
, last_name
, Name
?
last_name
A program calculates the area of a rectangle. What would be two good variables to use for the length and width of the rectangle: x
, y
, LENGTH
, length
, Width
, width
?
length, width