Chapter 2: Python Syntax and Fundamentals
Variables and Data Types (click on the it to learn in detail)
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
andname
are different).
Example:
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
is_valid = True # Boolean
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:
var = 5 # Initially an integer var = "text" # Now a string
Potential Misunderstanding:
Assigning a value to a reserved keyword (e.g.,
if = 5
) will result in a syntax error. Usehelp("keywords")
in Python to list reserved keywords.
Input and Output
The input()
function allows you to take input from the user, while the print()
function outputs data to the screen.
Input Example:
name = input("What is your name? ")
print("Hello, " + name + "! Welcome to Python.")
Notes on input()
:
By default,
input()
returns data as a string.You may need to cast the input to another type, e.g.,
age = int(input("Enter your age: "))
Print Formatting:
The print()
function supports string concatenation and formatted output:
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}") # f-string formatting
Comments and Code Style
Python uses comments to make code more understandable. It also follows the PEP 8 style guide to maintain consistency.
Comment Examples:
# This is a single-line comment
"""
This is a multi-line comment
used for longer explanations.
"""
Code Style Best Practices:
Use 4 spaces for indentation (do not mix tabs and spaces).
Limit lines to 79 characters.
Use descriptive names for variables and functions.
Operators
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:
x = 10
y = 3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
print(x / y) # Division: 3.33
print(x % y) # Modulus: 1
print(x ** y) # Exponentiation: 1000
print(x // y) # Floor Division: 3
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:
x = 5
y = 3
print(x == y) # Equal to: False
print(x != y) # Not equal to: True
print(x > y) # Greater than: True
print(x < y) # Less than: False
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:
x = True
y = False
print(x and y) # Logical AND: False
print(x or y) # Logical OR: True
print(not x) # Logical NOT: False
Notes on Operators:
Be careful with operator precedence. For example, multiplication takes precedence over addition:
result = 2 + 3 * 4 # Result is 14, not 20
Exercises
Exercise 1:
Write a program that takes your name and age as input and prints a greeting.
Sample Output:
What is your name? Alice
How old are you? 25
Hello Alice! You are 25 years old.
Solution:
name = input("What is your name? ")
age = input("How old are you? ")
print(f"Hello {name}! You are {age} years old.")
Exercise 2:
Write a program that takes two numbers as input and prints their sum, difference, product, and quotient.
Solution:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)
print("Quotient:", num1 / num2)
With these fundamentals in place, you’re ready to explore control flow in Python, which we will cover in the next chapter.
Last updated