[Tutor] ok i need some help with a for loop
Christian Witts
cwitts at compuscan.co.za
Thu Oct 15 16:47:07 CEST 2009
Skylar Struble wrote:
> ok so im working on a text based rpg game and am trying to get this
> code to work,
>
> items = ['crate', 'grave']
> lookwords = ['look', 'examine', 'investigate','open')
> input1 = raw_input('What do you want to do:')
> for word in items:
> for word2 in lookwords:
> if word and word2 in input1:
> print 'you look in the crate and find a map!'
> else:
> print 'sorry you used a word i didnt understand'
>
> it prints out all of the print things 2 times when i want it to print
> 1 or the other because what im trying to do is see if the input1 has
> both an item from items and lookwords in the string and if so print
> you look in the map or if it finds 1 or none to print sorry you used a
> word i didnt understand
>
>
> thanks for takeing the time to read this and gl.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
What you could do is transform it a little to something like the following:
items = ['crate', 'grave']
lookwords = ['look', 'examine', 'investigate','open')
input1 = raw_input('What do you want to do:')
success = False
for lw in lookwords:
if lw in input1:
for iw in items:
if iw in input1:
print 'You %s and found a map.' % input1
success = True
if success:
break
if success:
break
if not success:
print 'You used a word I did not understand'
That will first check to see if any of your `lookwords` are contained in the input (if they're not there why bother continuing as they haven't chosen a valid action) and if their input does contain the action then carry on and check to see if a valid item was selected.
If a valid item was selected then the variable `success` will be made True and before the next iteration it will break out of the loop (useful for speed if you have large lists of objects / actions to get through). If it loops through everything and doesn't find any matches it will print out 'You used a word I did not understand' because the success variable is still False.
This is just a rather basic idea, but it will get the job done.
--
Kind Regards,
Christian Witts
More information about the Tutor
mailing list