Variables and Data Types in Python

Variables and Data Types in Python

In Python, a variable is a name that refers to a value. Variables can be used to store and manipulate data in a program.

23 January 2023

Variables and Data Types in Python

In Python, a variable is a name that refers to a value. Variables can be used to store and manipulate data in a program. To create a variable in Python, you simply give it a name and assign a value to it using the assignment operator (=). For example:


x = 5
y = "hello"
z = [1, 2, 3]

In the above example, x is assigned the value 5, y is assigned the string “hello”, and z is assigned the list [1, 2, 3].

Python has several built-in data types, including:

Integer (int): Whole numbers, such as 3, -5, or 0. Float (float): Numbers with decimal points, such as 3.14, -0.5, or 1.23e5. String (str): A sequence of characters, such as “hello” or “goodbye”. List (list): An ordered collection of items, such as [1, 2, 3] or [“apple”, “banana”, “cherry”]. Tuple (tuple): An ordered collection of items, similar to a list, but immutable. Dictionary (dict): An unordered collection of key-value pairs, such as {"name": "John", "age": 30} Here are a few examples of how to use variables and data types in Python:

Example 1: Using Variables


x = 5
y = 3
z = x + y
print(z)

In this example, x is assigned the value 5, y is assigned the value 3, and z is assigned the value of x + y (8). The program then prints the value of z (8).

Example 2: Working with Strings


name = "John"
age = 30
print("My name is " + name + " and I am " + str(age) + " years old.")

In this example, the variable name is assigned the string “John” and the variable age is assigned the integer 30. We use the + operator to concatenate the strings and use str() function to convert the integer to a string before concatenating.

Example 3: Using Lists


colors = ["red", "green", "blue"]
print(colors[1])
colors.append("yellow")
print(colors)

In this example, the variable colors is assigned a list of strings [“red”, “green”, “blue”]. The program then prints the second item in the list (index 1, “green”) and then add a new item “yellow” to the list and print the updated list.

Example 4: Using Dictionaries


person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"])
person["age"] = 35
print(person)

In this example, the variable person is assigned a dictionary with key-value pairs for “name”, “age”, and “city”. The program then prints the value for the key “name” (John) and then updates the age key with new value 35 and print the updated dictionary

It’s important to keep in mind that the data type of a variable can change depending on the value assigned to it. For example, a variable that is initially assigned an integer

© day1.study