-2

I have two python files:

  1. Term
  2. Today

In all the py files the user is to enter some data For instance in the term.py file the user is to enter the age and the duration. How can I make today.py file have access to the data variables(age and duration) which have been input by the user in the in the term.py file

In the term.py file I have this code

 def Term_advance():
     print('advance')
     n = int(input('enter duration (n) :'))
     age = int(input("enter life's age :"))
     Sum_assuared = int(input('enter sum assuared :'))
     basis = input('what is the calculation basis::\n'
               '1.\t AM 92\n'
               '2.\t ELT 15 MALES\n'
               '3.\t ELT 12 FELAMES\n'
              '4.\t PEN\n'
              '5.\t A1967-70\n')
     If basis==1:
          today.tables_advance_perpetuity()

Then in the today.py file I have this code which reads the values from an excel document, the values however are to be input by the user in the Term.py file

 import xlrd
 loc = "C:PycharmProjects/Life annuities/tables.xlsx"  
 wb = xlrd.open_workbook(loc)


 def tables_advance_perpetuity():
     sheet = wb.sheet_by_index(0)
     sheet.cell_value(0, 0)
     num = int(input('enter the age of the life:'))
     for i in range(sheet.nrows):
         x = sheet.cell_value(i, 0)
         if x == num:
             dx = sheet.cell_value(num - 1, 2)
             nx = sheet.cell_value(num - 1, 6)
             print(dx)
             print(nx)
             ann = nx / dx
             print(f'Annuity value is {ann}')

So like for this case how can the today file read for instance the age of the life entered by the user in the term.py file( instead of asking the user to enter the values again in the today.py file)

Victor
  • 25
  • 5

2 Answers2

2

One solution to pass variables from file to file (although if you use functions properly this doesn't happen often) is to import them as such:

term.py

age = 18
duration = 2.56

today.py

import term  Assuming both scripts are in the same location or installed as modules

age = term.age
duration = term.duration

Again this will work but is not best practice and you should be able to pass these variables using functions easily.

rob_m
  • 321
  • 1
  • 9
0

When you are using classes, you can access variables declared with the "self" attribute from other class:

class Term:
    def __init__(self):
        self.my_public_variable = 0

Access from other class:

import Term
class Today:
    def __init__(self):
        self.my_other_public_variable = 0
        self.term = Term()
        self.my_cool_method(8)

    def my_cool_method(self, new_val):
        self.term.my_public_variable = new_val

Written by hand, so no guarantess that it spelling free ;)

Hagi
  • 140
  • 1
  • 8