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":
Any string is True , except empty strings. Any number is True , except 0 . Any list, tuple, set, and dictionary are True , except empty ones.
Any non-empty string str , whether 'True' or 'False' , is considered True . An empty string is considered False .
Iterate over the set and use count function (i.e. string. count(newstring[iteration])) to find the frequency of word at each iteration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With