functions variables not defined

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

functions variables not defined

Postby DevXux8 » Tue Apr 15, 2014 10:42 am

Hi, I have this problem with my functions. When I run dice function inside other function it says that dice1 is not defined, even its defined in dice() function. How can I have this problem go away, - what is wrong here? Also same is with hp1 and hp2 variables in hp() function. They keep errorin as not defined variables. What should i do that when i run the spine() function also hp() function and dice() functions variables are defined in spine() function? I really apreciate insight. Thanks. :) ps. I am total newbie to programming, so lets try to keep expalanations simple as possible...

Code: Select all
import random
   
def hp():
        hp1 = 42
        hp2 = 15

def dice():
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)

def spine():
    dice()
    hp()
    if dice1 > dice2:
        print("Wonder")
    else:
        print("ELSE")


spine()

DevXux8
 
Posts: 15
Joined: Sat Feb 01, 2014 9:53 am

Re: functions variables not defined

Postby stranac » Tue Apr 15, 2014 10:59 am

You should return values from your functions.
Something like:
Code: Select all
>>> import random
>>> def dice():
...     dice1 = random.randint(1, 6)
...     dice2 = random.randint(1, 6)
...     return dice1, dice2
...
>>> dice1, dice2 = dice()
>>> dice1
1
>>> dice2
6
Friendship is magic!

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

Re: functions variables not defined

Postby DevXux8 » Tue Apr 15, 2014 11:30 am

It still gives me same error. I trie return but still dice1 will remain undefined or nothing happends at concole...WHY WWHY WHY? :/
What i do wrong?

Code: Select all
import random
   
def hp():
        hp1 = 42
        hp2 = 15

def dice():
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
   
def spine():
        return dice()
        return hp()
        if hp1 > hp2:
                print("outstanding!")
        else:
                print("NULL")
       
spine()
DevXux8
 
Posts: 15
Joined: Sat Feb 01, 2014 9:53 am

Re: functions variables not defined

Postby metulburr » Tue Apr 15, 2014 11:37 am

I am not sure why you didnt take stranacs advice. You essentially just had to mimic his reponse in your own code.
Code: Select all
import random
   
def hp():
        hp1 = 42
        hp2 = 15

def dice():
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    return dice1, dice2

def spine():
    dice1, dice2 = dice()
    hp()
    if dice1 > dice2:
        print("Wonder")
    else:
        print("ELSE")


spine()


by the way, in your latest code snippet...
Code: Select all
def spine():
        return dice()
        return hp()

the function dice() does not return anything, thus by default returning None. However the funciton spine() returns the result of dice(), AKA None, on the first line, therefore nullifying all code after it. It wont run. So therefore, spine() returns None is youir latest code results. Your code would fail if it reached the comparison:
Code: Select all
    if dice1 > dice2:
as they are undefined
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1561
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: functions variables not defined

Postby sboden » Tue Apr 15, 2014 11:38 am

"Scoping"... whatever is in the function, stays in the function... a variable you "define" within a function, disappears at the end of that function.

You could use "global variables" in your case (simple example program), or return values, or rewrite your stuff. I would also suggest an introductory book to python.

Regards,
Sven
sboden
 
Posts: 6
Joined: Mon Apr 14, 2014 8:22 pm

Re: functions variables not defined

Postby DevXux8 » Tue Apr 15, 2014 11:40 am

I did tried, but i think my fustration level was so high that I couldnt still make it work. thanks. Its working now perfectly. :)
DevXux8
 
Posts: 15
Joined: Sat Feb 01, 2014 9:53 am

Re: functions variables not defined

Postby DevXux8 » Tue Apr 15, 2014 11:43 am

Yes, I am reading now python for absolute beginers 3th edition, but i get fustrated if I dont get to know what I need so that i can make my future program to work. Reading whole book at one stand is too hard for me. Even tho i keep reading it part by part everyday now. Thanks.
DevXux8
 
Posts: 15
Joined: Sat Feb 01, 2014 9:53 am

Re: functions variables not defined

Postby DevXux8 » Tue Apr 15, 2014 12:50 pm

So what I am trying to acchive here is a hitpoint counter that takes away sum from the hitpoints and saves new value for the variable.
pseudocode:
Player hitpoints are 42
monsters hitpoints are 15
trowing random dices
IF opponent dice is greater than players dice number
then two points are gone from players hitpoint
new player hitpoints are saved
new players hitpoints are printed.
else if players dice is greater
then two points are gone from monsters hitpoints
new monster hitpoints are saved
new player hitpoints are printed.


What I have tried to do is functions inside funtion, but I have no idea anymore how to crack this problem. This is what I got here, its farout from the pseudocode, i know. I dont know how to replace hp and save the new value for hp variable. I am not even sure is this good way to aproach this problem.

Code: Select all
import random
   
def hp():
    hp1 = 42
    hp2 = 15
    return hp1, hp2


def dice():
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    return dice1, dice2

def spine():
    hp1, hp2 = hp()
    dice1, dice2 = dice()
    if dice1 > dice2:
        print("Player rolls", + dice1)
        print("Monster rolls", + dice2)
        print("You hit the monter by 2 points!")
        print(hp2 - 2)
       
       
    if dice1 < dice2:
        print("You got hit by 2 points.")
        print(hp1 - 2)
       
       
       

spine()



So what should I do? How do i save the new hitpoint value for the hp variables? Thanks.
DevXux8
 
Posts: 15
Joined: Sat Feb 01, 2014 9:53 am

Re: functions variables not defined

Postby sboden » Tue Apr 15, 2014 1:08 pm

It depends... your example looks like a good candidate for some "object oriented" stuff. But that's a few steps farther away than you are right now probably.

Shoddy solutions for your current small example... shoddy in the sense that they're not nice, but it works.... supply a hashtable or list as argument to the function and store your stuff there... whatever you change in them will be visible after the function call... but then again... pretty dirty coding ;)
sboden
 
Posts: 6
Joined: Mon Apr 14, 2014 8:22 pm

Re: functions variables not defined

Postby DevXux8 » Tue Apr 15, 2014 1:11 pm

I like it dirty :D. but seriously, this is my first math base program so not much can be expected. What i have done before is just printing with conditions. :ugeek:
DevXux8
 
Posts: 15
Joined: Sat Feb 01, 2014 9:53 am

Re: functions variables not defined

Postby metulburr » Tue Apr 15, 2014 4:56 pm

I am not sure how far down the line that book starts using classes, but you going to have to learn them at some point. When you start throwing variables back and forth between functions, think classes.

here is your code in a class hierarchy, or just some food for thought
Code: Select all
import random

class Character:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp
    def take_damage_by(self, amt):
        self.hp -= amt
        print('{} takes {} damage'.format(self.name, amt))
       
class Player(Character):
    def __init__(self, name, hp):
        Character.__init__(self, name, hp)
        self.attack = 2
   
class Enemy(Character):
    def __init__(self, name, hp):
        Character.__init__(self, name, hp)
        self.attack = 3

class Dice:
    def roll(self):
        return random.randint(1, 6), random.randint(1, 6)
       
enemy = Enemy('Enemy', 10)
player = Player('Player', 10)
dice = Dice()

print(enemy.hp)
print(player.hp)

d1,d2 = dice.roll()
if d1 > d2:
    enemy.take_damage_by(player.attack)
else:
    player.take_damage_by(enemy.attack)

print(enemy.hp)
print(player.hp)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1561
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: morissio and 2 guests