Beginner question

Larry Hudson orgnut at yahoo.com
Tue Jun 4 05:13:16 EDT 2013


On 06/03/2013 08:39 PM, eschneider92 at comcast.net wrote:
> Is there a more efficient way of doing this? Any help is gratly appreciated.
>
>
> import random
> def partdeux():
>      print('''A man lunges at you with a knife!
> Do you DUCK or PARRY?''')
>      option1=('duck')
>      option2=('parry')
>      optionsindex=[option1, option2]
>      randomizer=random.choice(optionsindex)
>      while randomizer==option1:
>          if input() in option1:
>              print('he tumbles over you')
>              break
>          else:
>              print('he stabs you')
>              break
>      while randomizer==option2:
>          if input() in option2:
>              print('you trip him up')
>              break
>          else:
>              print('he stabs you')
>              break
> partdeux()
>

Yes, you are making this much more complicated than necessary.  It seems that what you are 
trying to do is input the option, then randomly print a success or failure message for that 
option.  I suspect you didn't plan it, but it also prints the "stab" message for invalid entries.

Like any program, it can be approached in many different ways.  Here is one possibility.
(Just the function def, add the import and function call as well.  Also I am not adding any 
comments.  See if you can follow the logic here yourself.)

----------
def partdeux():
     print('A man lunges at you with a knife!')
     option = input('Do you DUCK or PARRY?  ').lower()
     success = random.randint(0, 1)
     if success:
         if option == 'duck':
             print('He tumbles over you')
             return
         if option == 'parry':
             print('You trip him up')
             return
     print('He stabs you')
------------

BTW, ignore the response from Carlos.  I can see from the print() functions in your original 
that you're using Python 3.  His answer is only valid for Python 2.

      -=- Larry -=-




More information about the Python-list mailing list