Python, Function, need help

0 Cardinal Coog · February 17, 2015
I'm really new to Python (usually program in C++). Anyway, I wrote a program that displays the integers in the range of 13 to 100 and an acceptable "dating age" next to each. It's based off of Bucky's program for return values. The code I wrote is posted below, but I don't understand why I have to call femaleAge = n/2 + 7 in both the function allowedAge(n) and again in the for loop. Isn't the whole point of the function is so that I don't have to call it again in the loop?

Here's the code so far:

def allowedAge(n):
femaleAge = n/2 + 7
return femaleAge

for n in range(13, 101):
femaleAge = n/2 + 7
print(n, ' ----- ', femaleAge)



Post a Reply


Oldest  Newest  Rating
0 Cardinal Coog · February 17, 2015
I wrote the following in C++ which produces the same output as the one in Python, but I know this function is working right.

#include <iostream>
using namespace std;

int checkAge(int boysAge);

int main(){

    int n;
    int boysAge;
    int girlsAge;

    for(n = 13; n <= 100; n++){


int checkAge(int boysAge){

    int girlsAge = boysAge / 2 + 7;
    cout << boysAge << " ----- " << girlsAge << endl;

0 Cardinal Coog · February 17, 2015
@Red: Thanks. That makes sense now.:)
+1 Jacky L · February 19, 2015
I believe the reason why yours did not work is because whenever you define a function ( def allowedage(n) ), your variables inside the define cannot be called from the outside of define. You can Google "Global variables" and "Local variables" to understand this more.
  • 1



This section is all about snakes! Just kidding.

Bucky Roberts Administrator