Day 2: Python Variables & Data Types

 

Day 2: Python Variables & Data Types - Detailed Walkthrough

Rey, Day 2 ki vachav! Ninnati basics (Python install, Hello World) paina build chesi, ee roju variables and data types cover chestam. Variables ante data store chese containers, data types ante aa data ela untundo (numbers, text, etc.). Step-by-step cheddam, 1-2 hours plan, hands-on practice tho

Step 1: Understanding Variables (10-15 mins)

Variables are like labeled boxes where you store data (numbers, text, etc.). Python lo variables create cheyadam easy – no need to declare type explicitly.

  • Syntax: variable_name = value
    • Example: age = 25 (stores 25 in variable age).
  • Rules:
    • Names start with letters or _ (underscore), not numbers (e.g., age, _count, not 2age).
    • Case-sensitive (Age ≠ age).
    • Use meaningful names (e.g., salary instead of x).
  • Dynamic Typing: Python automatically detects data type. Example: name = "Rey" (string), marks = 85 (integer).

Action: Read this quick guide: W3Schools: Python Variables (5-10 mins). Focus on "Variable Names" and "Assign Multiple Values" sections.


Step 2: Data Types Overview (10-15 mins)

Python has several built-in data types. Ee roju focus chese main types:

  • int: Whole numbers (e.g., 5, -10, 0).
  • float: Decimal numbers (e.g., 3.14, -0.5).
  • str: Text/strings, in single/double quotes (e.g., "Hello", 'Rey').
  • bool: True/False values.

Check Type: Use type() function to see data type.

  • Example: print(type(42)) → <class 'int'>

Type Conversion:

  • Convert types when needed:
    • int("5") → 5 (string to int).
    • float(10) → 10.0 (int to float).
    • str(100) → "100" (int to string).
  • Be careful: int("abc") raises error (invalid conversion).

Action: Watch first 15 mins of RealPython: Python Variables (video or article). It explains types with examples.


Step 3: Hands-On Coding (30-40 mins)

Let’s write code in VS Code (or IDLE). Create a new file day2.py.

  1. Basic Variable Assignment:
    python
    name = "Rey"  # str
    age = 25      # int
    height = 5.9  # float
    is_student = True  # bool
    
    print(name, "is", age, "years old, height", height, "feet, student?", is_student)
    print("Type of age:", type(age))
    • Save and run: python day2.py.
    • Output: Rey is 25 years old, height 5.9 feet, student? True
    • Output: Type of age: <class 'int'>
  2. Type Conversion:
    python
    # Convert string input to int
    user_age = input("Enter your age: ")  # Input is always string
    user_age = int(user_age)  # Convert to int
    print("Next year, you'll be", user_age + 1)
    
    # Convert int to string
    score = 95
    message = "Your score is: " + str(score)
    print(message)
    • Run and test with input (e.g., enter 20).
    • Output: Next year, you'll be 21
    • Output: Your score is: 95
  3. String Formatting (Bonus for Day 2): Python has multiple ways to format strings for clean output:
    • f-strings (recommended, Python 3.6+):
      python
      name = "Rey"
      age = 25
      print(f"Rey, naa peru {name} mariyu naa vayasu {age} years!")
    • .format() (older method):
      python
      print("Rey, naa peru {} mariyu naa vayasu {} years!".format(name, age))
    • % operator (oldest, avoid):
      python
      print("Rey, naa peru %s mariyu naa vayasu %d years!" % (name, age))
    • Run and compare outputs. f-strings are cleanest!

Troubleshooting:

  • Error like ValueError? Check if input is valid (e.g., int("abc") fails).
  • Indentation wrong? Python is strict – use 4 spaces or 1 tab.
  • Output not clear? Use print() to debug variable values.

Step 4: Practice Exercise (20-30 mins)

Task: Write a script that:

  1. Asks user for their name (string) and salary (float).
  2. Prints a formatted message like: "Rey [name], your salary is [salary] INR."
  3. Converts salary to integer and prints: "As integer, salary is [int_salary]."

Solution:

python
# day2_exercise.py
name = input("Enter your name: ")  # Get name
salary = float(input("Enter your salary: "))  # Get salary as float

# Formatted output using f-string
print(f"Rey {name}, your salary is {salary} INR.")

# Convert to int and print
int_salary = int(salary)
print(f"As integer, salary is {int_salary} INR.")

Steps:

  1. Create day2_exercise.py in VS Code.
  2. Write the code above.
  3. Run: python day2_exercise.py.
  4. Test with inputs:
    • Name: "Ram"
    • Salary: "50000.75"
    • Output: Rey Ram, your salary is 50000.75 INR.
    • Output: As integer, salary is 50000 INR.

Challenge:

  • Add error handling (basic try-except) to handle invalid salary input (e.g., letters instead of numbers).
    python
    try:
        salary = float(input("Enter your salary: "))
        print(f"Rey {name}, your salary is {salary} INR.")
    except ValueError:
        print("Error: Please enter a valid number for salary!")

Step 5: Wrap-Up & Resources (5-10 mins)

  • What You Learned:
    • Variables: Create, name, assign.
    • Data Types: int, float, str, bool.
    • Type Conversion: int(), float(), str().
    • String Formatting: f-strings are your friend!
  • Track Progress: In your journal, note:
    • 2-3 things you understood (e.g., "f-strings are easy").
    • 1 question or struggle (e.g., "Why does int('abc') fail?").
  • Resources:

FOLLOW OUR WHATSAPP CHANNEL:
                                           MIDDLE CLASS BLOGS

Comments

Post a Comment

Popular Posts