Python Variables & DataTypes Tutorial by Trilochan Tarai | codeintervu.com | SilanSoftware
1. Python Variables
A variable in Python is a named location in memory where you can store data. Think of it as a labeled box where you can put different items (data) and the value of a variable may vary at the time of execution.
1.1 Assigning Values to Variables:
You assign a value to a variable using the assignment operator =.
# Assigning an integer to a variable
age = 30
# Assigning a string to a variable
name = "Trilochan"
# Assigning a float to a variable
price = 99.99
# Assigning a boolean to a variable
is_student = True
1.2 Variable Naming Rules:
# Valid
my_variable = 10
privatevar = 20
# Invalid (will raise a SyntaxError)
# 1st_variable = 30
Can contain letters, numbers, and underscores:
# Valid
user_name = "Bob"
item_count_2 = 100
Case-sensitive: age is different from Age.
age = 25
Age = 30
print(age) # Output: 25
print(Age) # Output: 30
Keywords cannot be used: Python has reserved keywords (e.g., if, else, while, for, print, True, False, None). You cannot use these as variable names.
# Invalid (will raise a SyntaxError)
# if = 10
Descriptive names are encouraged: Choose names that clearly indicate the purpose of the variable.
# Good
total_sales = 1500
# Not so good
ts = 1500
1.3 Dynamic Typing:
Python is a dynamically typed language. This means you don't need to explicitly declare the data type of a variable when you create it. Python automatically infers the data type based on the value assigned.
x = 10 # x is an integer
x = "Hello" # Now x is a string
x = 3.14 # Now x is a float
While convenient, this also means you should be mindful of the type of data a variable holds, especially when performing operations.
1.4 Checking Data Type:
You can use the type() function to check the data type of a variable.
my_var = 123
print(type(my_var)) # Output: <class 'int'>
my_var = "Python"
print(type(my_var)) # Output: <class 'str'>
my_var = [1, 2, 3]
print(type(my_var)) # Output: <class 'list'>
2. Python Data Types
Python has several built-in data types, which can be broadly categorized as follows:
2.1 Numeric Types:
Used to store numeric values.
· int (Integers): Whole numbers, positive or negative, without a decimal point.
num_int = 10
negative_int = -5
print(type(num_int))
float (Floating-Point Numbers): Numbers with a decimal point.
num_float = 3.14
scientific_notation = 1.23e-4 # Represents 0.000123
print(type(num_float))
complex (Complex Numbers): Numbers with a real and an imaginary part (e.g., a+bj).
num_complex = 3 + 4j
print(type(num_complex))
2.2 Sequence Types:
Ordered collections of items.
· str (Strings): Ordered sequences of characters. Enclosed in single (') or double (") quotes.
single_quote_str = 'Hello, Python!'
double_quote_str = "Python is fun."
multiline_str = """This is a
multiline string."""
print(type(single_quote_str))
Strings are immutable, meaning once created, their content cannot be changed.
list (Lists): Ordered, changeable (mutable) collection of items. Enclosed in square brackets []. Can contain items of different data types.
my_list = [1, "apple", 3.14, True]
print(my_list[0]) # Output: 1 (accessing by index)
my_list[1] = "banana" # Modifying an element
print(my_list) # Output: [1, 'banana', 3.14, True]
print(type(my_list))
tuple (Tuples): Ordered, unchangeable (immutable) collection of items. Enclosed in parentheses ().
my_tuple = (1, "orange", 5.0)
print(my_tuple[1]) # Output: orange
# my_tuple[0] = 2 # This would raise a TypeError (tuples are immutable)
print(type(my_tuple))
2.3 Mapping Type:
dict (Dictionaries): Unordered collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples). Values can be of any data type. Enclosed in curly braces {}.
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict["name"]) # Output: Alice
my_dict["age"] = 31 # Modifying a value
my_dict["occupation"] = "Engineer" # Adding a new key-value pair
print(my_dict)
print(type(my_dict))
2.4 Set Types:
· set (Sets): Unordered collection of unique items. Duplicates are automatically removed. Enclosed in curly braces {} or created using the set() constructor.
my_set = {1, 2, 3, 2, 4}
print(my_set) # Output: {1, 2, 3, 4} (duplicates removed)
another_set = set([5, 6, 6, 7])
print(another_set) # Output: {5, 6, 7}
print(type(my_set))
frozenset (Frozen Sets): Immutable version of a set.
my_frozenset = frozenset([1, 2, 3])
# my_frozenset.add(4) # This would raise an AttributeError (frozensets are immutable)
print(type(my_frozenset))
2.5 Boolean Type:
is_active = True
is_logged_in = False
print(type(is_active))
2.6 None Type:
no_value = None
Recommended by LinkedIn
print(no_value)
print(type(no_value))
3. Type Conversion (Type Casting)
You can convert values from one data type to another using built-in functions.
# int()
num_str = "123"
num_int = int(num_str)
print(num_int, type(num_int)) # Output: 123 <class 'int'>
# float()
num_int = 45
num_float = float(num_int)
print(num_float, type(num_float)) # Output: 45.0 <class 'float'>
# str()
num = 100
num_to_str = str(num)
print(num_to_str, type(num_to_str)) # Output: 100 <class 'str'>
# list()
my_tuple_for_list = (1, 2, 3)
list_from_tuple = list(my_tuple_for_list)
print(list_from_tuple, type(list_from_tuple)) # Output: [1, 2, 3] <class 'list'>
# tuple()
my_list_for_tuple = ["a", "b"]
tuple_from_list = tuple(my_list_for_tuple)
print(tuple_from_list, type(tuple_from_list)) # Output: ('a', 'b') <class 'tuple'>
# set()
my_list_for_set = [1, 2, 2, 3]
set_from_list = set(my_list_for_set)
print(set_from_list, type(set_from_list)) # Output: {1, 2, 3} <class 'set'>
# bool()
print(bool(0)) # Output: False (0 is considered False)
print(bool(1)) # Output: True
print(bool("")) # Output: False (empty string is False)
print(bool("abc"))# Output: True
print(bool([])) # Output: False (empty list is False)
print(bool([1])) # Output: True
Note: Not all conversions are possible or will result in meaningful data. For example, trying to convert a non-numeric string to an integer will raise a ValueError.
This tutorial covers the basics of Python variables and the most commonly used built-in data types. A solid understanding of these concepts is crucial for writing effective and robust Python programs. As you progress, you'll encounter more specialized data structures and ways to work with these fundamental types.
Quiz:
1. Which of the following is a valid variable name in Python?
A._my_variable
B.1st_variable
C.if
D.my-variable
2. What will be the data type of x after the following code is executed? ```python x = 10 x = 'Hello' x = 3.14 ```
A.float
C.str
D.NoneType
3. Which of the following data types is immutable?
A.tuple
B.set
C.list
D.dictionary
4. What is the output of type(3 + 4j)?
A.<class 'int'>
B.<class 'float'>
C.<class 'str'>
D.<class 'complex'>
5. What will type(my_var) return if my_var = [1, 'two', 3.0]?
A.<class 'set'>
B.<class 'tuple'>
C.<class 'list'>
D.<class 'dict'>
6. Which Python statement is used to check the data type of a variable var_name?
A.`type(var_name)`
B.`print_type(var_name)`
C.`get_type(var_name)`
D.`var_name.type()`
7. What is the result of bool("False")?
A.Error
B.None
C.False
D.True
True
Right answer
Any non-empty string in Python, including the string 'False', evaluates to True when converted to a boolean.
8. Which of the following defines a dictionary in Python?
A.`{1, 2, 3}`
B.`{'name': 'Alice', 'age': 25}`
C.`[key: value]`
D.`('item1', 'item2')`
9. If my_list = [10, 20, 30], what will my_list[1] return?
A.10
B.Error
C.20
D.30
10. What is frozenset primarily used for?
A.To store key-value pairs without duplicates.
B.To create an ordered collection of unique items.
C.To create a mutable set that can be modified.
D.To create an immutable version of a set.