simple coding help, using the if and or functions

This is the place for queries that don't fit in any of the other categories.

simple coding help, using the if and or functions

Postby RainyCats » Thu Aug 22, 2013 1:30 pm

hello,
im brand new to python so im doing some simple exercises and i am stuck on one.

this is the code:

Code: Select all
>>> words= ["pizazz", "python", "zebra", "pizza"]
>>> for x in words:
...     if x[0] in 'z':
...         print x
...
zebra
>>> for x in words:
...     if x[-1] in 'z':
...         print x
...
pizazz
>>> for x in words:
...     if x[0] or x[-1] in 'z':
...         print x
...
pizazz
python
zebra
pizza



when i try to print all the words beginning or ending in z, python prints all the words. I am using python 2.7.2
Thank you for any help,love,
Rainy
RainyCats
 
Posts: 2
Joined: Thu Aug 22, 2013 1:27 pm

Re: simple coding help, using the if and or functions

Postby stranac » Thu Aug 22, 2013 2:31 pm

Code: Select all
if x[0] or x[-1] in 'z':

This evaluates to True when any of these evaluates to True:
  • x[0]
  • x[-1] in 'z' -- you probably want to use == here instead of in

Solution:
Code: Select all
if x[0] == 'z' or x[-1] == 'z':
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 907
Joined: Thu Feb 07, 2013 3:42 pm

Re: simple coding help, using the if and or functions

Postby RainyCats » Thu Aug 22, 2013 2:38 pm

thanks alot your post told me where the problem was!, i tweaked my code:

Code: Select all
words = ["pizazz", "python", "zebra", "pizza"]
>>> for x in words:
...     if x[0] in 'z' or x[-1] in 'z':
...         print x


it seems i wasnt being specific enough my functions :) thanks a lot!!
RainyCats
 
Posts: 2
Joined: Thu Aug 22, 2013 1:27 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests