What is the boolean value of "string" in Python?

I mistakenly wrote this code in Python:

name = input("what is your name?") if name == "Kamran" or "Samaneh": print("That is a nice name") else: print("You have a boring name ;)") 

He always prints β€œThis is a beautiful name,” even if the entrance is not β€œKamran” or β€œSamaneh”.

Am I right in saying that he considers Samana to be true? Why?

By the way, I already noticed my mistake. The correct form:

 if name == "Kamran" or name == "Samaneh": 
+8
python string casting boolean
source share
6 answers

Any non-empty string in Python (and most other languages) is true, like all non-zero numbers and non-empty lists, dictionaries, sets, and tuples. one

A more convenient way to do what you want:

 name = input("what is your name?") if name in ("Kamran", "Samaneh"): print("That is a nice name") else: print("You have a boring name ;)") 

This creates a tuple containing the names you want and performs a membership test.

1 As Delnan notes in the comments, this applies to all well-written collections. That is, if you are implementing your own collection class, make sure that it is erroneous when it is empty.

+9
source share

Besides the empty string '' , the strings will be evaluated as True (see this page for a complete list of values ​​of all types that evaluate to False . This follows the logic of many other programming languages ​​(except for some that also evaluate strings such as '0' , 'false' , etc. to False .) The exact decision about what to do is somewhat arbitrary, but the choice made can be explained by the fact that it allows the actor to be used as a simple way to check for empty (default or unvisited) strings.

You can always force casting of any type to bool using the bool() function.

 >>> bool('') False >>> bool('non-empty string') True >>> bool('0') True >>> bool('False') True >>> bool('false') True 
+6
source share

http://docs.python.org/library/stdtypes.html#truth-value-testing

".... All other values ​​are considered true, so objects of many types are always true."

+2
source share

In Python, an empty string is considered False , True otherwise.

You can use the in operator:

 if name in ("Kamran","Samaneh"): print("That is a nice name") else: print("You have a boring name ;)") 
+2
source share

Non-empty string - True, yes. Empty value False. It is super convenient.

0
source share

Obviously, this should be:

 name = raw_input("what is your name?") 

not

 name = input("what is your name?") 

.

What you wrote looks like:

 if (name == "Kamran" or "Samaneh") 

Another good expression is:

 if name == ("Kamran" or "Samaneh") 

But I also prefer the name in ("Kamran" or "Saman"), as already shown

.

By the way, it can be written:

 print("That is a nice name" if raw_input("what is your name?") in ("Kamran","Samaneh") else "You have a boring name ;)") 
-2
source share

Source: https://habr.com/ru/post/650442/


All Articles