Session 2: Python Syntax, Data Types, & Variables
Session Objectives
By the end of this class, you will be able to:
● Understand and use variables to store data.
● Follow Python's syntax and naming conventions.
● Differentiate between key data types (Strings, Integers, Floats, Booleans).
● Use comments to document and explain your code.
● Get basic input from a user using the input() function.
Part 1: Variables, Assignment, and Syntax
1. What are Variables?
A variable is a container for storing a data value. Think of it as a labeled box where you can
put information. In Python, you create a variable the moment you first assign a value to it.
The single equals sign (=) is the assignment operator. It "assigns" the value on the right to
the variable on the left.
Syntax: variable_name = value
Code Example 1:
# Assigning a string value to a variable named 'greeting'
greeting = "Hello, world!"
# Assigning a number value to a variable named 'student_count'
student_count = 30
# We can print the value by printing the variable
print(greeting)
print(student_count)
# We can also change (re-assign) the value in a variable
student_count = 35
print("The new student count is:", student_count)
2. Python Identifiers & Naming Conventions
An identifier is the name you give to things like variables and, later, functions.
Rules for Identifiers:
1. Must start with a letter (a-z, A-Z) or an underscore (_).
2. Cannot start with a number.
3. Can only contain alpha-numeric characters (A-z, 0-9) and underscores.
4. Identifiers are case-sensitive (age, Age, and AGE are three different variables).
Naming Conventions (Best Practices): These are not rules (the code will run), but they are
strong recommendations for readable code. The standard convention for Python variables is
snake_case:
● All lowercase.
● Words are separated by underscores.
5
Code Example 2:
# GOOD variable names (snake_case convention)
first_name = "Aisha"
user_age = 25
_temporary_value = 100
# BAD variable names (will cause errors)
# 2_users = 2 # Error: Cannot start with a number
# user-email = "a@[Link]" # Error: Cannot use hyphens
# my var = "test" # Error: Cannot use spaces
# Case-Sensitivity Example
fruit = "Apple"
Fruit = "Orange"
print(fruit) # Output: Apple
print(Fruit) # Output: Orange
3. Python Reserved Words
These are special words that have meaning in Python. You cannot use them as variable
names. Examples include: if, else, for, while, True, False, None.
4. Comments
Comments are notes for humans that Python completely ignores. They are essential for
explaining why your code does something.
● Single-line comments start with #.
● Multi-line comments can be enclosed in triple quotes """...""" or '''...'''.
Code Example 3:
# This is a single-line comment.
# It explains that the next line calculates a price.
price = 10.0
tax_rate = 0.05
"""
This is a multi-line comment.
We will use it to calculate the final total
by adding the tax to the base price.
"""
total = price + (price * tax_rate)
print(total) # This line prints the final total
# print("This line is 'commented out' and will not run.")
6
Part 2: Python Data Types
Data Types are classifications for different kinds of data. Python is dynamically-typed,
meaning you don't have to declare the type; Python figures it out from the value.
We can check the type of any variable using the built-in type() function.
1. Text Type: String (str)
● Used for text.
● Created by enclosing characters in either single quotes ('...') or double quotes ("...").
Code Example 4:
single_quoted_string = 'Hello, Python!'
double_quoted_string = "My name is John."
# You can use one type of quote inside the other
message = "He said, 'Python is easy!'"
print(message)
print( type(message) ) # Output: <class 'str'>
2. Numeric Types: Integer (int) and Float (float)
● Integer (int): Whole numbers (positive, negative, or zero) without decimals.
● Float (float): Numbers with decimal points (floating-point numbers).
Code Example 5:
# Integer (int)
my_age = 30
temperature = -5
print( type(my_age) ) # Output: <class 'int'>
# Float (float)
gpa = 3.85
pi_value = 3.14159
print( type(gpa) ) # Output: <class 'float'>
3. Boolean Type (bool)
● Used for logical values.
● Can only be one of two values: True or False. (Note the capital letters!)
● Extremely important for conditions and decision-making.
Code Example 6:
is_student = True
is_admin = False
print("Is student?", is_student)
print( type(is_admin) ) # Output: <class 'bool'>
# Booleans are often the result of comparisons
print(10 > 5) # Output: True
print(2 == 3) # Output: False
7
4. The None Type (NoneType)
● A special data type that represents the absence of a value or a null value.
● It's often used as a placeholder before a variable is assigned a real value.
Code Example 7:
middle_name = None
print(middle_name)
print( type(middle_name) ) # Output: <class 'NoneType'>
Part 3: Practical Exercise: input() and Type Casting
Let's make our code interactive!
● We can get input from the user with the input() function.
● CRITICAL: The input() function always returns the data as a string (str), even if the
user types a number.
● If we want to use that input as a number, we must cast (convert) it.
● We use functions like int(), float(), and str() to convert between types.
Code Example 8 (Putting it all together):
# 1. Get user's name (this will be a string)
user_name = input("What is your name? ")
# 2. Get user's age (this will also be a string!)
age_string = input("How old are you? ")
# 3. Check the types
print("Type of user_name:", type(user_name))
print("Type of age_string:", type(age_string))
# 4. Convert the age_string to an integer
user_age = int(age_string)
# 5. Now we can do math with it
age_in_five_years = user_age + 5
# 6. Print a final message
# We must cast the integer back to a string (str) to join it
print("Hello, " + user_name + ". You are " + str(user_age) + " years old.")
print("In five years, you will be " + str(age_in_five_years) + " years old.")
8
Session 3: String & Number Operations
Session Objectives
By the end of this class, you will be able to:
● Perform mathematical calculations using Python's Arithmetic Operators.
● Understand and apply the Order of Operations (PEMDAS).
● Manipulate text using string operations and common String Methods.
● Compare values using Comparison Operators.
● Combine logical conditions using Boolean Operators.
● Explicitly convert data between types using Casting.
Part 1: Number Operations
This part covers how to work with numeric data types like int (integers) and float (decimal
numbers).
1. Arithmetic Operators
These are the basic mathematical operators you use to perform calculations.
Operator Name Description Example Result
+ Addition Adds two numbers 10 + 3 13
- Subtraction Subtracts one number from another 10 - 3 7
* Multiplication Multiplies two numbers 10 * 3 30
/ Division Divides one number by another (always 10 / 3 3.333..
results in a float) .
// Floor Divides and "floors" (rounds down) to 10 // 3 3
Division the nearest integer
% Modulos Returns the remainder of the division 10 % 3 1
** Exponent Raises a number to the power of another 10 ** 3 1000
2. Order of Operations (PEMDAS)
Python follows the standard mathematical order of operations. A common acronym is
PEMDAS:
1. Parentheses ()
2. Exponents **
3. Multiplication *, Division /, Floor Division //, Modulo % (from left to right)
4. Addition +, Subtraction - (from left to right)
9
Code Example 1:
# Without parentheses
# 2 * 3 is 6, then 5 + 6 is 11
result_1 = 5 + 2 * 3
print(f"Result 1: {result_1}") # Output: 11
# With parentheses
# 5 + 2 is 7, then 7 * 3 is 21
result_2 = (5 + 2) * 3
print(f"Result 2: {result_2}") # Output: 21
# Complex example
# 1. 4**2 = 16
# 2. 16 / 8 = 2.0
# 3. 10 + 2.0 - 1 = 11.0
result_3 = 10 + 4 ** 2 / 8 - 1
print(f"Result 3: {result_3}") # Output: 11.0
Part 2: String Operations & Methods
This part covers how to work with string (str) data.
1. String Values & Operations
Strings can be "added" together (Concatenation) and "multiplied" by an integer (Repetition).
Code Example 2:
first_name = "Chowdhury"
last_name = "Mehedi"
# Concatenation (+)
# We add a space " " in the middle
full_name = first_name + " " + last_name
print(f"Full Name: {full_name}") # Output: Chowdhury Mehedi
# Repetition (*)
line = "-" * 20
print(line) # Output: --------------------
2. Common String Methods
Methods are special functions that "belong" to an object (like a string). They let you perform
common actions on the string's value.
Syntax: variable_name.method_name()
Code Example 3:
message = " Hello, Welcome to Python! "
# .strip() - Removes whitespace from the beginning and end
print(f"Stripped: '{[Link]()}'")
# .lower() - Converts to all lowercase
print(f"Lower: {[Link]()}")
# .upper() - Converts to all uppercase
10
print(f"Upper: {[Link]()}")
# .replace(old, new) - Replaces a substring with a new one
print(f"Replaced: {[Link]('Python', 'Django')}")
# .find(substring) - Returns the index (position) of the first occurrence
print(f"Find 'Welcome': {[Link]('Welcome')}")
3. Modern String Formatting (f-strings)
The easiest way to put variables inside strings is by using f-strings.
● Start the string with an f (before the quotes).
● Put your variables inside curly braces {}.
Code Example 4:
name = "Aisha"
session = 3
# The old, difficult way (using + and casting)
old_way = "Hello, " + name + ". Welcome to session " + str(session) + "."
# The new, clean f-string way
new_way = f"Hello, {name}. Welcome to session {session}."
print(old_way)
print(new_way)
Part 3: Comparison, Logic, and Casting
1. Comparison Operators
These operators compare two values and always return a Boolean (True or False). This is
essential for making decisions.
Operator Name Example Result
== Equal to 10 == 10 True
!= Not equal to 10 != 5 True
> Greater than 10 > 5 True
< Less than 10 < 5 False
>= Greater than or equal to 10 >= 10 True
<= Less than or equal to 10 <= 5 False
Note: == (comparison) is different from = (assignment).
11
2. Logical (Boolean) Operators
These operators are used to combine or invert True/False values.
● and: Both sides must be True for the result to be True.
● or: At least one side must be True for the result to be True.
● not: Inverts the value (True becomes False, False becomes True).
Code Example 5:
age = 25
is_student = True
# and: Must be older than 18 AND a student
can_get_discount = (age > 18) and (is_student == True)
print(f"Can get discount: {can_get_discount}") # Output: True
# or: Must be under 18 OR a student
age = 70
is_student = False
can_enter_free = (age < 18) or (age > 65)
print(f"Can enter free: {can_enter_free}") # Output: True (because age > 65)
# not
is_raining = False
can_go_outside = not is_raining
print(f"Can go outside: {can_go_outside}") # Output: True
3. Casting (Type Conversion)
Casting is how we manually convert a variable from one data type to another. This is crucial
when working with the input() function, which always gives us a string.
● int(value) - Converts to an integer
● float(value) - Converts to a float
● str(value) - Converts to a string
Code Example 6 (Putting it all together):
# 1. input() gives us a string
age_string = input("How old are you? ")
# 2. We cast the string to an integer
user_age = int(age_string)
# 3. Now we can do math and comparisons
is_adult = user_age >= 18
age_in_ten_years = user_age + 10
print(f"You are an adult: {is_adult}")
print(f"You will be {age_in_ten_years} in ten years.")
12