Variable in Python


Variables in Python are used to hold values that can be referenced and changed throughout the program. Here's an overview of Python variables, their kinds, and how they function:

Variable Declaration: 

In Python, the type of a variable is automatically inferred based on its assigned value, eliminating the need for explicit declaration.

Example:

x = 5          # Integer

name = "John"  # String

price = 19.99  # Float

is_active = True  # Boolean


Variable Naming Rules: 
  1. Variable names must begin with a letter or underscore (_).
  2. Subsequent characters may be letters, numbers, or underscores.
  3. Variable names are case-sensitive (for example, name and Name are not the same variable).
  4. Python keywords (such as if, while, and for) are not allowed.
Common Variable Types:

 Integer: Whole numbers, positive or negative.
 x = 10
 y = -5

Float: Numbers with a decimal point.
pi = 3.14159
temperature = -5.2

String: A set of characters. It should be enclosed within double quotes
greeting = "Hello, world!"

Boolean: Represents True or False.

is_valid = True
has_error = False


None: This is similar to "null" in other languages
result = None

Multiple Assignments:
Likewise, in other programming languages, in python we can also be able to assign multiple values in a single line.
a, b, c = 1, 2, "apple"

Type Checking:
You can check the type of a variable using the type() function.

x = 5
print(type(x))  # Output: <class 'int'>

Type Casting:

You can convert between types using type casting functions like int(), float(), str() etc.
x = "123"
y = int(x)  # Converts string to integer

Global and Local Variables:
  • Global variables are defined outside of functions and are accessible throughout the program.
  • Local variables are defined within functions and are accessible only within that function.
x = 10  # Global variable

def my_function():
    x = 5  # Local variable
    print(x)  # 5 (local x is used)

print(x)  # 10 (global x is used)

Changing Global Variables Inside Functions:

To modify a global variable within a function, you need to use the global keyword.

x = 10

def modify_variable():

    global x

    x = 20

modify_variable()

print(x)  # 20



Post a Comment

0 Comments