Python Variables

In Python, variables act as containers to store data values, and they are crucial for holding information that can be used and manipulated throughout your program.

Creating Variables

Unlike other programming languages, Python does not require a specific command to declare a variable. A variable is automatically created when you assign a value to it.

For example:

x = 5
y = "1984"
print(x)  # 5
print(y)  # 1984

Here, the variables x and y are created and assigned the values 5 and "1984" respectively. Python is dynamically typed, meaning the variable type is determined by the value assigned, and you can change the type later:

x = 4       # x is of type int
x = "Dune" # x is now of type str
print(x)  # Dune

Casting Variables

If you need to define a variable with a specific type, you can use casting:

x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0
print(x)  # '3'
print(y)  # 3
print(z)  # 3.0

Getting the Type of a Variable

To check the type of a variable, use the type() function:

x = 5
y = "1984"
print(type(x))  # <class 'int'>
print(type(y))  # <class 'str'>

You will explore more about data types and casting in later chapters.

String Variables

String variables can be created using either single or double quotes:

x = "1984"
# is the same as
x = '1984'
print(x)  # 1984

Case Sensitivity

Python is case-sensitive, meaning variable names like age, Age, and AGE would refer to three different variables:

a = 4
A = "Dune"
# A will not overwrite a
print(a)  # 4
print(A)  # Dune

Variable Naming Rules

When naming variables, follow these rules:

  • A variable name must start with a letter or an underscore (_).
  • It cannot start with a number.
  • It can only contain alphanumeric characters and underscores (A-Z, 0-9, _).
  • Variable names are case-sensitive.
  • It cannot be any of the reserved Python keywords.

Examples of Legal Variable Names:

myvar = "1984"
my_var = "1984"
_my_var = "1984"
myVar = "1984"
MYVAR = "1984"
myvar2 = "1984"

Examples of Illegal Variable Names:

2myvar = "1984"  # SyntaxError
my-var = "1984"  # SyntaxError
my var = "1984"  # SyntaxError

Multi-Word Variable Names

For better readability, consider the following naming conventions:

  • Camel Case: Each word, except the first, starts with a capital letter: myVariableName
  • Pascal Case: Each word starts with a capital letter: MyVariableName
  • Snake Case: Each word is separated by an underscore: my_variable_name

Assigning Multiple Variables

You can assign multiple values to multiple variables in a single line:

x, y, z = "The Hobbit", "1984", "Dune"
print(x)  # The Hobbit
print(y)  # 1984
print(z)  # Dune

Or assign the same value to multiple variables:

x = y = z = "The Hobbit"
print(x)  # The Hobbit
print(y)  # The Hobbit
print(z)  # The Hobbit

Unpacking a Collection

If you have a collection of values, such as a list or tuple, Python allows you to unpack those values into variables:

books = ["The Hobbit", "1984", "Dune"]
x, y, z = books
print(x)  # The Hobbit
print(y)  # 1984
print(z)  # Dune

Outputting Variables

Using the print() function, you can output variables:

x = "Python is awesome"
print(x)  # Python is awesome

You can also output multiple variables, separated by commas:

x = "Python"
y = "is"
z = "awesome"
print(x, y, z)  # Python is awesome

Or use the + operator for concatenation:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)  # Python is awesome

For numerical values, the + operator adds them:

x = 5
y = 10
print(x + y)  # 15

Note: You cannot combine strings and numbers using the + operator. It will result in an error:

x = 5
y = "1984"
print(x + y)  # This will cause an error

Instead, use commas to combine them:

x = 5
y = "1984"
print(x, y)  # 5 1984

Global Variables

Variables created outside functions are global variables, accessible throughout the program:

x = "awesome"
def myfunc():
  print("Python is " + x)
myfunc()  # Python is awesome

If you define a variable with the same name inside a function, it will be local to that function:

x = "awesome"
def myfunc():
  x = "fantastic"
  print("Python is " + x)
myfunc()  # Python is fantastic
print("Python is " + x)  # Python is awesome

The global Keyword

To modify a global variable inside a function, use the global keyword:

x = "awesome"
def myfunc():
  global x
  x = "fantastic"
myfunc()
print("Python is " + x)  # Python is fantastic

Exercises:

  1. Create a variable called name and assign it your name. Print the value.
  2. Change the value of name to a number. What happens?
  3. Use the type() function to check the type of name.
  4. Create three variables a, b, and c in one line, and assign them the values 1, 2, and 3 respectively. Print the values.
  5. Try to use a Python keyword as a variable name. What error do you get?
  6. Write a program that swaps the values of two variables without using a third variable.
  7. Use the global keyword to change the value of a global variable inside a function.
  8. Declare a variable in camelCase, PascalCase, and snake_case. Print them to see the difference.
  9. Create a list of three items. Unpack the list into three variables and print them.
  10. Write a Python program that demonstrates the difference between local and global variables.

Answers:

  1. name = "Your Name"
    print(name) # Your Name
  2. Changing the value of name to a number is allowed in Python. The type of the variable changes accordingly.
  3. print(type(name)) # <class ‘str’>
  4. a, b, c = 1, 2, 3
    print(a, b, c) # 1

Leave a Comment

Best 3d printer : top picks and buying guide for 2024. Troubleshooting common smart device connectivity issues.