Python identifiers, keywords, data types, type casting and escape characters
AdvertisementIntroduction
Python is a high-level, general-purpose programming language known for readable syntax and a large ecosystem of libraries.
Python fundamentals include identifiers, keywords, data types, variables, type conversion, operators, and string handling.
Understanding these concepts helps you write clear programs and avoid common errors.
Python Tokens
A token is a basic individual unit of a Python program.
Common categories of Python tokens include:
- Keywords
- Identifiers
- Literals
- Operators
- Delimiters or punctuators
Example:
total = 10 + 20
In this statement:
totalis an identifier.=is an assignment operator.10and20are integer literals.+is an arithmetic operator.
Identifiers in Python
An identifier is a name used to identify a variable, function, class, or another named object.
Examples:
student_name = "Alex"
age = 21
total_marks = 450
Here, student_name, age, and total_marks are identifiers.
Rules for Identifiers
- An identifier cannot begin with a digit.
- It can contain letters, digits, and underscores.
- Spaces are not allowed.
- Most punctuation and special characters, such as
@,$, and-, cannot be used in ordinary identifiers. - Python identifiers are case-sensitive.
- Reserved keywords cannot be used as ordinary identifiers.
Examples:
| Identifier | Valid? | Reason |
|---|---|---|
name |
Yes | Contains letters |
student1 |
Yes | Digits may follow the first character |
_total |
Yes | An underscore may start a name |
total_marks |
Yes | Underscores are permitted |
1student |
No | Begins with a digit |
student-name |
No | Contains a hyphen |
student name |
No | Contains a space |
class |
No | Reserved keyword |
Case Sensitivity
Python treats uppercase and lowercase letters as different characters.
age = 20
Age = 30
AGE = 40
print(age)
print(Age)
print(AGE)
Output:
20
30
40
Naming Best Practices
Use descriptive variable names:
student_name = "Alex"
total_price = 250
number_of_students = 40
Avoid unclear names such as x1, abc, or temp2 when a descriptive name would improve readability.
Python conventionally uses snake_case for variable and function names.
Keywords in Python
Keywords are reserved words that have special meanings in Python syntax.
They cannot be used as ordinary variable or function names.
Examples include:
if
else
for
while
def
class
return
import
try
except
True
False
None
Example of a valid program:
if True:
print("Condition is true")
Output:
Condition is true
Here, if and True have special meanings.
The following is invalid:
# Invalid: 'class' is a keyword.
# class = "Python"
Checking Keywords
Python provides the keyword module.
import keyword
print(keyword.iskeyword("if"))
print(keyword.iskeyword("student"))
Output:
True
False
You can display the keyword list for your installed Python version:
import keyword
print(keyword.kwlist)
The exact list can depend on the Python version. Some soft keywords, such as match and case, have special meanings only in particular syntactic contexts.
Variables in Python
A variable is a name that refers to an object or value.
name = "Alex"
age = 21
salary = 35000.50
print(name)
print(age)
print(salary)
Output:
Alex
21
35000.5
Python uses dynamic typing, which means a name can refer to objects of different types during program execution.
value = 100
print(value)
value = "Python"
print(value)
Output:
100
Python
This is allowed because Python does not require you to declare a variable's type in advance.
Data Types in Python
A data type describes the kind of value represented by an object and the operations available for it.
Common built-in types include integers, floating-point numbers, complex numbers, strings, Booleans, lists, tuples, sets, dictionaries, and NoneType.
Integer: int
Integers represent whole numbers.
age = 21
temperature = -5
print(type(age))
print(type(temperature))
Floating-Point: float
Floating-point numbers represent real-valued approximations.
price = 99.50
percentage = 85.75
print(type(price))
Complex: complex
Complex numbers contain real and imaginary components.
number = 3 + 4j
print(number)
print(type(number))
String: str
Strings represent text.
name = "Python"
message = 'Hello, World!'
print(name)
print(type(message))
Strings can use single or double quotation marks.
Boolean: bool
Boolean values represent logical truth values: True and False.
is_student = True
is_finished = False
print(type(is_student))
List: list
Lists are ordered, mutable collections.
numbers = [10, 20, 30]
numbers.append(40)
print(numbers)
Output:
[10, 20, 30, 40]
Tuple: tuple
Tuples are ordered collections that cannot be reassigned item by item after creation.
coordinates = (10, 20)
print(coordinates)
print(type(coordinates))
Set: set
Sets store distinct elements and do not guarantee a fixed display order.
numbers = {10, 20, 20, 30}
print(numbers)
The duplicate value is stored only once.
Dictionary: dict
Dictionaries store key-value pairs.
student = {
"name": "Alex",
"age": 21
}
print(student["name"])
print(student["age"])
Output:
Alex
21
NoneType
None represents the absence of a value.
result = None
print(result)
print(type(result))
Checking Data Types
Use the built-in type() function to inspect an object's type.
print(type(10))
print(type(10.5))
print(type("Hello"))
print(type(True))
print(type([1, 2, 3]))
You can also use isinstance() to check whether an object belongs to a type.
age = 21
print(isinstance(age, int))
print(isinstance(age, str))
Output:
True
False
Type Conversion and Type Casting
Type conversion means converting a value from one data type to another.
Python provides several built-in conversion functions.
int()
Converts a compatible value to an integer.
number = int("25")
print(number)
print(type(number))
Output:
25
<class 'int'>
Converting a floating-point number to an integer removes its fractional part toward zero.
print(int(9.8))
print(int(-9.8))
Output:
9
-9
float()
Converts a compatible value to a floating-point number.
price = float("99.50")
print(price)
str()
Produces a string representation of a value.
age = 21
message = "Age: " + str(age)
print(message)
Output:
Age: 21
bool()
Converts a value to its Boolean interpretation.
print(bool(1))
print(bool(0))
print(bool(""))
print(bool("Python"))
Output:
True
False
False
True
In Python, zero, empty strings, empty collections, and None are examples of falsey values. Most other objects are truthy.
Invalid Type Conversion
Some conversions are not possible.
# Raises ValueError:
# int("hello")
If input data may be invalid, use exception handling to handle conversion failures.
Implicit and Explicit Type Conversion
Implicit Conversion
Python sometimes converts numeric values automatically during an operation.
number = 10
decimal = 2.5
result = number + decimal
print(result)
print(type(result))
Output:
12.5
<class 'float'>
The integer participates in the arithmetic operation with the floating-point number, producing a float.
Explicit Conversion
Explicit conversion occurs when the programmer calls a conversion function.
number = int("100")
decimal = float("3.14")
print(number)
print(decimal)
Explicit conversion is particularly useful when reading numeric input from a user.
Taking Input from Users
The input() function reads text from the user.
name = input("Enter your name: ")
print("Welcome,", name)
For numeric calculations, convert the returned string:
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
For decimal input:
price = float(input("Enter the price: "))
print("Price entered:", price)
Remember that invalid numeric input can raise a ValueError.
Escape Characters in Python Strings
Escape sequences allow special characters to be represented inside strings.
An escape sequence typically begins with a backslash.
Common Escape Sequences
| Escape sequence | Meaning |
|---|---|
\n |
Newline |
\t |
Horizontal tab |
\\ |
Backslash |
\' |
Single quotation mark |
\" |
Double quotation mark |
\r |
Carriage return |
\b |
Backspace |
\f |
Form feed |
Newline Example
print("Hello\nWorld")
Output:
Hello
World
Tab Example
print("Name\tAge")
print("Alex\t21")
Output:
Name Age
Alex 21
The exact visual spacing depends on the terminal or editor.
Including Quotation Marks
print("He said, \"Hello!\"")
print('It\'s a Python example.')
Output:
He said, "Hello!"
It's a Python example.
Including a Backslash
print("C:\\Users\\Student")
Output:
C:\Users\Student
Raw Strings
A raw string uses the r or R prefix.
In a raw string, backslashes are generally treated literally rather than starting escape sequences.
path = r"C:\Users\Student\Documents"
print(path)
Raw strings are often convenient for Windows-style paths and regular expressions.
A raw string cannot end with an odd number of backslashes because the final backslash would escape the closing quotation mark.
Comments in Python
Comments help explain the purpose of code.
Single-line comments begin with #.
# Calculate the total price
price = 100
quantity = 3
total = price * quantity
print(total)
Output:
300
Comments are useful when they explain why something is done, especially when the reason is not obvious from the code.
Practical Example
The following program combines identifiers, data types, input, conversion, and output.
student_name = input("Enter student name: ")
marks1 = float(input("Enter marks for subject 1: "))
marks2 = float(input("Enter marks for subject 2: "))
marks3 = float(input("Enter marks for subject 3: "))
total_marks = marks1 + marks2 + marks3
average_marks = total_marks / 3
print("\nStudent Report")
print("Name:", student_name)
print("Total Marks:", total_marks)
print("Average Marks:", average_marks)
Concepts Used
- Identifiers to name variables
- Strings to store the student's name
- Floating-point values to store marks
- Input to collect information
- Arithmetic to calculate the total and average
- Escape sequences to format the output
Common Beginner Mistakes
Using a Keyword as a Variable
Incorrect:
# class = "Python"
Correct:
class_name = "Python"
Starting a Variable Name with a Digit
Incorrect:
# 2marks = 90
Correct:
marks2 = 90
Confusing Assignment and Comparison
= assigns a value, while == compares values.
age = 18
print(age == 18)
Forgetting Type Conversion
Incorrect:
# input() returns a string.
# This will not perform numeric addition:
# result = input("Enter a number: ") + 10
Correct:
number = int(input("Enter a number: "))
result = number + 10
print(result)
Misunderstanding Escape Sequences
\n represents a newline, while \\ represents a literal backslash. Use raw strings when literal backslashes are useful.
Practice Questions
- What is an identifier in Python?
- What rules must an identifier follow?
- What is the difference between a keyword and an identifier?
- Why is Python described as dynamically typed?
- What is the difference between
int,float, andstr? - What does
type()do? - What is the difference between implicit and explicit conversion?
- What is the purpose of
bool()? - What does the escape sequence
\nrepresent? - How does a raw string differ from an ordinary string?
Coding Exercises
- Create variables for your name, age, and city. Print them.
- Ask a user for two integers and display their sum.
- Convert the string
"45.5"to a float and print its type. - Print a message on two lines using
\n. - Print a Windows-style file path using a raw string.
- Write a program that calculates the average of three marks.
- Create a program that checks whether a value is an integer using
isinstance().
Summary
In these study notes, we covered:
- Python tokens
- Identifiers and naming rules
- Keywords and the keyword module
- Variables and dynamic typing
- Common built-in data types
- Type checking with
type()andisinstance() - Implicit and explicit type conversion
- User input
- Escape sequences and raw strings
- Comments and basic programming practice
Understanding these fundamentals prepares you for more advanced Python concepts, including operators, conditional statements, loops, functions, collections, and object-oriented programming.
Official resources
- Python Language Reference: Lexical Analysis
- Python Built-in Types
- Python Built-in Functions
- Python Keyword Module
- Python Downloads
About this guide. This is a written study guide for the topic of this episode, prepared to go with the video above. It is not a word-for-word transcript, so the video may cover things in a different order.