1.2 Python Core Syntax & Variables
Python Core Syntax & Variables
Python has a simple and readable syntax, making it suitable for beginners as well as professional applications such as Data Science, Automation, Artificial Intelligence, Web Development, and Scientific Computing.
Before working with NumPy, pandas, automation scripts, or machine-learning libraries, you should understand Python's core syntax, variables, data types, input, output, and basic built-in functions.
- Python syntax and indentation
- Variables and assignment
- Dynamic typing
- Python naming conventions
- Basic built-in functions
- Taking input using
input() - Displaying output using
print() - Type conversion
- Formatted output
- Common syntax mistakes
1. Understanding Python Syntax
Syntax refers to the rules that determine how Python statements must be written.
Python is designed to be readable. Unlike some programming languages, Python uses indentation to define blocks of code.
Simple Python Statement
print("Hello, Python!")
The statement calls the built-in print() function and
displays text on the screen.
Another Example
name = "Alex"
print(name)
Here, the string "Alex" is assigned to the variable
name, which is then displayed.
2. Python Indentation
Python uses indentation to identify blocks of code. This is one of the most important syntax rules beginners must understand.
Correct Indentation
age = 20
if age >= 18:
print("Adult")
The indented print() statement belongs to the
if block.
Incorrect Indentation
age = 20
if age >= 18:
print("Adult")
This produces an indentation-related error because the body of
the if statement is not properly indented.
Use consistent indentation. The conventional style for Python code is 4 spaces per indentation level.
3. Comments in Python
Comments are notes written inside source code for humans. Python ignores comments during normal execution.
Single-Line Comment
# Calculate the average score
score = 85
Comment After Code
score = 85 # Student score
Comments are useful for explaining complex logic, documenting assumptions, and making code easier to maintain.
4. What Is a Variable?
A variable is a name that refers to a value or object in a Python program.
Python variables are created when a value is assigned to a name.
name = "Alex"
age = 21
score = 87.5
In this example:
-
namerefers to a string. -
agerefers to an integer. -
scorerefers to a floating-point number.
5. Variable Assignment
The assignment operator = assigns a value to a
variable.
city = "London"
marks = 92
percentage = 92.5
Assignment is different from mathematical equality. The statement:
x = 10
means that the value 10 is assigned to
x.
Updating a Variable
count = 10
count = 20
print(count)
Output:
20
6. Multiple Assignment
Python allows multiple variables to be assigned in a single statement.
name, age, score = "Alex", 21, 88
The equivalent individual assignments would be:
name = "Alex"
age = 21
score = 88
Assigning the Same Value
x = y = z = 0
All three variables refer to the assigned value.
7. Dynamic Typing in Python
Python is a dynamically typed language. You do not normally have to declare the data type of a variable before assigning a value to it.
value = 100
print(value)
The variable can later refer to an object of another type:
value = 100
value = "Python"
print(value)
The same variable name can therefore be rebound to an object of a different type.
| Language Characteristic | Python |
|---|---|
| Type declaration required before assignment? | Generally no. |
| Type determined at runtime? | Yes. |
| Can a name be rebound to another type? | Yes. |
8. Checking the Type of a Value
The built-in type() function can be used to inspect
the type of an object.
age = 21
print(type(age))
Output will indicate that the value is an integer.
More Examples
name = "Alex"
price = 99.50
active = True
print(type(name))
print(type(price))
print(type(active))
Typical results are:
<class 'str'>
<class 'float'>
<class 'bool'>
9. Python Identifiers
An identifier is a name used to identify a variable, function, class, module, or other program entity.
Valid Identifiers
student_name
total_marks
score1
_age
data_2026
Invalid Identifiers
2students
student-name
total marks
class
These are invalid for different reasons, including starting with a digit, using an operator, containing spaces, or using a reserved keyword.
10. Rules for Naming Variables
- A variable name may contain letters, digits, and underscores.
- It cannot begin with a digit.
- Spaces are not allowed.
-
Special characters such as
-and@should not be used in identifiers. - Python keywords cannot be used as ordinary variable names.
- Python identifiers are case-sensitive.
Case Sensitivity
name = "Alex"
Name = "Jordan"
print(name)
print(Name)
name and Name are different identifiers.
11. Python Naming Conventions
Python programmers commonly follow the naming conventions described by PEP 8.
| Entity | Recommended Style | Example |
|---|---|---|
| Variable | snake_case | student_name |
| Function | snake_case | calculate_total() |
| Constant | UPPER_CASE | MAX_RETRIES |
| Class | PascalCase | StudentRecord |
Good Naming
student_count = 50
average_score = 84.5
maximum_attempts = 3
Poor Naming
x = 50
a = 84.5
m = 3
Short names are sometimes appropriate for small local calculations, but meaningful names generally improve readability.
12. Python Built-in Functions
Python provides many functions that can be used without importing an external library.
| Function | Purpose | Example |
|---|---|---|
print() |
Displays output. |
print("Hello")
|
input() |
Reads user input as text. |
input("Name: ")
|
type() |
Returns the type of an object. |
type(10)
|
len() |
Returns the number of items in a supported object. |
len("Python")
|
sum() |
Adds values from an iterable. |
sum([10, 20, 30])
|
max() |
Returns the largest value. |
max([10, 30, 20])
|
min() |
Returns the smallest value. |
min([10, 30, 20])
|
round() |
Rounds a number according to the specified precision. |
round(12.567, 2)
|
13. Displaying Output with print()
The print() function displays values or text.
print("Hello, Python!")
print(100)
print(25 + 15)
Output:
Hello, Python!
100
40
Printing Multiple Values
name = "Alex"
score = 92
print(name, score)
By default, print() separates multiple arguments with
a space.
14. sep and end in print()
The print() function provides optional parameters
that allow you to control formatting.
Using sep
print("2026", "08", "23", sep="-")
Output:
2026-08-23
Using end
print("Hello", end=" ")
print("World")
Output:
Hello World
15. Taking Input with input()
The input() function allows a program to receive
information entered by the user.
name = input("Enter your name: ")
print("Hello", name)
If the user enters:
Alex
the program can display:
Hello Alex
input() returns the user's input as a
string.
16. Type Conversion
When numeric input is required, the string returned by
input() usually needs to be converted to the
appropriate numeric type.
Convert to Integer
age = int(input("Enter your age: "))
print(age)
Convert to Float
price = float(input("Enter the price: "))
print(price)
Convert to String
number = 100
text = str(number)
print(text)
| Function | Conversion |
|---|---|
int() |
Converts a compatible value to an integer. |
float() |
Converts a compatible value to a floating-point number. |
str() |
Converts a value to a string representation. |
bool() |
Converts a value to a Boolean value according to Python's truth-value rules. |
17. Formatted Output
Python provides several ways to format output. For modern Python programs, f-strings are usually the most convenient approach.
Basic f-string
name = "Alex"
score = 92
print(f"{name} scored {score} marks.")
Output:
Alex scored 92 marks.
Expression Inside an f-string
a = 10
b = 20
print(f"Total = {a + b}")
Output:
Total = 30
18. Formatting Numbers
f-strings can also control numeric formatting.
Two Decimal Places
price = 125.6789
print(f"Price: {price:.2f}")
Output:
Price: 125.68
Percentage Formatting
accuracy = 0.956
print(f"Accuracy: {accuracy:.1%}")
Output:
Accuracy: 95.6%
19. Combining Strings
Strings can be combined using the + operator.
first_name = "Alex"
last_name = "Morgan"
full_name = first_name + " " + last_name
print(full_name)
Output:
Alex Morgan
For readable output containing several variables,
f-strings are usually clearer than repeatedly concatenating
strings with +.
20. Variables in Calculations
Variables can participate in arithmetic expressions.
length = 10
width = 5
area = length * width
print(f"Area = {area}")
Output:
Area = 50
Data Science Example
total_sales = 125000
number_of_orders = 250
average_order_value = total_sales / number_of_orders
print(f"Average order value: {average_order_value:.2f}")
This type of calculation is common in Data Science and business analytics.
21. Swapping Variables
Python provides a concise way to swap two variable values.
a = 10
b = 20
a, b = b, a
print(a)
print(b)
Output:
20
10
No temporary variable is required.
22. Constants in Python
Python does not enforce immutable constants through a special variable declaration keyword. Instead, programmers commonly use uppercase names to indicate that a value should be treated as a constant.
PI = 3.141592653589793
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
These names communicate intent to other developers.
23. Useful Built-in Function Examples
len()
course = "Python"
print(len(course))
Output:
6
sum()
scores = [80, 90, 75, 95]
print(sum(scores))
Output:
340
max() and min()
scores = [80, 90, 75, 95]
print(max(scores))
print(min(scores))
Output:
95
75
round()
value = 87.45678
print(round(value, 2))
Output:
87.46
24. Python Keywords
Python has reserved words with predefined meanings. They cannot normally be used as ordinary identifiers.
Examples
if
else
for
while
def
class
return
import
try
except
True
False
None
For example, this is invalid:
class = "Python"
because class is a Python keyword.
25. Finding Python Keywords Programmatically
Python provides the keyword module for inspecting
reserved keywords.
import keyword
print(keyword.kwlist)
This displays the keywords recognised by the Python interpreter.
26. Common Beginner Syntax Errors
| Error | Problem | Correct Approach |
|---|---|---|
| Missing colon |
Block statement does not end with :.
|
Add the required colon. |
| Wrong indentation | Code block is not aligned correctly. | Use consistent indentation. |
| Unclosed string | Opening quotation mark has no matching closing quotation mark. | Close the string correctly. |
| Invalid identifier | Variable name violates Python's identifier rules. | Rename the variable. |
| Using a keyword as a variable | Reserved Python word used as an identifier. | Choose another name. |
27. Mini Project — Student Score Calculator
Create a small Python program that accepts three subject scores and calculates the total and average.
name = input("Enter student name: ")
maths = float(input("Enter Mathematics score: "))
science = float(input("Enter Science score: "))
english = float(input("Enter English score: "))
total = maths + science + english
average = total / 3
print()
print(f"Student: {name}")
print(f"Total: {total:.2f}")
print(f"Average: {average:.2f}")
Skills Practised
- Variables
- Input
- Type conversion
- Arithmetic operations
- f-string formatting
- Basic program structure
28. Why These Basics Matter in Data Science
Data Science libraries automate many complex operations, but Python fundamentals remain essential.
| Python Concept | Data Science Application |
|---|---|
| Variables | Store datasets, measurements, configuration values, and calculated results. |
| Input / Output | Build interactive analysis and automation tools. |
| Functions | Reuse data-processing logic. |
| Loops | Process repeated tasks and records. |
| Conditions | Apply rules and classification logic. |
| Data Types | Determine how values can be processed. |
| Exceptions | Handle errors during data processing and automation. |
29. Python Interview Questions
Q1. What does dynamically typed mean in Python?
View Answer
Python determines the type of an object at runtime, and a variable name can be rebound to objects of different types.
Q2. What is the difference between = and
==?
View Answer
= is the assignment operator, while
== tests whether two values compare equal.
Q3. What does input() return?
View Answer
It returns the user's entered data as a string. Numeric
input generally needs explicit conversion using functions
such as int() or float().
Q4. Why is indentation important in Python?
View Answer
Python uses indentation to define code blocks. Incorrect indentation can change the structure of the program or produce an error.
Q5. What is PEP 8?
View Answer
PEP 8 is the principal Python style guide that provides recommendations for writing readable and consistent Python code.
30. Examination Questions
Multiple Choice Questions
Q1. Which symbol is used for assignment in Python?
===:=:<-
Answer: B — =
Q2. What is returned by input() by default?
- Integer
- Float
- String
- Boolean
Answer: C — String
Q3. Which function can be used to determine an object's type?
datatype()typeof()type()kind()
Answer: C — type()
Q4. Which is a valid Python variable name?
2scorestudent-namestudent_namestudent name
Answer: C — student_name
Short Answer Questions
- Explain dynamic typing in Python.
- State four rules for naming Python identifiers.
-
Differentiate between
int()andfloat(). - What is the purpose of f-strings?
- Explain the importance of indentation in Python.
31. Practical Challenge
Build a Simple Expense Calculator
Write a Python program that:
- Asks the user for their name.
- Accepts the cost of three expenses.
- Calculates the total expense.
- Calculates the average expense.
- Displays the result using f-string formatting.
Challenge: Format all monetary values to two decimal places.
32. Python Core Syntax Quick Reference
| Task | Syntax / Example |
|---|---|
| Assign variable |
age = 21
|
| Print output |
print("Hello")
|
| Take input |
name = input("Name: ")
|
| Convert to integer |
int(value)
|
| Convert to float |
float(value)
|
| Convert to string |
str(value)
|
| Check type |
type(value)
|
| Count items |
len(value)
|
| Formatted output |
f"Score: {score}"
|
| Round number |
round(value, 2)
|
33. Key Takeaways
- Python uses readable syntax and indentation to structure code.
- Variables are created through assignment.
- Python uses dynamic typing.
- Identifiers are case-sensitive.
- Meaningful variable names improve code readability.
-
input()returns a string. -
Use
int()orfloat()when numeric input is required. -
print()displays output and supports formatting options such assepandend. - f-strings provide a clean way to create formatted output.
-
Built-in functions such as
len(),sum(),min(), andmax()are useful throughout Data Science.
Write Python code for humans first: use meaningful names, consistent indentation, clear formatting, and simple structure. Readable code is easier to debug, automate, analyse, and maintain.