Python Variables , explanation and examples.

What is variable and describe data type and data type casting.

In programming, a variable can be defined as a named location in the memory where a value is stored. The data stored in a variable can be modified when the program is running, that is why it is called a variable. Variables are an important component of any programming language and in Python, variables are used to store data.

Variable Declaration and Assignment:

  1. Declaring a Variable:

In Python, the variable data type need not be declared explicitly. Just by assigning a value to a variable name, Python will figure out the type of the variable itself. To declare a variable just write the variable name followed by an equal sign (`=`) and the value you wish to assign to it.

Command:

x = 10

Explanation:

Here we are declaring the variable x and assigning it a value of 10 which is an integer. Python identifies the variable x as an integer, due to the value assigned to it.

  1. VariableAssignment

In Python, you can assign different types of values to variables, such as integers, floats, strings, booleans, lists, tuples, dictionaries, etc. The assigned value can be either a literal, the result of an expression, or the output of a function call.

Command:

name = “Alice”

age = 25

is_student = True

Explanation:

  • We have the string “Alice” assigned to the variable name.
  • The variable age is assigned the integer 25.
  • The variable is_student is assigned a boolean value True.

Variable Naming Conventions:

1. Rules for Naming Variables:

  • The first character of the variable name should be a letter (a-z, A-Z) or an underscore (`_`). They do not have to start with a number.
  • The remaining part of the variable name can comprise of letters, digits, or underscores.
  • Naming variables are case sensitive. For instance, myVar, MyVar, and myvar are not the same variables.
  • Python keywords (mapped to reserved words such as if, else, for, while, etc. ) are not allowed for variable names.

Command:

# Valid variable names

name = “Alice”

age = 25

is_student = True

my_var = “example”

Explanation:

  • my_name, my_age, is_student, and my_var are all valid variable names in Python.
  • They adhere to the rules mentioned above: they begin with a letter or underscore, followed by the letters, numbers, or underscores.

2. Best Practices for Naming Variables:

  • Use descriptive names: Names of variables must be descriptive and indicate the purpose of the variable.
  • Use lowercase letters: Names of the variables usually should be in lower case with underscores between the words (“snake_case”).
  • Avoid using single-letter names (except for simple loop variables): Meaningful names such as count or index should be used instead of single-letter ones like i or x.
  • Be consistent: Use the same naming convention consistently throughout your code.
  • Try to avoid abbreviations unless they are well-known and bring a meaning to the variable name.

Command:

Descriptive variable names

student_name = “Alice”

student_age = 25

is_student = True

Following these naming conventions and best practices helps maintain clean, readable, and maintainable code. Feel free to apply these guidelines in your Python projects! Let me know if you have any questions or need further clarification.

Data Types in Python

Python provides many built-in data types that are used to store the data of different categories.

1. Integers (int):

Integers are whole numbers, which do not have any decimal place or fraction a part.

Command:

age = 25

2. Floating-Point Numbers (float):

The characteristics of floating-point numbers are as follows: Floating point numbers are the type of real numbers which includes the decimal point.

Command:

pi = 3. 14

3. Strings (str):

Strings are values that are composed of characters and are mostly enclosed between single, double or triple quotation marks.

Command:

name = “Alice”

greeting = ‘Hello, World!’

long_text = “””This is a long string that spans multiple lines.”””

4. Lists (list):

Lists are the sets of elements, which can be of different types and which are enclosed into square brackets.

Command:

fruits = [“apple”, “banana”, “cherry”]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, “two”, 3.0, [4, 5]]

5. Tuples (`tuple`):

Tuples are similar to lists because they are ordered sets of elements, but they cannot be modified once they have been written and are contained within parentheses.

Command:

coordinates = (10.0, 20.0)
person = (“Alice”, 25, “Engineer”)

6.Dictionaries (dict):

Dictionaries are quite similar to lists but are not ordered, and they store elements in key-value pairs surrounded by curly braces {}.

Command:

student = {“name”: “Alice”, “age”: 25, “major”: “Computer Science”}

7. Sets (set):

It is a collection of unique items, and the elements are not ordered and not identified by indexes and are enclosed within curly brackets.

Command:

unique_numbers = {1, 2, 3, 4, 5}

Type Conversion (Casting) 

Python also provides features by which, one can easily type cast the values from one data type to another. This is referred to as type conversion or casting. Here are some common conversions:


float_number = 3.14
int_number = int(float_number) # int_number will be 3
str_number = “123”
int_from_str = int(str_number) # int_from_str will be 123

2. Converting to Float (float):

Command:

int_number = 10

float(int_number) #float_number will be 10. 0

str_number = “3. 14”

float_from_str = float(str_number) # float_from_str will be 3.14

3. Converting to String (str):

Command:

int_number = 10

float_number = 3. 14

str_from_int = str(int_number) # str_from_int will be “10”
str_from_float = str(float_number) # str_from_float will be “3.14”

4. Converting to List (list):

Command:

tuple_data = (1, 2, 3)
list_from_tuple = list(tuple_data) # list_from_tuple will be [1, 2, 3]

5. Converting to Tuple (tuple):

Command:

list_data = [1, 2, 3]
tuple_from_list = tuple(list_data) # tuple_from_list will be (1, 2, 3)

6. Converting to Dictionary (dict):

Command:

# Creating a dictionary from a list of tuples
list_of_tuples = [(“name”, “Alice”), (“age”, 25)]
dict_from_list = dict(list_of_tuples) # dict_from_list will be {‘name’: ‘Alice’, ‘age’: 25}

7. Converting to Set (set):

Command:

list_data = [1, 2, 3, 3, 4]
set_from_list = set(list_data) # set_from_list will be {1, 2, 3, 4}

Leave a Reply

Your email address will not be published. Required fields are marked *