Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the logical value of "string" in Python? [duplicate]

I erroneously 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 ;)")

It always prints out "That is a nice name" even when the input is neither "Kamran" nor "Samaneh".

Am I correct in saying that it considers "Samaneh" as a true? Why?

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

if name == "Kamran" or name == "Samaneh":
like image 734
Kamran Bigdely Avatar asked Dec 25 '10 21:12

Kamran Bigdely


People also ask

Is string a true value in Python?

Any string is True , except empty strings. Any number is True , except 0 . Any list, tuple, set, and dictionary are True , except empty ones.

Is a string true or false in Python?

Any non-empty string str , whether 'True' or 'False' , is considered True . An empty string is considered False .

How do you count repeated words in a string in Python?

Iterate over the set and use count function (i.e. string. count(newstring[iteration])) to find the frequency of word at each iteration.


1 Answers

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

A nicer way to do what you want is:

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 that you want and performs a membership test.

1 As delnan points out in the comments, this applies to all well written collections. That is, if you implement a custom collection class, make sure that it is false when it's empty.

like image 128
aaronasterling Avatar answered Oct 22 '22 05:10

aaronasterling