Chapter 2: Python Syntax and Fundamentals
Last updated
Last updated
Python is dynamically typed, which means you don’t have to declare a variable’s type explicitly. A variable can hold different types of data like numbers, strings, and more. Variables are essentially reserved memory locations to store values.
Rules for Naming Variables:
Variable names must start with a letter or an underscore (_
).
They cannot start with a number.
Variable names can only contain alphanumeric characters and underscores (A-Z
, a-z
, 0-9
, _
).
Variable names are case-sensitive (Name
and name
are different).
Example:
Notes:
Variables do not need to be declared with a type; Python infers the type based on the value assigned.
Reassigning a variable changes its type dynamically:
Assigning a value to a reserved keyword (e.g., if = 5
) will result in a syntax error. Use help("keywords")
in Python to list reserved keywords.
The input()
function allows you to take input from the user, while the print()
function outputs data to the screen.
Input Example:
Notes on input()
:
By default, input()
returns data as a string.
You may need to cast the input to another type, e.g.,
Print Formatting:
The print()
function supports string concatenation and formatted output:
Python uses comments to make code more understandable. It also follows the PEP 8 style guide to maintain consistency.
Comment Examples:
Use 4 spaces for indentation (do not mix tabs and spaces).
Limit lines to 79 characters.
Use descriptive names for variables and functions.
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations:
Operator
Name
Example
+
Addition
5 + 3
equals 8
-
Subtraction
5 - 3
equals 2
*
Multiplication
5 * 3
equals 15
/
Division
5 / 3
equals 1.67
//
Floor Division
5 // 3
equals 1
%
Modulus
5 % 3
equals 2
**
Exponentiation
2 ** 3
equals 8
Example Code:
Comparison Operators
Comparison operators are used to compare values and return a Boolean (True
or False
):
Operator
Name
Example
==
Equal to
5 == 3
equals False
!=
Not equal to
5 != 3
equals True
>
Greater than
5 > 3
equals True
<
Less than
5 < 3
equals False
>=
Greater or equal
5 >= 3
equals True
<=
Less or equal
5 <= 3
equals False
Example Code:
Logical Operators
Logical operators are used to combine conditional statements:
Operator
Name
Example
and
Logical AND
True and False
= False
or
Logical OR
True or False
= True
not
Logical NOT
not True
= False
Example Code:
Notes on Operators:
Be careful with operator precedence. For example, multiplication takes precedence over addition:
Exercise 1:
Write a program that takes your name and age as input and prints a greeting.
Sample Output:
Solution:
Exercise 2:
Write a program that takes two numbers as input and prints their sum, difference, product, and quotient.
Solution:
With these fundamentals in place, you’re ready to explore control flow in Python, which we will cover in the next chapter.