Site icon Kaizen.Personal computer work.

Variables and Data types.(Python)

Japanese version.

In Python, data is represented in various types. A data type indicates what kind of value the data represents. The main data types include:

Variables are used to store data. A variable assigns a name to a value, and the value can be changed as needed. In Python, variables are assigned values using a simple assignment operator, "=", which assigns a value to a variable name.

For example, you can assign the integer value 5 to the variable "x" like this:

x = 5

Variable names are made up of a combination of alphanumeric characters and underscores (_). Variable names cannot start with a number. Python distinguishes between uppercase and lowercase letters in variable names.

Python automatically determines the data type of a variable's assigned value. You can also explicitly specify a variable's data type.

For example, you can assign the string "John" to the variable "name" and the integer value 25 to the variable "age" like this:

name = "John"

age = 25

The data types of the values assigned to these variables are "str" and "int", respectively.

Using variables makes a program more flexible and allows for more complex calculations and operations. Understanding variables and data types is essential for basic Python coding.

int (integer)

Integers are numbers that include positive integers, negative integers, and zero. The int type in Python can represent integers of any size. This is because Python automatically allocates the necessary number of digits.

To use the int type, simply assign an integer value to a variable.

For example, you can assign the integer value 5 to the variable "x" like this:

x = 5

In Python, you can also manipulate int values using arithmetic operators. Arithmetic operators include addition (+), subtraction (-), multiplication (*), and division (/), among others.

For example, you can assign integer values to variables "x" and "y", add them together, and assign the result to variable "z" like this:

x = 5

y = 3

z = x + y

print(z)

In this case, variable "z" is assigned the value of 8.

The int data type is one of the frequently used data types in Python, and it is necessary for performing mathematical operations and calculations.

Let's try it.

float (floating-point number)

The float data type in Python is used to represent floating-point numbers.

Floating-point numbers are numbers that have digits after the decimal point. The float type in Python can represent decimal numbers of any number of digits. However, the precision of floating-point numbers is limited, and there is a possibility of errors.

To use the float type, simply assign a decimal value to a variable.

For example, you can assign the decimal value 3.14 to the variable "x" like this:

x = 3.14

In Python, you can also manipulate float values using arithmetic operators.

For example, you can assign floating-point numbers to variables "x" and "y", multiply them together, and assign the result to variable "z" like this:

x = 2.5

y = 1.5

z = x * y

print(z)

In this case, variable "z" is assigned the value of 3.75.

The float data type is one of the frequently used data types in Python and is used for numerical calculations that require decimal point precision. However, it is important to note that there can be issues with precision.

str (string)

A string is a sequence of any characters, including letters, numbers, and symbols. The str type in Python can represent text strings enclosed in either double or single quotes.

To use the str type, simply assign a string to a variable.

For example, you can assign the string "John" to the variable "name" like this:

name = "John"

In Python, there are many operations you can perform on strings. String operations include string concatenation, string substitution, slicing, and getting the length of a string, among others.

For example, you can assign strings to variables "first_name" and "last_name", concatenate them together, and assign the result to variable "full_name" like this:

first_name = "John"

last_name = "Doe"

full_name = first_name + " " + last_name

print(full_name)

In this case, variable "full_name" is assigned the value of "John Doe".

The str data type is one of the frequently used data types in Python and is used for text processing and string manipulation.

String manipulation

There is no need to force yourself to learn these operations. Just search for them when you need them.

Concatenate

You can concatenate strings using the "+" operator.

str1 = "Hello"

str2 = "World"

str3 = str1 + " " + str2

print(str3)  # "Hello World"
Replace

To replace a part of a string with another string, you can use the replace() method.

str1 = "apple"

str2 = str1.replace("a", "b")

print(str2)  # "bpple"
Split

To split a string by a specified delimiter, you can use the split() method.

str1 = "apple,banana,orange"

list1 = str1.split(",")

print(list1)  # ["apple", "banana", "orange"]
Converting Case

To convert a string to uppercase, you can use the upper() method.

To convert a string to lowercase, you can use the lower() method.

str1 = "Hello World"

str2 = str1.upper()

str3 = str1.lower()

print(str2)  # "HELLO WORLD"

print(str3)  # "hello world"
Removing Leading and Trailing Spaces

To remove leading and trailing spaces from a string, you can use the strip() method.

str1 = "   Hello World   "

str2 = str1.strip()

print(str2)  # "Hello World"
Accessing Characters at a Specific Position

To access a character at a specific position in a string, you can use the index of the character.

str1 = "Hello"

char1 = str1[0]  # Get first character. 

char2 = str1[1]  # Get the second character.

print(char1)  # "H"

print(char2)  # "e"
Getting the Length

To get the length of a string, you can use the len() function.

str1 = "Hello World"

length = len(str1)

print(length)  # 11
Formatting

To insert variables or values into a string, you can use "{}" in the string and use the format() method to create the string.

name = "John"

age = 30

greeting = "My name is {}, and I am {} years old.".format(name, age)

print(greeting)  # "My name is John, and I am 30 years old."
Searching for a Substring

To check if a string contains a specific substring, you can use the "in" operator.

str1 = "Hello World"

if "World" in str1:
    print("Found")  # "Found"

bool (Boolean)

Boolean values are used to represent two states: true or false. The bool type in Python is used to express whether a condition is true or false. Conditions are evaluated using operators such as comparison operators and logical operators.

When using the bool type, a condition can be assigned to a variable.

For example, the following code assigns a comparison operator to the variable "x":

x = 5 > 3

In this case, the condition "5 > 3" is true, so the variable "x" is assigned the Boolean value of "True".

The bool type is frequently used in Python for controlling the flow of code (using control structures such as if statements, for loops, and while loops) and as return values for functions. Multiple conditions can also be combined using logical operators.

For example, the following code assigns comparison operators to variables "x" and "y", and then uses logical operators to combine them into a single condition assigned to the variable "z":

x = 5 > 3

y = 2 < 1

z = x and not y

print(z)

In this case, the condition "x and not y" is evaluated, resulting in the Boolean value of "True" being assigned to the variable "z".

The bool type is one of the most frequently used data types in Python, used for evaluating conditions and controlling the flow of code.

list

The list data type in Python is used to store multiple values in an ordered sequence.

Create

A list is made up of multiple elements enclosed in square brackets "[]", separated by commas.

For example, the following code creates a list of elements that include numbers and strings:

numbers = [1, 2, 3, 4, 5]

fruits = ['apple', 'orange', 'banana']

print(numbers)

print(fruits)

To create an empty list in Python, you can use square brackets "[]".

Here is an example of creating an empty list:

my_list = []

In this example, an empty list named "my_list" is created.

Retrieve element.

To retrieve an element from a list, you need to specify the element's index. The first element of a list has an index of 0, the second has an index of 1, and so on.

Here is an example of using list indexes to retrieve elements from a list:

fruits = ['apple', 'orange', 'banana']

print(fruits[0])  # apple

print(fruits[1])  # orange

print(fruits[2])  # banana

In this example, the variable "fruits" is assigned a list, and the indexes are used to retrieve elements from the list.

You can also specify negative indexes to retrieve elements from the end of the list. When using negative indexes, the elements are specified in reverse order from the end of the list. For example, the last element has an index of -1, the second-to-last element has an index of -2, and so on.

Here is an example of using negative indexes to retrieve elements from a list:

fruits = ['apple', 'orange', 'banana']

print(fruits[-1])  # banana

print(fruits[-2])  # orange

print(fruits[-3])  # apple

Additionally, the slicing feature of lists can be used to extract a portion of the list.

numbers = [1, 2, 3, 4, 5]

some_numbers = numbers[1:4]

print(some_numbers)  # [2, 3, 4]

It is also possible to retrieve all elements using a loop.

my_list = [1, 2, 3, 4, 5]

# Loop through all elements in the list
for item in my_list:
    print(item)

This will assign each element in the list to the variable item, and print it out using the print() function.

If you also want to get the index number of each element, you can use the enumerate() function like this:

my_list = [1, 2, 3, 4, 5]

# Loop through all elements in the list and their index numbers
for index, item in enumerate(my_list):
    print(f"Index {index}: {item}")

This will assign each element in the list to the variable item, and its index number to the variable index, and print them out using the print() function.

Lists are frequently used in Python for storing arrays and sets of data.

Get the number of elements.

To get the number of elements in a Python list, you can use the built-in function "len()". The len() function returns the number of elements in the list.

Here is an example of getting the number of elements in a list:

fruits = ['apple', 'orange', 'banana']

print(len(fruits))  # 3

In this example, the len() function is used to get the number of elements in the "fruits" list. The result is displayed as "3".

Note that the len() function can also be used to get the number of elements in other Python objects, such as strings, tuples, and dictionaries.

Edit element.

Lists can be modified by adding, removing, and changing elements.

There is no need to force yourself to learn these operations. Just search for them when you need them.

Add

Tail

To add an element, the "append" method can be used:

numbers = [1, 2, 3, 4, 5]

numbers.append(6)

print(numbers)  # [1, 2, 3, 4, 5, 6]
Head

To add an element to the beginning of a list in Python, you can use the built-in function "insert()". This function allows you to insert a new element at a specified position in the list. To add an element to the beginning of a list, you can specify the argument 0.

Here is an example of adding an element to the beginning of a list:

my_list = [1, 2, 3, 4, 5]

my_list.insert(0,0)

print(my_list)  # [0, 1, 2, 3, 4, 5]

In this example, the original list before adding the element was [2, 3, 4, 5] and then the built-in function "insert()" is used to add a new element "1" at the beginning of the list. As a result, the list [1, 2, 3, 4, 5] is displayed.

Specified position.

To insert an element at a specified position in a list, you can use the built-in function "insert()".

The "insert()" function can insert an element at a specified position in a list.

Here is an example of inserting an element at a specified position in a list:

my_list =[1, 2, 3, 4, 5]

my_list.insert(2, 'new')

print(my_list)  # [1, 2, 'new', 3, 4, 5]

In this example, five elements are added to the list "my_list" and then "new" is inserted at position 2. As a result, the element "new" is added to the specified position in the list and the resulting list is "[1, 2, 'new', 3, 4, 5]".

Delete

One element is specified as a value.

The "remove" method can be used:

numbers = [1, 2, 3, 4, 5]

numbers.remove(3)

print(numbers)  # [1, 2, 4, 5]
One element is specified as a index.

The "del" keyword with the element's index.

Here is an example of removing an element from a list using its index:

fruits = ['apple', 'orange', 'banana']

del fruits[1]  # remove the element at index 1 (i.e., 'orange')

print(fruits)  # ['apple', 'banana']
Multiple elements

You can also remove multiple elements at once by specifying a range of indexes. Here is an example:

fruits = ['apple', 'orange', 'banana', 'grape', 'kiwi']

del fruits[1:4]  # remove elements with indexes 1, 2, and 3

print(fruits)  # ['apple', 'kiwi']

In this example, elements with indexes 1, 2, and 3 are removed from the "fruits" list.

Note that when you remove an element from a list, the indexes of the remaining elements may change. If you need to remove multiple elements from a list, make sure to check the indexes of the remaining elements after each deletion.

All elements

To delete all elements from a list in Python, you can use the built-in function "clear()".

Here is an example of deleting all elements from a list:

my_list = [1, 2, 3, 4, 5]

my_list.clear()

print(my_list)  # []

In this example, five elements are added to the list "my_list" and then all elements are deleted using "clear()". As a result, an empty list "[]" is displayed.

Update

To change an element, the index of the element can be specified and then assigned a new value:

numbers = [1, 2, 3, 4, 5]

numbers[2] = 10

print(numbers)  # [1, 2, 10, 4, 5]

Join

To concatenate lists in Python, you can use the "+" operator or the "extend()" method.

When using the "+" operator, you can concatenate two lists by using the "+" operator between them. Here is an example of concatenating two lists using the "+" operator:

list1 = [1, 2, 3]

list2 = [4, 5, 6]

concatenated_list = list1 + list2

print(concatenated_list)  # [1, 2, 3, 4, 5, 6]

In this example, two lists "list1" and "list2" are concatenated using the "+" operator to create a new list called "concatenated_list".

When using the "extend()" method, you can add a specified list to the end of the calling list by passing the list as an argument to the "extend()" method. Here is an example of concatenating two lists using the "extend()" method:

list1 = [1, 2, 3]

list2 = [4, 5, 6]

list1.extend(list2)

print(list1)  # [1, 2, 3, 4, 5, 6]

In this example, two lists "list1" and "list2" are concatenated using the "extend()" method, and the original "list1" is updated.

tuple

A tuple is another data type in Python that allows you to store multiple values, like a list.

Tuples are created using parentheses "()" and the elements of a tuple are separated by commas.

Here is an example of creating a tuple:

fruits = ('apple', 'orange', 'banana')

Unlike a list, once a tuple is created, its elements cannot be changed. However, the elements within a tuple themselves may be mutable.

To access elements in a tuple, you can use the same indexing and slicing syntax as you would with a list.

Here is an example of accessing elements in a tuple:

fruits = ('apple', 'orange', 'banana')

print(fruits[0])  # apple

print(fruits[1])  # orange

print(fruits[2])  # banana

To get the number of elements in a Python tuple, you can use the built-in function "len()".

Here is an example of getting the number of elements in a tuple:

fruits = ('apple', 'orange', 'banana')

print(len(fruits))  # 3

In this example, the len() function is used to get the number of elements in the "fruits" tuple. The result is displayed as "3".

Note that the len() function can also be used to get the number of elements in other Python objects, such as lists, strings, and dictionaries.

Tuples are lighter than lists and are immutable, making them suitable for situations where you have data that won't change and don't want to risk unintentional modification of the data.

dictionary

Python's dictionary is a data type for storing multiple values as key-value pairs. Unlike lists or tuples, elements in a dictionary can be accessed using keys instead of indexes.

Create

You can use curly braces {} and separate the key-value pairs with a colon :. For example:

In this example, "key1" is a key and "value1" is the corresponding value. Similarly, "key2" is a key with the corresponding value "value2". You can use any immutable object, such as strings or numbers, as keys. Values can be any Python objects, including strings, numbers, lists, dictionaries, tuples, and booleans.

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

To create an empty dictionary, you can use curly braces {}.

my_dict = {}

Retrieve element.

To retrieve an item from a dictionary in Python, you can use the key to look up the value in the dictionary using square brackets []. For example:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Retrieve the value associated with the key "key1"

value = my_dict ["key1"]

print(value)  # "value1" will be displayed

This will assign the value associated with the key "key1" to the variable value.

Note that if you try to look up a key that does not exist in the dictionary, you will get a KeyError. To avoid this, you can check whether the key is in the dictionary before trying to retrieve the value. You can do this using the in keyword, like this:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Check whether the key "key4" is in the dictionary
if "key4" in my_dict:
    value = my_dict["key4"]
    print(value)
else:
    print("key4 not found in my_dict")

In this case, "key4" is not in the dictionary, so the else block will be executed and "key4 not found in my_dict" will be displayed.

It is also possible to retrieve all elements using a loop.

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Loop through all elements in the dictionary
for key, value in my_dict.items():
    print(key, value)

This will assign each key-value pair in the dictionary to the variables key and value, and print them out using the print() function.

The items() method returns a list of key-value pairs as tuples, which are then unpacked into the variables key and value in the for loop.

If you only want to loop through the keys of the dictionary, you can use the keys() method like this:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Loop through all keys in the dictionary
for key in my_dict.keys():
    print(key)

If you only want to loop through the values of the dictionary, you can use the values() method like this:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Loop through all values in the dictionary
for value in my_dict.values():
    print(value)

Get the number of elements.

To get the number of items in a dictionary in Python, you can use the len() function. For example:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Get the number of items in the dictionary
length = len(my_dict)

print(length)  # will display 3

This will assign the number of items in the dictionary to the variable length, and display it using the print() function.

The number of items in a dictionary is equal to the number of key-value pairs in the dictionary. For an empty dictionary, the number of items will be 0.

Edit element.

Dictionary can be modified by adding, removing, and changing elements.

There is no need to force yourself to learn these operations. Just search for them when you need them.

Add and Update

To add an element to the dictionary in Python, you need to update an existing key-value pair or add a new key-value pair. To add a key-value pair to a dictionary, you can do the following:

my_dict = {"key1": "value1", "key2": "value2"}

# Add a new key-value pair
my_dict["key3"] = "value3"

print(my_dict)

In this code, we add a new key-value pair {"key3": "value3"} to the dictionary my_dict. We then use the print() function to output the updated dictionary.

If the key does not already exist in the dictionary, a new key-value pair will be added. If the key already exists in the dictionary, the corresponding value will be updated.

Delete

One element

To remove an element from a dictionary in Python, you can use the del statement. This statement removes the key-value pair corresponding to the specified key.

Here is an example of removing an element from a dictionary:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Remove the key-value pair corresponding to the key "key2"

del my_dict["key2"]

print(my_dict)

In this code, we remove the key-value pair corresponding to the key key2. If the dictionary does not contain the key key2, a KeyError will be raised. We then use the print() function to output the updated dictionary.

All elements

To remove all elements from a dictionary in Python, you can use the clear() method. This method removes all key-value pairs from the dictionary.

Here is an example of removing all elements from a dictionary:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Remove all elements from the dictionary

my_dict.clear()

print(my_dict)

In this code, we use the clear() method to remove all key-value pairs from the dictionary. We then use the print() function to output an empty dictionary.

For those who want to learn Python efficiently.

The information on this site is now available in an easy-to-read e-book format for $3.00.

Or Kindle Unlimited (unlimited reading).

This textbook is used for new employees with no programming experience.

This book focuses on basic programming topics.

We do not cover topics such as object-oriented programming, statistical analysis using Python-specific libraries, machine learning, as these topics are difficult to understand from the standpoint of initial programming learning.

This book is especially recommended for those who have no experience with programming.

Links

Python Articles

Python
Exit mobile version