Skip to content
Home » PYTHON JUMPSTART COURSE Section 1 – Introduction, Lesson 8 – Naming Rules

PYTHON JUMPSTART COURSE Section 1 – Introduction, Lesson 8 – Naming Rules

Spread the love

In Python everything’s an object. Variables, functions, modules and all the other stuff we’re about to learn are objects. And each object needs a name by which we can refer to it. These names are called identifiers. So, what are the naming rules in Python?

Identifiers

So, an identifier is a name used to identify a variable, function, class, module or other object.

– Identifiers can consist of the uppercase letters “A” through “Z”, the lowercase letters “a” through “z” , the underscore _ and, except for the first character, the digits 0 through 9:

>>> size = 10
>>> _color = "blue"
>>> STN = 0.00014
>>> code784 = "p44 - bc16"

– There may be no blanks in identifiers. If an identifier should consist of more than one word, we may use underscores:

average_speed  # recommended for variable and function names

– There may be no special characters like [‘.’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’] in identifiers.

– Identifiers must not be the same as any of the Python keywords.

Python keywords

Keywords are special words which are reserved and can’t be used as identifiers. We can use the help() function to find info about any keyword, module or topic:

>>> help()

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
 
If we type ‘keywords’, we’ll get the list of all the keywords.

help> 
keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass                

help>

You can also use the iskeyword() method to check if a name is a keyword.

Case-Sensitivity

Python is case sensitive. The variables name and Name are two different things. Here a variable name is defined:

>>> name = "Anne"

We can’t print Name because there is no such variable:

>>> print(Name)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Name' is not defined

Valid and Invalid Identifiers

We can use the string method isidentifier() to check if the identifier is valid. You can use the method directly on the string:

>>> "name".isidentifier()   # this one is OK
True
>>> "a$ww".isidentifier()   # invalid because of the $ character
False
>>> "2aa".isidentifier()    # invalid because of the initial digit
False

If you use an invalid name, you get an error:

>>> 7th = 48    # Here the first character is a number
  File "<stdin>", line 1
    7th = 48
      ^
SyntaxError: invalid syntax
>>> del = 81    # Here the variable name is a keyword
  File "<stdin>", line 1
    def = 81
        ^
SyntaxError: invalid syntax

QUIZ

1. The names of classes, functions, variables, etc. are called:
    A) identifiers
    B) identities
    C) IDs
 
2. Which of the following is not a valid name for an object:
    A) wp6
    B) _wp6
    C) 6wp
 
3. We can check whether an identifier is a keyword by using the … method:
    A) iskeyword()
    B) keyword()
    C) _keyword()
 

TRUE OR FALSE?

1) Python is case sensitive.
2) Keywords can’t be used as identifiers.

WHAT’S THE OUTPUT?

1)
>>> “aaa”.isidentifier()  
 
2)
>>> “x_24”.isidentifier()
 
3)
>>> “nn!”.isidentifier()  

SOLUTION

QUIZ

1. The names of classes, functions, variables, etc. are called:
    A) identifiers
    B) identities
    C) IDs
 
2. Which of the following is not a valid name for an object:
    A) wp6
    B) _wp6
    C) 6wp
 
3. We can check whether an identifier is a keyword by using the … method:
    A) iskeyword()
    B) keyword()
    C) _keyword()
 

TRUE OR FALSE?

1) Python is case sensitive.
True
2) Keywords can’t be used as identifiers.
True

WHAT’S THE OUTPUT?

1
>>> “aaa”.isidentifier()  
Output:
True
 
2
>>> “x_24”.isidentifier()  
Output:
True
 
3
>>> “nn!”.isidentifier()  
Output:
False

PROJECT

'''
Naming Rules - Project

VALID NAMES
__________________________________________________________

Your task is to write a program that lets the user test whether a name
can be used as an identifier. It can if it complies with the naming rules
Python imposes. 

The program should work like in the following example:

Which name do you want to test? max_volume
max_volume is a valid name: True

or

Which name do you want to test? 3n
3n is a valid name: False

This could be done better with conditional statements, but we haven't
talked about them yet, so this will do for now.

And here's how you should write this program:

#1. Create a variable called name to store user input. Use the following
prompt in the input function:

Which name do you want to test? 


#2. Write code that will print a message like this:

x is a valid name: True

where x is the user input and the last part (True or False) is returned
by the isidentifier function. 

First create a variable called message that will store the string. 
Use concatenation to format the string. 

There is one thing we haven't covered yet that you will need to do:
if you try to use the isidentifier function in concatenation directly,
it won't work. This is because this function returns a boolean value
(True or False) and you can't concatenate strings with booleans. This is
why you have to convert the boolean to a string. Then it will print
as True or False.

In order to convert x to a string, the syntax is:

str(x)

So, use the syntax with the isidentifier function.

When you're done formatting the string, print the value of the message 
variable.

'''

PROJECT SOLUTION

##1. 

name = input("Which name do you want to test? ")

##2. 

message = name + " is a valid name: " + str(name.isidentifier())
print(message)


Spread the love

Leave a Reply