← Introduction to Programming

Introduction/Objectives

Welcome to Week 2’s tutorial! In this week’s lecture, you learned about the fundamental building blocks of Python programming: variables, data types, and operators.

In this tutorial, you will:

  • Create and use variables to store different types of data
  • Work with Python’s four fundamental data types: int, float, str, and bool
  • Apply arithmetic, relational, and logical operators to solve problems
  • Format output using f-strings for professional-looking results
  • Convert between different data types using type casting

Core Content

1. Variables and Assignment

What are variables? Think of a variable as a labeled box where you can store a value. You give the box a name (the variable name), and you can put different things inside it (the value). Later, you can use that name to retrieve or change what’s in the box.

How to create variables:

# Basic variable assignment
name = "Alisher"
age = 19
height = 1.75
is_enrolled = True

# Multiple assignment in one line
x, y, z = 10, 20, 30

# Assigning the same value to multiple variables
a = b = c = 0

Variable Naming Rules:

  • Must start with a letter (a-z, A-Z) or underscore (_)
  • Can contain letters, numbers, and underscores
  • Cannot contain spaces or special characters
  • Case-sensitive: age and Age are different variables
  • Cannot use Python keywords like if, for, print, etc.
# Good variable names
student_name = "Laylo"
total_score = 95
_private_value = 100

# Bad variable names (these will cause errors!)
# 2fast = 50           # Can't start with a number
# my-variable = 10     # Can't use hyphens
# for = 5              # Can't use keywords

Practical Example:

# Creating variables for a student record
first_name = "Dilshod"
last_name = "Karimov"
student_id = 20230001
gpa = 3.85
is_scholarship_eligible = True

# You can change variable values
gpa = 3.92  # Updated GPA

# Display the information
print(f"Student: {first_name} {last_name}")
print(f"ID: {student_id}")
print(f"GPA: {gpa}")

2. Fundamental Data Types

Python has four basic data types that you’ll use constantly. Each type represents a different kind of information.

2.1 Integer (int)

What is it? Whole numbers without decimal points. Can be positive, negative, or zero.

# Examples of integers
age = 20
temperature = -5
score = 0
population = 1000000

# You can check the type
print(type(age))  # Output: <class 'int'>

# Integers can be very large
big_number = 999999999999999999999
print(big_number)  # Python handles big integers automatically!

2.2 Float (float)

What is it? Numbers with decimal points. Used for measurements, prices, and any value requiring precision.

# Examples of floats
height = 1.75
price = 29.99
temperature = 36.6
pi = 3.14159

# Check the type
print(type(height))  # Output: <class 'float'>

# Even whole numbers with .0 are floats
value = 5.0
print(type(value))  # Output: <class 'float'>

2.3 String (str)

What is it? Text data enclosed in single (') or double (") quotes. Used for names, messages, and any textual information.

# Examples of strings
name = "Aziza"
message = 'Good morning!'
address = "123 Main Street, Urgench"

# Single or double quotes work the same
greeting1 = "Hello"
greeting2 = 'Hello'

# Use different quotes if your string contains quotes
sentence = "She said 'Hello' to me"
quote = 'He replied "Hi there"'

# Check the type
print(type(name))  # Output: <class 'str'>

# Numbers in quotes are strings, not numbers!
age_str = "20"
print(type(age_str))  # Output: <class 'str'>

2.4 Boolean (bool)

What is it? Logical values representing True or False. Used for conditions and decision-making.

# Examples of booleans
is_student = True
has_graduated = False
is_raining = False

# Check the type
print(type(is_student))  # Output: <class 'bool'>

# Booleans often come from comparisons
is_adult = 20 >= 18  # True
is_passing = 45 >= 50  # False

print(is_adult)    # Output: True
print(is_passing)  # Output: False

3. Arithmetic Operators

What are they? Symbols that perform mathematical calculations on numbers.

# Basic arithmetic operations
a = 10
b = 3

# Addition
sum_result = a + b
print(f"{a} + {b} = {sum_result}")  # Output: 10 + 3 = 13

# Subtraction
difference = a - b
print(f"{a} - {b} = {difference}")  # Output: 10 - 3 = 7

# Multiplication
product = a * b
print(f"{a} * {b} = {product}")  # Output: 10 * 3 = 30

# Division (always returns a float)
quotient = a / b
print(f"{a} / {b} = {quotient}")  # Output: 10 / 3 = 3.3333...

# Floor Division (rounds down to nearest integer)
floor_div = a // b
print(f"{a} // {b} = {floor_div}")  # Output: 10 // 3 = 3

# Modulus (remainder after division)
remainder = a % b
print(f"{a} % {b} = {remainder}")  # Output: 10 % 3 = 1

# Exponentiation (power)
power = a ** b
print(f"{a} ** {b} = {power}")  # Output: 10 ** 3 = 1000

Practical Example: Area Calculator

# Calculate the area of a rectangle
length = 5.5
width = 3.2

area = length * width
perimeter = 2 * (length + width)

print(f"Rectangle dimensions: {length}m x {width}m")
print(f"Area: {area} square meters")
print(f"Perimeter: {perimeter} meters")

4. Relational (Comparison) Operators

What are they? Operators that compare two values and return True or False.

# Comparison examples
x = 10
y = 20

# Equal to
print(x == y)   # False
print(x == 10)  # True

# Not equal to
print(x != y)   # True
print(x != 10)  # False

# Greater than
print(y > x)    # True
print(x > 20)   # False

# Less than
print(x < y)    # True
print(y < 10)   # False

# Greater than or equal to
print(x >= 10)  # True
print(x >= 15)  # False

# Less than or equal to
print(x <= 10)  # True
print(x <= 5)   # False

Practical Example: Age Verification

# Check if someone is eligible to vote
age = int(input("Enter your age: "))

is_eligible = age >= 18
is_minor = age < 18

print(f"Age: {age}")
print(f"Eligible to vote: {is_eligible}")
print(f"Still a minor: {is_minor}")

5. Logical Operators

What are they? Operators that combine boolean values or comparison results.

# AND operator - both conditions must be True
print(True and True)    # True
print(True and False)   # False
print(False and False)  # False

# OR operator - at least one condition must be True
print(True or False)    # True
print(False or False)   # False

# NOT operator - reverses the boolean value
print(not True)         # False
print(not False)        # True

Practical Example: Admission Requirements

# Check if a student meets admission requirements
test_score = int(input("Enter test score (0-100): "))
gpa = float(input("Enter GPA (0.0-4.0): "))

# Student qualifies if test_score >= 70 AND gpa >= 3.0
qualifies = test_score >= 70 and gpa >= 3.0

# Student gets a warning if test_score < 50 OR gpa < 2.0
needs_warning = test_score < 50 or gpa < 2.0

print(f"\nTest Score: {test_score}")
print(f"GPA: {gpa}")
print(f"Qualifies for admission: {qualifies}")
print(f"Needs academic warning: {needs_warning}")

6. Type Conversion (Type Casting)

What is it? Converting a value from one data type to another.

Why do we need it? The input() function always returns a string. If you need to do math with user input, you must convert it to a number first!

# Converting to integer
float_num = 3.7
string_num = "42"

int_from_float = int(float_num)  # 3 (decimals are truncated!)
int_from_string = int(string_num)  # 42

print(int_from_float)   # 3
print(int_from_string)  # 42

# Converting to float
int_num = 5
string_decimal = "3.14"

float_from_int = float(int_num)        # 5.0
float_from_string = float(string_decimal)  # 3.14

print(float_from_int)      # 5.0
print(float_from_string)   # 3.14

# Converting to string
number = 100
decimal = 3.14
boolean = True

str_from_int = str(number)    # "100"
str_from_float = str(decimal)  # "3.14"
str_from_bool = str(boolean)   # "True"

print(str_from_int)      # "100"
print(str_from_float)    # "3.14"
print(str_from_bool)     # "True"

# Converting to boolean
bool(0)        # False
bool(1)        # True
bool("")       # False (empty string)
bool("Hello")  # True (non-empty string)
bool(3.14)     # True (non-zero number)

Important Note: Be careful with int() conversion from strings!

# This works
valid_conversion = int("25")
print(valid_conversion)  # 25

# This causes an error!
# invalid_conversion = int("25.5")  # ValueError!
# You must convert to float first, then to int
correct_way = int(float("25.5"))
print(correct_way)  # 25

Practical Example: User Input with Math

# Without type conversion (WRONG!)
# age = input("Enter your age: ")  # Let's say user enters "20"
# next_year = age + 1  # ERROR! Can't add string and integer

# With type conversion (CORRECT!)
age = int(input("Enter your age: "))  # Converts string to integer
next_year = age + 1

print(f"Your age: {age}")
print(f"Next year you'll be: {next_year}")

7. String Formatting with f-strings

What are f-strings? A modern, convenient way to insert variables and expressions into strings. The f before the quotes means “formatted string.”

# Basic f-string usage
name = "Malika"
age = 19

# Without f-strings (old way)
print("My name is " + name + " and I am " + str(age) + " years old.")

# With f-strings (modern way)
print(f"My name is {name} and I am {age} years old.")

# You can put expressions inside the curly braces
print(f"Next year I will be {age + 1} years old.")

# Formatting numbers
price = 15999.5
print(f"Price: {price:.2f} sum")  # Output: Price: 15999.50 sum

pi = 3.14159265359
print(f"Pi to 2 decimals: {pi:.2f}")  # Output: Pi to 2 decimals: 3.14
print(f"Pi to 4 decimals: {pi:.4f}")  # Output: Pi to 4 decimals: 3.1416

Practical Example: Receipt Generator

# Generate a simple receipt
item = input("Enter item name: ")
quantity = int(input("Enter quantity: "))
price_per_item = float(input("Enter price per item: "))

total = quantity * price_per_item

print(f"\n{'='*40}")
print(f"         RECEIPT")
print(f"{'='*40}")
print(f"Item: {item}")
print(f"Quantity: {quantity}")
print(f"Price per item: {price_per_item:.2f} sum")
print(f"{'='*40}")
print(f"TOTAL: {total:.2f} sum")
print(f"{'='*40}\n")

Putting It All Together

Let’s create a BMI (Body Mass Index) Calculator that combines variables, data types, operators, type conversion, and f-strings!

# BMI Calculator Program
# BMI = weight (kg) / (height (m))^2
# BMI Categories:
# - Underweight: BMI < 18.5
# - Normal: 18.5 <= BMI < 25
# - Overweight: 25 <= BMI < 30
# - Obese: BMI >= 30

print("="*50)
print("          BMI CALCULATOR")
print("="*50)

# Get user input
name = input("Enter your name: ")
weight = float(input("Enter your weight (kg): "))
height = float(input("Enter your height (m): "))

# Calculate BMI
bmi = weight / (height ** 2)

# Determine category using comparisons
is_underweight = bmi < 18.5
is_normal = bmi >= 18.5 and bmi < 25
is_overweight = bmi >= 25 and bmi < 30
is_obese = bmi >= 30

# Display results
print(f"\n{'='*50}")
print(f"Results for {name}")
print(f"{'='*50}")
print(f"Weight: {weight} kg")
print(f"Height: {height} m")
print(f"BMI: {bmi:.2f}")
print(f"{'='*50}")
print(f"Underweight (< 18.5): {is_underweight}")
print(f"Normal (18.5-24.9): {is_normal}")
print(f"Overweight (25-29.9): {is_overweight}")
print(f"Obese (>= 30): {is_obese}")
print(f"{'='*50}\n")

What this program demonstrates:

  • Taking multiple user inputs with type conversion
  • Using arithmetic operators for calculations
  • Using exponentiation operator (**)
  • Using relational operators for comparisons
  • Using logical operators (and) to check ranges
  • Storing boolean results in variables
  • Professional output formatting with f-strings

Practice Exercises

Exercise 1: Temperature Converter

Write a program that converts temperature from Celsius to Fahrenheit and Kelvin.

Formulas:

  • Fahrenheit = (Celsius × 9/5) + 32
  • Kelvin = Celsius + 273.15

Requirements:

  • Ask the user for temperature in Celsius
  • Calculate both Fahrenheit and Kelvin
  • Display all three temperatures with 2 decimal places
  • Use f-strings for output

Exercise 2: Circle Properties Calculator

Write a program that calculates the area and circumference of a circle.

Formulas:

  • Area = π × r²
  • Circumference = 2 × π × r
  • Use pi = 3.14159

Requirements:

  • Ask the user for the radius
  • Calculate area and circumference
  • Display results with 2 decimal places
  • Use f-strings for formatted output

Exercise 3: Grade Eligibility Checker

Write a program that checks if a student is eligible for the dean’s list.

Requirements:

  • Ask for: student name, GPA (0.0-4.0), total credit hours
  • Dean’s list requirements:
    • GPA >= 3.5 AND credit hours >= 12
  • Display:
    • Student information
    • Whether they made the dean’s list (True/False)
    • How many more GPA points needed (if GPA < 3.5)
    • How many more credits needed (if credits < 12)