Jump to content

Python- Function problem. Code for a basic console game.

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Wolfi

Wolfi

    Newbie

  • Members
  • Pip
  • 3 posts
Hello everyone,

I have a simple question about functions in python.
I would want to change a pre-declared variable inside a function, return it and view/change the information afterwards.

------------------------
HERE IS A SIMPLE EXAMPLE
------------------------

variable = 3

def function(variable):

	variable += 3

	return variable

print variable 

-----------------------
WHAT I WANNA USE IT FOR
-----------------------

chosen_weapon = ''


def getWeapon(chosen_weapon):

	chosen_weapon = raw_input ('Choose you weapon < Gun, knife>')

	if chosen_weapon.startswith('g'):

		chosen_weapon = 'gun'

	elif chose_weapon.startswith('k'):

		chosen_weapon = 'knife'

	return chosen_weapon

	

if chosen_weapon == 'gun':

	print 'You have chosen a gun. Ammo = 6'

elif chosen_weapon == 'knife':

	print 'You have chosen a knife as your weapon.'

_________________________

So this is an example: what I want to use it for.
Does anybody have an idea? I want to take that information from the function. Actually the goal of the function is to give chosen_weapon a piece of information from which I can benefit later.

ARE THERE ANY OTHER WAYS OF DOING WHAT I NEED?

Thankyou in advance,
Wolfi

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 890 posts
Why not something like this:

def getWeapon():

    weapon = raw_input()

    if weapon == 'g':

        return "gun"

    elif weapon == 'k':

        return "knife"

    else:

        return "unarmed"


weapon = getWeapon()

What you accually want is global variable. Just type global weapon in function, before raw_input()
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
Wolfi

Wolfi

    Newbie

  • Members
  • Pip
  • 3 posts
Thank you very much Flying Dutchman, but I have one more question.
So when my code is:

def getWeapon():

	print 'Choose you weapon'

	weapon = raw_input()

	if weapon == 'g':

	    return "gun"

	elif weapon == 'k':

	    return "knife"

	else:

	    return "unarmed"


weapon = getWeapon()


	

In the declare statement "weapon = getWeapon()" the "Choose your weapon" appears. Do you know how to declare it without that happening?

Thank you, your code works!

Wolfi

#4
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 890 posts
You mean that print before raw_input() ? Simply remove it, or place text in raw_input(), inside parenthesis.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#5
Wolfi

Wolfi

    Newbie

  • Members
  • Pip
  • 3 posts
Yes, you're right. I get it now, thanks.

Wolfi