Learn Python in 30 Days - Day 2: Variables and Data Types (with Examples)

Rifat Seniabad
By -
0

 

Learn Python in 30 Days - Day 2: Variables and Data Types (with Examples)


Welcome to Day 2! Today, we’ll explore Python variables and data types, which are essential for writing dynamic programs. Let’s dive in!


1. What are Variables?

A variable is like a container that stores data values. You can use it to store numbers, text, or other data.

Syntax:

variable_name = value

Example:

name = "Farjana"
age = 20
is_student = True

print("Name:", name)
print("Age:", age)
print("Is a student:", is_student)

Output:

Name: Farjana
Age: 20
Is a student: True

2. Rules for Naming Variables

  1. Must start with a letter or an underscore (_).
  2. Cannot start with a number.
  3. Can contain letters, numbers, and underscores.
  4. Case-sensitive (age and Age are different).

Valid Examples:

name = "Mim"
_age = 25
student2 = True

Invalid Examples:

2name = "Mim"  # Starts with a number
my-name = "Mim"  # Contains a hyphen

3. Data Types in Python

Python has several data types to represent different kinds of information.

Common Data Types:

Data Type Example
int 10, -5, 0
float 3.14, -0.01, 2.5
str "hello", '123'
bool True, False
list [1, 2, 3]

4. Examples of Variables and Data Types

Example 1: Integer and Float

num1 = 10       # Integer
num2 = 3.14     # Float

print("Integer:", num1)
print("Float:", num2)

Output:

Integer: 10
Float: 3.14

Example 2: String

greeting = "Hello, Python!"
print(greeting)

Output:

Hello, Python!

Example 3: Boolean

is_coding_fun = True
print("Is coding fun?", is_coding_fun)

Output:

Is coding fun? True

Example 4: List

fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits)

Output:

Fruits: ['apple', 'banana', 'cherry']

5. Practice Tasks for Day 2

Task 1: Store and Print Information

Create variables for your name, age, and favorite hobby, then print them:

name = "Farjana"
age = 20
hobby = "baking"

print("Name:", name)
print("Age:", age)
print("Hobby:", hobby)

Task 2: Basic Calculations

Store two numbers in variables and calculate their sum, difference, and product:

a = 15
b = 7

print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)

Task 3: Update Variables

Create a variable, update its value, and print the result:

counter = 10
print("Initial value:", counter)

counter = counter + 5
print("Updated value:", counter)

6. Pro Tips for Day 2

  • Always use meaningful variable names to make your code readable.
  • Experiment with different data types to see how they behave.
  • Use type() to check the data type of a variable:
    x = 10
    print(type(x))  # Output: <class 'int'>
    

🎯 Day 2 Goal: Understand how to declare variables, identify data types, and practice simple operations.

Let me know when you’re ready for Day 3! 🚀

Tags:

Post a Comment

0Comments

Post a Comment (0)