Variables and Data Types

โœ•

1. Variables

    1.1 Real World Scenario
    1. Imagine your room has different containers: ๐Ÿ“ฆ Box labeled Books ๐Ÿ‘• Box labeled Clothes ๐ŸŽ Basket labeled Fruits Each container stores something and has a name so that you can find it later. Similarly, a Variable is a named container used to store data in a computer's memory for later use. ๐Ÿ“ฆ name โžœ "Rabindra" ๐Ÿ“ฆ age โžœ 25 ๐Ÿ“ฆ PI โžœ 3.14159
Variables
Variables
    1.2 Definition
    1. A variable is a named storage location used to store data values that can be used or modified later in a program.
    1.3 Key Points
    1. โœ… Created by assigning a value to a name โœ… Can be reassigned to different values later โœ… Used to store information for future use โœ… Makes programs easier to understand and maintain
    1.4 Examples:
    1. x = 5
    2. name = "Rabindra"
    3. PI = 3.14159
    4. is_student = True
    5. colors = ["red", "green", "blue"]
    1.5 Constants
    1. Sometimes we have values that should not change throughout a program. These values are called Constants. Examples: PI = 3.14159 MAX_MARKS = 100 ๐Ÿ“Œ Constants are usually written in UPPERCASE letters.
Variable and Constants
Variable and Constants

2. Variable Naming Conventions

    2.1 Rules
    1. โœ… Should have meaningful names โœ… Can contain letters (a-z, A-Z), digits (0-9), and underscores (_) โœ… Must start with a letter or underscore (_) โœ… Python is case-sensitive โœ… snake_case is preferred โ€” this means writing variable names in lowercase with underscores between words, like total_marks โŒ Reserved keywords cannot be used as variable names (for, while, def, etc.)
Python Variable Naming Convention
Python Variable Naming Convention
    2.2 Case Sensitivity
    1. name = "Ram" NAME = "Hari" Here, name and NAME are treated as two different variables due to case sensitivity.

3. Data Types

    3.1 Why Do We Need Data Types?
    1. Consider the following examples: print(5 + 3) # โžœ 8 print("5" + "3") # โžœ "53" print("5" + 3) # โžœ Error ๐Ÿค” Why are the results different? Because the values have different Data Types.
    3.2 Definition
    1. A data type specifies the type of value stored in a variable and determines the operations that can be performed on it.
    3.3 Python Data Types
    1. Python data types are broadly classified into: ๐Ÿ”น Primitive Data Types โ€” Store a single value (like a number or word) ๐Ÿ”น Collection Data Types โ€” Store multiple values together (like a list of items)
Python Data Types
Python Data Types

4. Primitive Data Types

    4.1 ๐Ÿ”ข Integer (int)
    1. Whole numbers without decimal points. Examples: 10, -5, 0Example Variable: age = 25
    4.2 ๐Ÿ”ข Float (float)
    1. Numbers with decimal points. Examples: 3.14, -2.5, 0.1, 3.0Example Variable: temperature = 36.59
    4.3 ๐Ÿ”ค String (str)
    1. Sequence of characters enclosed in quotes. Examples: 'Python', "Hi", """Hello World""", "3.0"Example Variable: name = "Alice"
    4.4 โœ… Boolean (bool)
    1. Represents truth values. Possible values: True, FalseExample Variable: is_active = True
    4.5 Complex (complex)
    1. Numbers with real and imaginary parts. Examples: 3 + 4j, -2.5 + 3.14j, 0 + 2jExample Variable: z = 2 + 3j

5. Collection Data Types

    5.1 List
    1. A collection of items enclosed in square brackets [ ]. Examples: [1, 2, 3], ["apple", "banana", "cherry"], [1, "hello", 3.14]Example Variable: my_list = [True, 4, "pulp"]
    5.2 Tuple
    1. A collection of items enclosed in parentheses ( ). Examples: (1, 2, 3), ("apple", "banana", "cherry"), (1, "hello", 3.14)Example Variable: my_tuple = (True, 4, "pulp")
    5.3 Set
    1. A collection of unique items enclosed in curly braces { }. Examples: {1, 2, 3}, {"apple", "banana", "cherry"}, {1, "hello", 3.14}Example Variable: my_set = {True, 4, "pulp"}
    5.4 Dictionary
    1. A collection of key-value pairs enclosed in curly braces { }. Examples: {"name": "Alice", "age": 25}, {"fruit": "apple", "healthy": True}Example Variable: my_dict = {"city": "Kathmandu", "country": "Nepal"}

6. Data Types Affect Operations

    6.1 Addition โž•
    1. print(5 + 3) # โžœ 8 (int + int = int) print(3.5 + 2.5) # โžœ 6.0 (float + float = float) print("Hello" + " " + "World") # โžœ "Hello World" (str + str = str) print("5" + "3") # โžœ "53" (str + str = str) print(5 + "3") # โžœ Error (int + str = TypeError)
Addition Operator for Different Data Types
Addition Operator for Different Python Data Types
    6.2 Subtraction โž–
    1. print(5 - 3) # โžœ 2 (int - int = int) print(3.5 - 2.5) # โžœ 1.0 (float - float = float) print("Hello" - "World") # โžœ Error (str - str = TypeError) print(5 - "3") # โžœ Error (int - str = TypeError)
Subtraction Operator for Different Data Types
Subtraction Operator for Different Python Data Types
    6.3 Multiplication โœ–๏ธ
    1. print(5 * 3) # โžœ 15 (int * int = int) print(3.5 * 2) # โžœ 7.0 (float * int = float) print("Hello" * 3) # โžœ "HelloHelloHello" (str * int = str) print("Hello" * "World") # โžœ Error (str * str = TypeError)
Multiplication Operator for Different Data Types
Multiplication Operator for Different Python Data Types
    6.4 Division โž—
    1. print(5 / 2) # โžœ 2.5 (int / int = float) print(3.5 / 2) # โžœ 1.75 (float / int = float) print("Hello" / 2) # โžœ Error (str / int = TypeError) print(5 / "2") # โžœ Error (int / str = TypeError) ๐Ÿ“Œ Same operator can behave differently depending on the data type. ๐Ÿ“Œ TypeError means Python doesn't allow that operation between these two data types.
Division Operator for Different Data Types
Division Operator for Different Python Data Types

7. Checking Data Types

    7.1 Why Check Data Types?
    1. We often need to know the data type of a variable before performing operations because the result depends on the data type.
    7.2 How to Check Data Types?
    1. We can check the data type of a variable using the type() function. Syntax: type(variable_name)Example: num = 10 print(type(num)) # โžœ <class 'int'> name = "Alice" print(type(name)) # โžœ <class 'str'> is_active = True print(type(is_active)) # โžœ <class 'bool'> colors = ["red", "green", "blue"] print(type(colors)) # โžœ <class 'list'>
Checking Data Type in Python
Checking Data Type in Python

8. Type Conversion

    8.1 Why Do We Need Type Conversion?
    1. Sometimes we need to convert data from one type to another before performing operations. For example, what if we want to add two numbers, but they are stored as strings? Example: num_1 = "10" num_2 = "5" print(num_1 + num_2) # โžœ "105" (str + str = str) print(int(num_1) + int(num_2)) # โžœ 15 (int + int = int) To convert a value, write the new data type's name followed by the value in brackets, like this: target_datatype(value) Some common conversions are: int() โžœ Converts to integer float() โžœ Converts to float str() โžœ Converts to string bool() โžœ Converts to boolean list() โžœ Converts to list tuple() โžœ Converts to tuple set() โžœ Converts to set dict() โžœ Converts to dictionary
Data Type Conversion in Python
Data Type Conversion in Python
    8.2 Example of Type Conversion
    1. num_str = "100" print(type(num_str)) num_int = int(num_str) # โžœ 100 print(type(num_int)) # โžœ <class 'int'> num_float = float(num_str) # โžœ 100.0 print(type(num_float)) # โžœ <class 'float'> num_bool = bool(num_str) # โžœ True print(type(num_bool)) # โžœ <class 'bool'> new_num = 10.0 print(type(new_num)) new_num_str = str(new_num) # โžœ "10.0" print(type(new_num_str)) # โžœ <class 'str'> โš ๏ธ If conversion is not possible due to invalid data, Python raises a ValueError. For example, int("apple") will raise ValueError because "apple" cannot be converted into an integer.

9. Type Conversion Practical Examples

    9.1 Example 1
    1. var_1 = "5" var_2 = "2.5" print(var_1 + var_2) # โžœ 52.5 var_1_float = float(var_1) var_2_float = float(var_2) print(var_1_float + var_2_float) # โžœ 7.5
    9.2 Example 2
    1. var_5 = "10" var_6 = 5 print(var_5 * var_6) # โžœ 1010101010 print(int(var_5) * var_6) # โžœ 50

Practice QuestionsNot started

  1. Inside python_lab folder, create a new folder named variable. In the variable folder, solve each questions in a separate file.

    Question 1 of 2

    • ๐Ÿชช Create a variable to store your name and print it.
    • ๐ŸŽ‚ Create a variable to store your age using proper data type and print it.
    • ๐Ÿ“ Create a constant named PI to store the value 3.14159 and print it.
    • ๐Ÿ‡ณ๐Ÿ‡ต Create a variable to store a boolean value is_nepali (True or False, like answering a yes/no question) and print it.
  2. Inside python_lab folder, create a new folder named data_type_conversion. In the data_type_conversion folder, solve each questions in a separate file.

    Question 2 of 2

    • ๐ŸŽ‚ You store your age as num_int = 15. Display its data type. Now convert it to float and string, and display the type again each time.
    • ๐Ÿ›’ A shop stores item price as text: num_str = "25". Add a delivery charge of 10 to it after proper type conversion, and print the total.
    • ๐ŸŒก๏ธ A thermometer reads float_num = 10.5. Convert it to string, then add "10" (a label) to it, and print the result โ€” what happens?
    • โœ… A form field stores is_active = True for "is this user active?". Convert it to string and print both the result and its data type.
    • ๐Ÿ’ฐ Two friends write down money they have as text: num_1 = "5" and num_2 = "2.5". Convert both to float and print their total.
    • ๐Ÿงพ A cashier accidentally writes : print(5 + "5") โ€” predict what this will print, then run it and check. Now fix the code so it correctly prints 10.