True false int python

Логический тип данных (bool) в Python

Логический тип данных (bool) (или булевый тип) это примитивный тип данных, который принимает 2 значения — истина или ложь.

В Python имеется самостоятельный логический тип bool , с двумя предопределенными значениями:

True и False пишутся с большой буквы. Если написать с маленькой true , интерпретатор выдаст ошибку: NameError: name ‘true’ is not defined

True и False являются экземплярами класса bool который в свою очередь является подклассом int Поэтому True и False в Python ведут себя как числа 1 и 0. Отличие только в том, как они выводятся на экран.

>>> True True >>> type(True) >>> isinstance(True, int) True >>> True == 1 True >>> True + 4 # True это число 1 5 >>> 5 * False # False это число 0 0

Часто логический тип данных используется в ветвлениях if . Если результат выполнения True — выполняется соответствующая ветка.

Цикл while работает аналогичным образом — цикл выполняется до тех пор, пока логическое выражение True .

Читайте также:  Формат print в питоне

>>> count = 5 >>> while count: print(«count = <>«.format(count)) count -= 1 count = 5 count = 4 count = 3 count = 2 count = 1

Преобразования

Другие типы → bool

В Python для приведения других типов данных к булевому типу, используется функция bool() Работает эта функция по следующему соглашению:

  • непустая строка (в том числе если это один или несколько пробелов);
  • ненулевое число (в том числе меньшее единицы, например -5);
  • непустой список/кортеж (даже если он содержит один пустой элемент, например пустой кортеж);
  • функция.

👉 Функция bool() вернет False:

bool → str

Бывают ситуации, когда нам необходимо получить True и False в строковом представлении. Если выполнить код ниже, он вызовет ошибку:

print(«answer is » + True) TypeError: can only concatenate str (not «bool») to str

Ошибка произошла потому, что Python не выполняет неявное приведение типов (как например JavaScript), так как неявное приведение может маскировать логические ошибки.

Для вывода на экран булевого значения, необходимо привести его к строке:

>>> answer = True >>> print(«my answer is » + str(True)) my answer is True

или используйте форматирование строки:

print(«my answer is <>«.format(True))

bool → int

Встроенная функция int() преобразует логическое значение в 1 или 0.

Аналогичного результата можно добиться умножением логического типа на единицу:

Логический тип и операторы

Операторы — это своего рода функционал, представленный в виде символов (например + ==) или зарезервированных слов (например and not).

В Python используется несколько типов операторов. Мы же рассмотрим только операторы сравнения и логические операторы , т.к. результатом их выполнения являются True или False .

>>> 1 == 5 False >>> 1 != 5 True >>> 1 > 5 False >>> 1 < 5 True >>> 1 >= 5 False >>> 1

>>> (1 + 1 == 2) or (2 * 2 == 5) True >>> (1 + 1 == 2) and (2 * 2 == 5) False >>> (1 + 1 == 2) and not (2 * 2 == 5) True

Источник

Convert bool (True, False) and other types to each other in Python

In Python, truth values (Boolean values) are represented by bool type objects, True and False . Results by comparison operators are returned as True or False and are used in conditional expressions in if statements, etc.

bool is a subclass of int

True and False are objects of bool type.

print(type(True)) # print(type(False)) # 

You can confirm that bool is a subclass of the integer type int with the built-in function issubclass() .

print(issubclass(bool, int)) # True 

True and False are equivalent to 1 and 0

True and False are equivalent to 1 and 0 .

print(True == 1) # True print(False == 0) # True 

Since bool is a subclass of int , it can be calculated like integers.

print(True + True) # 2 print(True * 10) # 10 

Therefore, you can count the number of True in the list of True and False using the built-in function sum() which calculates the sum of the numbers stored in the list.

print(sum([True, False, True])) # 2 

A generator expression can be used to count the number of elements in a list that meet certain conditions. Use [] for list comprehensions and () for generator expressions.

When the generator expression is the only argument of the function, () can be omitted, so it can be written as follows.

l = [0, 1, 2, 3, 4] print([i > 2 for i in l]) # [False, False, False, True, True] print(sum(i > 2 for i in l)) # 2 

Truth value testing in Python

In Python, objects other than True and False are also evaluated as true or false in the conditional expressions of if statements.

The following objects are considered False , as in the official documentation above.

  • Constants defined to be false: None and False
  • Zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1)
  • Empty sequences and collections: » , () , [] , <> , set() , range(0)

All other objects are considered True .

For example, a non-empty string is considered True .

You can check if an object is considered as True or False by using bool() explained below.

Convert other types to bool : bool()

You can convert objects of other types to True or False with bool() according to the truth value testing described above.

Any non-empty string, whether ‘True’ or ‘False’ , evaluates to True . An empty string is considered False . If you want to convert based on the contents of the string, use distutils.util.strtobool() explained below.

print(bool('True')) print(bool('False')) print(bool('abc')) # True # True # True print(bool('')) # False 

Any number that is not 0 , whether it is an integer int , a floating-point number float , or a complex number complex , is considered True . If it is 0 , it is considered False .

print(bool(1)) print(bool(2)) print(bool(1.23)) print(bool(-1)) # True # True # True # True print(bool(0)) print(bool(0.0)) print(bool(0j)) # False # False # False 

All non-empty sequences and collections, such as lists, tuples, sets, or dictionaries, evaluate to True . Empty sequences and collections evaluate to False .

print(bool([1, 2, 3])) print(bool((1, 2, 3))) print(bool(1, 2, 3>)) print(bool('k1': 1, 'k2':2, 'k3': 3>)) # True # True # True # True print(bool([])) print(bool(())) print(bool(<>)) # False # False # False 

Convert a specific string to 1 , 0 : distutils.util.strtobool()

As mentioned above, bool() converts the string ‘False’ to True .

You can convert a string according to its contents with distutils.util.strtobool() .

Convert a string representation of truth to true (1) or false (0). True values are y , yes , t , true , on and 1 ; false values are n , no , f , false , off and 0 . Raises ValueError if val is anything else. 9. API Reference — distutils.util.strtobool() — Python 3.11.3 documentation

You need to import distutils.util . It is included in the standard library, so no additional installation is required.

distutils.util.strtobool() returns 1 for the strings ‘y’ , ‘yes’ , ‘true’ , ‘on’ , ‘1’ , and returns 0 for ‘n’ , ‘no’ , ‘f’ , ‘false’ , ‘off’ , ‘0’ .

Case sensitivity does not matter; you can use ‘TRUE’ , ‘True’ , ‘YES’ , and so on.

from distutils.util import strtobool print(strtobool('true')) print(strtobool('True')) print(strtobool('TRUE')) # 1 # 1 # 1 print(strtobool('t')) print(strtobool('yes')) print(strtobool('y')) print(strtobool('on')) print(strtobool('1')) # 1 # 1 # 1 # 1 # 1 print(strtobool('false')) print(strtobool('False')) print(strtobool('FALSE')) # 0 # 0 # 0 print(strtobool('f')) print(strtobool('no')) print(strtobool('n')) print(strtobool('off')) print(strtobool('0')) # 0 # 0 # 0 # 0 # 0 

Raises ValueError for other values.

# print(strtobool('abc')) # ValueError: invalid truth value 'abc' 

If you want to accept input other than the specified strings, you need to handle exceptions.

try: strtobool('abc') except ValueError as e: print('other value') # other value 

The name is strtobool() , but the return value is int ( 1 or 0 ) instead of bool ( True or False ).

In conditional expressions like if statements, 1 and 0 are treated as True and False , respectively, so you can use them directly.

if strtobool('yes'): print('True!') # True! 

Convert bool to other types

Convert bool to number: int() , float() , complex()

As mentioned above, since True and False are equivalent to 1 and 0 , they can be converted to 1 and 0 of the respective types with int() , float() , and complex() .

print(int(True)) print(int(False)) # 1 # 0 print(float(True)) print(float(False)) # 1.0 # 0.0 print(complex(True)) print(complex(False)) # (1+0j) # 0j 

Convert bool to string: str()

You can convert True and False to strings ‘True’ and ‘False’ with str() .

print(str(True)) print(str(False)) # True # False print(type(str(True))) print(type(str(False))) # # 

Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .

Other types

list() and tuple() cannot convert bool types to lists and tuples. It will not be converted to an empty list.

# print(list(True)) # TypeError: 'bool' object is not iterable 

Источник

How to Convert bool to int in Python | Convert bool to string in Python

In this Python tutorial, we will discuss, how to convert bool to int in Python as well as I will show you how to convert bool to string in Python.

Boolean in Python

In Python, Boolean is a data type that is used to store two values True and False. We can also evaluate any expression and can get one of two answers. And While comparing two values the expression is evaluated to either true or false. Bool is used to test the expression in Python.

my_string = "Hello Sam" print(my_string.isalnum())

You can refer to the below screenshot:

python bool to int

When we compare two values, the expression is evaluated and it returns the Boolean answer which is either true or false.

After writing the above code, once we will print then the output will appear as “ False ”. Here, a is not greater than b so it returns the output as false.

You can refer to the below screenshot:

bool to int python

Convert boolean to string in Python

To convert a boolean to a string in Python, we will use str(bool) and then convert it to string.

bool = True my_string = str(bool) print(my_string) print(type(my_string))

Once you execute the code, it will print “my_string and type(my_string)” then the output will appear as “ True ”. Here, str(bool) is used to convert a boolean to a string in Python.

You can refer to the below screenshot.

boolean to string python

With this example, I have shown you how to convert a boolean to string in Python.

Convert bool to int in Python

To convert a boolean to an integer in Python, we will use int(bool) and then convert it to an integer.

bool = True my_integer = int(bool) print(my_integer) print(type(my_integer))

Once you run the code, it will print “my_integer and type(my_integer)” then the output will appear as “ 1 ”. Here, int(bool) is used to convert a boolean to an integer value.

You can refer to the below screenshot:

python bool to int

This is how to convert bool to int in Python.

You can also convert a boolean to an integer in Python by performing arithmetic operations like addition or multiplication with 0 or 1.

# Using arithmetic operations a = True # This is boolean b = False # This is boolean # Performing arithmetic operations to convert boolean to integer int_a = a * 1 int_b = b + 0 print(int_a) # Output: 1 print(int_b) # Output: 0

Conclusion

In this tutorial, I have explained to you, how to convert a bool to an int in Python and how to convert a bool to a string in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Оцените статью