How to print list with from input with specific items? For example with names which ends with x. I've got this code
while True:
name = input("Enter your name: ")
if name == "":
break
list = []
namex = name.endswith("x")
if name == namex:
list.append(name)
print (list)
but when i try to print list it gives me nothing:
>>> Enter your name: alex
Enter your name: james
Enter your name: abcx
Enter your name:
>>>
Your issue is that namex is a boolean , not a string .
>>> 'abc'.endswith("x")
False
>>> 'abcx'.endswith("x")
True
This means that any equality comparison between a string and a boolean will return false. You want to trigger the "if" statement if the statement ends with "x", or:
names = []
while True:
name = input("Enter your name: ")
if name == "":
break
namex = name.endswith("x")
# namex is a boolean type, which if it is True, will trigger an if statement
if namex:
names.append(name)
print(names)
namex = name.endswith("x")
if name == namex:
Does not do what you think it does. name.endswith("x")
returns True
or False
. Should be
if name.endswith("x"):
instead.
names = []
while True:
name = input("Enter your name: ")
if name == "":
break
if name.endswith("x"):
names.append(name)
print (names)
List comprehension iter
version:
>>> [name for name in iter(input, '') if name.endswith('x')]
dsf
sdfdsf
dsffdx
sx
['dsffdx', 'sx']
Here, I am storing all the names ending with 'x' in namex_list
instead of using the list
(also a built-in variable) variable you used before.
Also, i am assigning namex_list
as an empty list before the while condition and printing the namex_list
at the end outside of while
.
namex_list = []
while True:
name = input("Enter your name: ")
if name == "":
break
if name.endswith("x"):
namex_list.append(name)
print (namex_list)
Also, name == namex
does not check what you are trying to achieve because of the comparison between string values and boolean values.
For example:
>>> name1 = 'abc'
>>> name2 = 'abcx'
>>> namex1 = name1.endswith('x')
>>> namex2 = name2.endswith('x')
>>> namex1
False
>>> namex2
True
>>> name1 == namex1
False
>>> name2 == namex2
False
You should use an if
instead to achieve what you are trying to achieve in your code above:
if name.endswith("x"):
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.