понедельник, 11 мая 2020 г.

Типы переменных в Python - String, Integer, Float, Boolean, List, Dictionary, Tuple.

Существуют несколько типов переменных в Пайтон:

1.

STRING (str)

- Это строка. Чтобы задать этот тип, нужно данные взять в ковычки (не важно одинарные или двойные)
a = "text"

dir(str) - Чтобы вывести весь список доступных для данного типа данных функций.

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']



2.

INTEGER (int)

- Целое число. Задается без ковычек.
b = 10

dir(int)

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']



3.

FLOAT

- Это дробное число. Задается без ковычек с точкой.
c = 10.2

dir(float)

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']


4.

BOOLEAN (bool) 

- Значение этой переменной может быть только TRUE или FALSE.
d = True

dir(bool)

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']


5.

LIST [Список] 

mutable (может быть изменен) в отличии от Tuple.

- это список переменных. Он может содержать любое количество переменных разного типа (в примере 4 переменные разного типа).
list = [10, 10.4, "text", "24759"]

List также может содержать другой list
list = [0, 10.4, "text", [8, 'efhe']]

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


RANGE 

- эта функция позволяет создать список с указанным диапазомом.
list(range(1, 6))
Это то же самое, что:
[1, 2, 3, 4, 5]
Обратите внимание, что 6 не попадает в список!

Можно указать еще ШАГ в качестве третьего аргумента
list(range(1, 6, 2))
[1, 3, 5]
то есть это все числа в переделах диапазона с 1 до 5 с шагом 2


При необходимости, можно изменить тип переменной в программе.
Например, программа-калькулятор запрашивает числа, чтобы потом выполнить действия с ними... Для этого мы будет использовать функцию INPUT, но она воспринимает всегда данные как строку.

a = input("Введите число A")
b = input("Введите число B")

Предположим пользователь указал a = 5, b = 3.
Пользователь вводит числa. Но если мы сложим их сейчас, то получим:
c = a + b = 53

Потому что 5 и 3 - это текст.

Чтобы в программе переделать текст на числа, добавляем нужный нам формат - float или integer.

a = float (input ("Введите число A:   "))
b = float (input ("Введите число B:   "))
c = a + b
print ("Результат = " + str(c))

Результат нам надо было переделать обратно в строку для печати. Поэтому в функции print - указываем - str(c)


APPEND - Добавляет 1 элемент в список

list = [10, 10.4, "text", "24759"]
list.append(1)
print(list)
Результат
[10, 10.4, 'text', '24759', 1]

MAX - Найти максимальное значение в списке

student_grades = [9.1, 8.8, 7.5]

max_value = max(student_grades) print(max_value)

Результат:
9.1



6.

DICTIONARY (dict) {Словарь}


student_grades = {"Marie": 12, "John": 5, "Max": 6, "Michael": 10, "Anna": 11}

Про словари можете почитать в СТАТЬЕ.

Словарь может содержать внутри себя любые элементы. 
Пример - Словарь содержит 3 переменные с кортежем данных для каждого времени суток).

day_temperatures = {'morning':(1.3, 2.1, 3.0), 'noon':(19.6, 34.4, 1.2), 'evening':(2.3, 4.4, 4.7)}

dir(dict)

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']



7.

TUPLE (Кортеж) 

- immutable в отличии от List.
Это значит, что кортеж не может быть изменен (не может мутировать)

temperature = (10, 24, 5, 19, 2)

Кортеж может содержать внутри себя любые другие переменные.
color_codes = (("green", "red", "white"), (1,2), (3974, "uougo"))  
-  Кортеж содержит внутри себя 3 других кортежа

dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']


HELP


Можно почитать документацию по командам или переменным в Python, используя HELP

help(str) 

help(str.replace) 

replace(self, old, new, count=-1, /)
    Return a copy with all occurrences of substring old replaced by new.
    
      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.

help(dict.values)

values(...)
    D.values() -> an object providing a view on D's values



Комментариев нет:

Отправить комментарий

Самые полезные ФУНКЦИИ Пайтона

 1)  PRINT - выводит на печать переменную, указанную в скобках print (average)   2)  LEN - посчитать количество элементов в списке student...