Character Set in Python with suitable
Example
Certainly! Here's a simple explanation of the Character Set in Python with a suitable
example:
Character Set in Python
The character set is the group of characters that can be used in Python programs.
Python source code is written using characters from this set.
Components of Python Character Set:
Letters: All uppercase and lowercase English alphabets (A-Z, a-z)
Digits: Numbers from 0 to 9
Special symbols: Symbols like +, -, *, /, =, <, >, :, (), {}, [], etc.
Whitespace: Spaces, tabs, newline characters (used to separate statements and
indent blocks)
Important Points:
Identifiers (such as variable names) can use letters, digits, and underscores _, but
cannot start with a digit.
Python supports Unicode, so you can use many characters beyond ASCII in strings.
Example illustrating Character Set usage:
# Letters and digits used in variable names
name = "Alice" # Letters and quotes for string literal
age = 25 # Digits used for integer literal
score_1 = 95 # Letters, underscore, digits combined for identifier
# Special symbols used in operations
total_score = age + score_1 # '+' operator adds values
# Whitespace used for readability and indentation
if total_score > 100:
print("Great job!") # Indented to mark the block inside ‘if’
# Using special symbols in strings is allowed
message = "Hello, World!"
print(message)
Explanation:
name, age, score_1, and total_score are identifiers made from letters, digits, and
underscore.
= and + are special symbols (operators).
"Alice" and "Hello, World!" use letters and punctuation within string literals.
Spaces and indentation control the program structure
Python Statements
A statement in Python is a complete instruction that the Python interpreter can
execute. It can be a single action (simple statement) or a group of actions (compound
statement).
Types of Python Statements:
1. Simple Statement
A single instruction written on one line, like an assignment or function call.
2. Compound Statement
Consists of one or more statements grouped together, usually involving
indentation, such as if, for, and while blocks.
Examples:
1. Simple Statements
python
x = 10 # Assignment statement: assigns value 10 to variable x
print(x) # Function call statement: outputs the value of x
2. Compound Statements
python
age = 18
if age >= 18: # if statement (compound statement) starts here
print("You are an adult") # indented block executed if condition is True
else:
print("You are a minor") # indented block executed if condition is False
3. Multiple Simple Statements on One Line (using semicolon)
python
a = 5; b = 10; print(a + b) # Multiple statements separated by semicolons
Summary:
Simple statements are single-line instructions (assignment, print, etc.).
Compound statements control the flow using indentation and include blocks of
statements (like if, for).
Python uses indentation (spaces or tabs) to group statements in a block.
Tokens in Python:
Tokens are the smallest individual units in a Python program. The interpreter breaks
every line of code into these basic components before execution.
Types of Tokens in Python
1. Identifiers
Names used to identify variables, functions, classes, etc.
Must start with a letter or underscore (_), followed by letters, digits, or
underscores.
Example:
python
student_name = "Rita"
_age = 15
2. Keywords
Reserved words with special meaning, cannot be used as identifiers.
Example:
python
if True:
print("This is a keyword example.")
Here, if and True are keywords.
3. Operators
Symbols that perform operations—arithmetic, comparison, logical, etc.
Example:
python
sum = 4 + 5 # '+' is an addition operator
check = sum > 6 # '>' is a comparison operator
4. Literals (Constants)
Fixed values assigned to variables.
Example:
python
age = 16 # Integer literal
pi = 3.14 # Float literal
message = "Welcome!" # String literal
is_valid = True # Boolean literal
empty = None # None literal
5. Punctuators
Special symbols that organize and structure code, such as (), :, ,, {}, [].
Example:
python
def greet(name): # Parentheses () and colon :
print("Hello,", name)
list1 = [1, 2, 3] # Square brackets []
Summary Table
Token Type Example Purpose
Identifier score = 50 Variable/function names
Keyword if, for, else Reserved words
Operator +, >, == Mathematical or logical ops
Literal "hi", 7, 3.5 Direct value in code
Punctuator (), :, [], , Code structure
By understanding tokens, you can read, write, and debug Python code more
easily because you know how every piece is interpreted by the computer.
Identifiers:
An Identifier in Python is the name you give to variables,
functions, classes, or other objects to identify them in your code.
Rules for Naming Identifiers in Python:
Must begin with a letter (A-Z or a-z) or an underscore (_).
Can contain letters, digits (0-9), and underscores (_) after
the first character.
Cannot start with a digit.
Cannot be a Python
keyword (like if, for, while, True, None).
Are case-sensitive (Var and var are different).
Cannot contain special characters like @, #, !, -, or spaces.
No limit on length, but keep them readable and preferably
concise.
Examples of Valid Identifiers:
python
student_name = "Ravi"
_age = 21
totalSales = 3000
var123 = 50
Examples of Invalid Identifiers:
python
123var = 5 # Starts with a digit - invalid
@username = "Alex" # Contains special character '@' - invalid
if = 10 # 'if' is a keyword - invalid
total-sales = 500 # Contains hyphen '-' - invalid
user name = "Neha" # Contains space - invalid
Simple Usage Example:
python
# Valid identifiers
name = "Alice"
age = 25
_score = 90
print(name) # Output: Alice
print(age) # Output: 25
print(_score) # Output: 90
Additional Notes:
Leading underscore _var: by convention indicates "internal
use" or "private" in a module or class.
Double underscore __var: used in classes for name mangling
(advanced topic).
Avoid using Python keywords as identifiers to prevent errors.
This ensures your code is clear, error-free, and follows Python
conventions.
Related
What are the main rules for naming valid Python identifiers
How do Python's keywords differ from identifiers in usage
Why can't a Python identifier start with a number or contain
special characters
How does case sensitivity affect Python identifiers and their
naming
What are some best practices for choosing descriptive
identifiers in Python
Examples:
alid Identifiers
python
userName = "Sam" # Letters and capital: valid
age1 = 20 # Letters and digits, does not start with a digit: valid
_score = 15 # Starts with underscore: valid
total_sales = 500 # Underscores are allowed: valid
value123 = 7 # Letters and numbers: valid
Invalid Identifiers
python
1user = "Tom" # Starts with a digit: invalid
user-name = "Eve" # Hyphen is not allowed: invalid
if = 10 # 'if' is a Python keyword: invalid
user name = "Ana" # Space not allowed: invalid
@score = 20 # Special character '@' not allowed: invalid
Quick Test in Python
You can use the .isidentifier() method to check if a string is a valid identifier:
python
print("score1".isidentifier()) # True
print("1score".isidentifier()) # False
print("user-name".isidentifier()) # False
print("for".isidentifier()) # True (but 'for' is a keyword, so it's reserved)
Rules of Identifies:
Here are the main rules for identifiers in Python:
Start with a letter or underscore: Identifiers must begin with a letter (A–Z
or a–z) or an underscore (_). They cannot start with a digit.
Valid: name, _value
Invalid: 1st_number
Can contain letters, digits, and underscores: After the first character,
identifiers can include letters, digits (0–9), and underscores.
Valid: score1, data_2025
No special characters other than underscore: Identifiers cannot contain
symbols like @, #, $, %, spaces, or hyphens.
Invalid: user-name, user name, @score
Cannot be a Python keyword: Reserved words such as if, for, class, while,
etc., cannot be used as identifiers.
Case-sensitive: Identifiers are case-sensitive. For example, Total, total,
and TOTAL are all different.
No length limit (but readability matters): Technically, there’s no limit,
but identifiers should be reasonably short and descriptive.
Examples:
python
valid_id = 10 # Valid
Valid_ID = 20 # Valid (different from 'valid_id')
user2score = 15 # Valid
__hidden = 5 # Valid
2numbers = 7 # Invalid (starts with digit)
user-score = 8 # Invalid (hyphen not allowed)
if = 12 # Invalid (keyword)
my score = 50 # Invalid (space not allowed)
Keywords in Python
Keywords in Python are special reserved words that have a specific meaning and
purpose. They define the core language syntax and structure—these words cannot
be used as variable names, function names, or any other identifiers.
Keywords are case-sensitive and must be written exactly as defined.
Key Points About Python Keywords
Reserved for special functions by the language.
Using a keyword as a name will cause a syntax error.
Most keywords are in lowercase, except True, False, and None.
List of Python Keywords (as of July 2025)
Below is the latest official list of Python keywords. You can get this list in any Python
interpreter by running:
python
import keyword
print(keyword.kwlist)
List:
False await Else import
None break except in
True class finally is
And continue For lambda
As def from nonlocal
Assert del global not
Async elif If or
Pass raise return try
While with yield
Usage Example
Trying to use a keyword as a variable name causes an error:
python
if = 5 # ❌ This will cause a syntax error because 'if' is a keyword.
But using them properly is essential:
python
for i in range(3):
print(i)
if True:
print("This is a keyword example.")
Learning Tip
If you’re not sure whether a word is a keyword, you can check using:
python
import keyword
print(keyword.iskeyword("while")) # Output: True
This list is up-to-date for Python 3.11/3.12 (as of 2025) and covers what every
beginner should know about Python keywords.
Related
How many keywords are currently reserved in the latest Python version
What are the most commonly used Python keywords in everyday coding
How can I check if a word is a Python keyword in my code
Why are certain words like 'and' and 'or' considered keywords in Python
How do Python keywords differ across Python 2 and Python 3 versions
Keywords in Python:
Python has several types of operators that allow you to perform operations on values
and variables. Here is a concise overview of the main Python operator types with
examples:
1. Arithmetic Operators
Perform basic mathematical calculations.
Operator Meaning Example Outpu
t
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 5/2 2.5
// Floor division 5 // 2 2
% Modulus (remainder) 5%2 1
** Exponentiation 2 ** 3 8
Example:
python
a = 15
b=4
print(a + b) # 19
print(a - b) # 11
print(a * b) # 60
print(a / b) # 3.75
print(a // b) # 3
print(a % b) # 3
print(a ** b) # 50625
2. Assignment Operators
Assign values to variables and perform operations simultaneously.
Operator Meaning Equivalent to Exampl
e
= Assign x=5 x=5
+= Add and assign x=x+3 x += 3
-= Subtract and assign x=x-3 x -= 3
*= Multiply and assign x=x*3 x *= 3
/= Divide and assign x=x/3 x /= 3
%= Modulus and assign x=x%3 x %= 3
//= Floor divide and assign x = x // 3 x //= 3
**= Exponentiate and assign x = x ** 2 x **= 2
Example:
python
x=5
x += 3
print(x) # 8
3. Comparison Operators
Compare two values; the result is a boolean (True or False).
Operator Meaning Example Outpu
t
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 3<5 True
>= Greater than or equal 5 >= 3 True
<= Less than or equal 3 <= 3 True
Example:
python
print(10 == 10) # True
print(7 != 5) # True
print(10 > 5) # True
print(2 < 5) # True
print(10 >= 10) # True
print(3 <= 4) # True
4. Logical Operators
Combine boolean expressions.
Operator Meaning Example Outpu
t
and True if both true True and False False
or True if at least one true True or False True
not Invert boolean value not True False
Example:
python
a, b = True, False
print(a and b) # False
print(a or b) # True
print(not a) # False
5. Bitwise Operators
Operate at the binary level on integers.
Operator Meaning Example Output
& Bitwise AND 10 & 7 2
| Bitwise OR 10 | 7 15
^ Bitwise XOR 10 ^ 7 13
~ Bitwise NOT ~10 -11
<< Left shift 10 << 2 40
Operator Meaning Example Output
>> Right shift 10 >> 1 5
Example:
python
a = 10 # 1010 in binary
b = 7 # 0111 in binary
print(a & b) # 2
print(a | b) # 15
print(a ^ b) # 13
print(~a) # -11
print(a << 2) # 40
print(a >> 1) # 5
6. Membership Operators
Test if a value is present in a sequence.
Operator Meaning Example Outpu
t
in True if value is in sequence 'a' in 'apple' True
True if value is NOT in
not in sequence 3 not in True
Example:
python
print('a' in 'banana') # True
print(10 not in [2, 4, 6]) # True
7. Identity Operators
Check if two variables refer to the same object in memory.
Operator Meaning Example Output
True/
is True if both are the same a is b False
True/
is not True if not the same a is not b False
Example:
python
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(a is b) # True
print(a is c) # False (same values but different objects)
print(a is not c) # True
These operator categories cover almost all the operations you’ll typically need in
Python programming. Each is illustrated with simple usage examples to help
understanding.
Punctuators in Python and list of Punctuator
Punctuators in Python
Punctuators (or punctuation symbols) in Python are special characters that
organize and structure code. They mark the boundaries of statements, separate
elements, and affect the way the interpreter reads the program. Punctuators
do not perform computations (unlike operators), but they are crucial for the correct
syntax and structure of Python code.
List of Common Punctuators in Python
Punctuator Name/Use Example Usage
Function calls,
() Parentheses grouping: print(x)
[] Square brackets Lists, indexing/slicing: a
{} Braces/Curly brackets Dictionaries, sets: {"a":1}
Block start (loops, functions): if
: Colon x:, Dicts: {"a":1}
, Comma Separates items: a, b, c
Access
. Dot/Period attributes: object.method()
Separate multiple
; Semicolon statements: x=2; y=3
= Assignment operator Assignment: x = 5
== Equality operator Comparison: x == 5
Compound assignment
+=, -=, ... punctuators x += 2
Punctuator Name/Use Example Usage
@ Decorators @staticmethod
# Comment symbol # This is a comment
' ", """ Quotes String delimiters: 'hi', "hi"
Backslash (escape, line
\ continuation) \", \\, or to break lines
Backtick (used for repr in Python
` 2) Not commonly used in Python 3
These are most frequently encountered in Python.
Examples of Punctuators in Action
python
# Using parentheses, colon, and indentation for function definition
def greet(name):
print("Hello,", name) # Parentheses and comma
# List with square brackets, values separated by commas
my_list = [1, 2, 3]
# Dictionary with curly braces, colon and commas
my_dict = {'a': 10, 'b': 20}
# Accessing an attribute of a string object
word = "python"
print(word.upper())
# Using the hash for comments
# This line won't be executed
# Using the at symbol for decorators
@staticmethod
def my_function():
pass
# Backslash for line continuation
x=1+2+3+\
4+5
# Using quotes
str1 = "Hello"
str2 = 'World'
# Semicolon to write multiple statements in one line
a = 1; b = 2; print(a + b)
Summary Table
Symbol(s) Describes Typical Usage Example
func(x); grouping
() Parentheses expressions
Symbol(s) Describes Typical Usage Example
[] Square brackets lst, [1][4][2]
{} Curly braces {"a":1}, {1,2}
: Colon def f():, if x > 0:
, Comma print(a, b), lists/tuples
. Dot obj.attr, module.func()
; Semicolon x=1; y=2
= Assignment x=5
==, !=, etc. Comparison/assignment if x == y:
@ Decorator @classmethod
# Comment # Comment
' ", """ Quotes (string delimiters) 'a', "b", """c"""
"newline:\n"; line
\ Backslash continuation
` Backtick (Python 2) Legacy use (not in Py3)
Note: Some symbols (like +, -, *) are both operators and, in technical
categorization, can also appear as punctuators in some contexts, but are mainly
treated as operators in Python. Punctuators are essential for code structure and
forming Python syntax.
If you need detailed usage examples for any specific punctuator, let me know!
Related
What are the main categories of punctuators in Python and their functions
How do Python punctuators compare to those in C or C++
Why is string.punctuation useful in text processing tasks
How do context and placement affect the role of punctuators in Python
What are some less common punctuators in Python and their usage chances
Literals in Python
A literal in Python is a fixed value written directly in the source code. It represents
data that does not change during program execution. Python supports several types
of literals, each representing different kinds of data.
Common Types of Literals in Python with Examples:
1. Numeric Literals
Represent numbers of various types:
Integer literals: Whole numbers without a decimal point.
python
a = 10
b = -25
Floating-point literals: Numbers with decimal points.
python
c = 3.14
d = -0.01
Complex literals: Numbers with a real and imaginary part, where the
imaginary part is denoted by j.
python
e = 5 + 2j
f = -3j
2. String Literals
Text enclosed in quotes.
Single quotes:
python
s1 = 'Hello'
Double quotes:
python
s2 = "Python"
Triple quotes (for multi-line strings):
python
s3 = '''This is
a multi-line
string'''
Raw strings (ignore escape sequences):
python
s4 = r"C:\Users\Name"
3. Boolean Literals
Represent truth values:
python
flag1 = True
flag2 = False
4. Collection Literals
Literals representing collection data types:
List:
python
lst = [1, 2, 3]
Tuple:
python
tpl = (1, 2, 3)
Dictionary:
python
d = {"name": "Alice", "age": 30}
Set:
python
st = {1, 2, 3}
5. Special Literal
None represents the absence of value or a null value:
python
n = None
Example showing different literals:
python
# Numeric literals
num_int = 100
num_float = 3.14
num_complex = 2 + 3j
# String literals
greeting = "Hello"
multiline = '''This is
a multi-line string'''
# Boolean literals
is_valid = True
is_done = False
# Collection literals
fruits = ["apple", "banana", "cherry"] # list
coordinates = (10, 20) # tuple
person = {"name": "John", "age": 25} # dictionary
unique_numbers = {1, 2, 3} # set
# Special literal
nothing = None
print(num_int, num_float, num_complex)
print(greeting)
print(multiline)
print(is_valid, is_done)
print(fruits, coordinates, person, unique_numbers)
print(nothing)
Output:
text
100 3.14 (2+3j)
Hello
This is
a multi-line string
True False
['apple', 'banana', 'cherry'] (10, 20) {'name': 'John', 'age': 25} {1, 2, 3}
None
Summary:
Literals are fixed values used in code like numbers, text, booleans,
collections, or None.
They are the basic data you'll use in Python programs and help represent
information directly.