Python Forum
havent programmed in years - confused by why RETURN is not returning
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
havent programmed in years - confused by why RETURN is not returning
#1
haven't programmed in years
thought i would try python, wrote a script that was failing
shorten the code to just the section that I think is giving the problem

the problem being that the RETURN is not returning how/what I think it should
have researched but can't see my error

think that the RETURN should be returning values for heads_count, tails_count, x, z but it's not

import random

x = 0
x = int(x)
y = 0
y = int(y)
z = ""
z = str(z)
heads_count = 0
tails_count = 0


heads_count = int(heads_count)
tails_count = int(tails_count)


def count(heads_count, tails_count, x):

    heads_count = 0
    tails_count = 0
    
    print("in the count function")
    print(f" x is {x}")

    while x < 10:
        options = ["heads","tails"]
        result = random.choice(options)
        if result == "heads":
            heads_count += 1
        else:
            tails_count += 1
        x += 1

        print(f"heads: {heads_count} tails: {tails_count} flips {x}")
    print(f"heads: {type(heads_count)}")
    print(f" flips is {x} before leaving count function")
    z = input("return something?!?! : ")
    return (heads_count, tails_count, x, z)

    
	
def main():

    print(f"heads: {heads_count} tails {tails_count} flips {x}")

    print(f" x is {x}")
    print("in the main function")
    count(heads_count, tails_count, x)

    print("back in the main function? WHY is THIS not returning as I THINK?!!??")
    print(f"heads: {heads_count} tails {tails_count} flips {x}")
    print(f"heads: {type(heads_count)}")
    print(f"z: {type(z)}")
    print(f"your input was: {z}")


main()
thanks for any help
Reply
#2
A simple return function example

def simple_return(var):
    count = f'Returning Count -> {", ".join([str(i) for i in range(var)])}'
    return count

print(simple_return(10))
Output:
Output:
Returning Count -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
the problem is that you try manipulate global variables inside the function count, without declaring them as such, using global keyword. So there is e.g. heads_count in the global scope, as well [different] heads_count inside the function, i.e. local scope.. Anyway, working with global variables should be avoided, unless you have really good reason to do so. And that is what you are doing - returning values from function. What you need to do, is to assign the return values (i.e. unpack the tuple you return).

Before that, a couple of other issues, you need to take care of.
1.
x = 0
x = int(x)
x is 0, no need to cast to int
Same for rest

2. It doesn't make sense to initialize the variables, then pass them as arguments. Your function does not use the arguments you pass (except x, but see 3. below). Remove the parameters from your function

3. No need to use while, better use for loop if you know exact number of times you want to iterate - 10

import random
 
def count(n=10): # how many times to toss, n=10 by default
 
    heads_count = 0
    tails_count = 0
    options = ["heads", "tails"]
    for i in range(n):
        result = random.choice(options)
        if result == "heads":
            heads_count += 1
        else:
            tails_count += 1
    return (heads_count, tails_count)
 
     
     
def main():
    heads_count, tails_count = count()
    print(f"heads: {heads_count} tails {tails_count}")

main()
Note, a lot of things can be done differently, but you get the idea
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
The return statement returns values from a function.
def add(a, b):
    result = a + b
    return result

total = add(2, 3)
print(total)
Output:
5
This part:
def add(a, b):
creates a function named "add" and says it expects 2 arguments.
This part:
    result = a + b
    return result
is the body of the function. The body defines what the function does. Here the body adds the arguments a and b and returns the result.

This part:
total = add(2, 3)
calls the function and assigns the return value to a variable named "total".

All functions return a value, even if they don't contain a return statement. If a function doesn't have a return statement, the return value is None.

What you tried to do is called "pass by reference". In pass by reference, a function is passed arguments meant to hold the return value for the function. Python does not support pass by reference. In Python you pass arguments used by the body of the function, and use "return" to return values from the function. To use the function return values, the caller must assign the return value(s) to a variable.
Reply
#5
thanks for the reply
and i understand what you are showing

you are sending 10 to the function and printing

my question is - arnt i sending the heads_count, tails_count, x to count function and returning those variables, just not the value that I am expecting - at the very least I would think that the count variable should be 10, but it's not when printed in the main function

------------

ok so before posting i did some more script manipulations and searching to find that python runs top to bottom (which I didnt realize)

i thought the
count(heads_count, tails_count, x)


was calling (old school programming GOTO) the count function and then returning to the main function with those variables and continuing

guess I have been out of programming far longer then I thought and need to do some more reading
thanks for the help
Reply
#6
(Mar-26-2023, 03:45 AM)stmoose Wrote: you are sending 10 to the function and printing
n is parameter of the function, and instead of default value, like I did, you can do e.g. heads_count, tails_count = count(100) in which case it will pass 100 as argument and it will toss the coin 100 times. The take away is that you should assign the value returned by the function.

Here is some more reading on scope in python and how the names are resolved:
https://realpython.com/python-scope-legb-rule/
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  String int confused janeik 7 1,085 Aug-02-2023, 01:26 AM
Last Post: deanhystad
  I am confused with the key and value thing james1019 3 975 Feb-22-2023, 10:43 PM
Last Post: deanhystad
  Pandas confused DPaul 6 2,581 Sep-19-2021, 06:45 AM
Last Post: DPaul
  is and '==' i'm confused hshivaraj 6 2,728 Sep-15-2021, 09:45 AM
Last Post: snippsat
  Confused with 'flags' tester_V 10 4,941 Apr-12-2021, 03:03 AM
Last Post: tester_V
  Simple Tic Tac Toe but I'm confused Izith 1 2,205 Sep-26-2020, 04:42 PM
Last Post: Larz60+
  I am really confused with this error. Runar 3 3,039 Sep-14-2020, 09:27 AM
Last Post: buran
  Confused on how to go about writing this or doing this... pythonforumuser 3 2,502 Feb-10-2020, 09:15 AM
Last Post: snippsat
  'Age' categorical (years -months -days ) to numeric Smiling29 4 2,948 Oct-17-2019, 05:26 PM
Last Post: Smiling29
  Create a monthly mean column in multiple years fyec 1 4,029 Jun-21-2018, 03:57 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020