I have the file addr with the contents
Name,Phone,Email,Year_of_Birth
Elizi Moe,5208534566,emoe@ncsu.edu,1978
Ma Ta,4345667345,mta@yahoo.com,1988
Diana Cheng,5203456789,dcheng@asu.edu,1970
I am looking to extract the data and display it in so that it looks like
Please enter in the current year: 2018
Name Phone Email Age
Elizi Moe 5208534566 emoe@ncsu.edu 40
Ma Ta 4345667345 mta@yahoo.com 40
Diana Cheng 5203456789 dcheng@asu.edu 40
But each age should be calculated properly based on their year of birth. I have hardcoded in the year 1978 as a test case, but I am having trouble getting my age to calculate dynamically.
Here is my code, MyClasses.py:
class Subscriber:
inp = input("Please enter in the current year: ")
def __init__(self, name="name", phone=5206675857, email="your@email.com", year=0):
self.name= name
self.phone= phone
self.email= email
self.year= year
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getEmail(self):
return self.email
def getAge(self):
age = Subscriber().inp-1978
return age
def setYear(self, year):
self.year = year
execute
from MyClasses import Subscriber
import csv, sys
def main():
filename = sys.argv[1:]
filein = open("addr.csv", 'r')
data = csv.DictReader(filein)
user = Subscriber()
recordList = []
for record in data:
recordList.append(Subscriber(record["Name"],record["Phone"],record["Email"],record["Year_of_Birth"]))
print("%-15s%-15s%-15s%-15s" %("Name","Phone","Email","Age"))
for i in range(len(recordList)):
print("%-15s%-15s%-15s%-15s" %(recordList[i].getName(),recordList[i].getPhone(),recordList[i].getEmail(),recordList[i].getAge()))
main()
I have attempted to change the line getAge() to:
def getAge(self):
age = Subscriber().inp-self.year
return age
which means I have to set the year value to an integer. But I am not sure where to put it. I have tried this.
recordList.append(Subscriber(record["Name"],record["Phone"],record["Email"],record["Year_of_Birth"]))
user.setYear(int(record["Year_of_Birth"]))
But I keep getting error
TypeError: unsupported operand type(s) for -: 'int' and 'str'
The error is quite self explanatory. You are performing -
operator on string and int.
In your code, age = Subscriber().inp-self.year
after using user.setYear(int(record["Year_of_Birth"]))
the 2nd operand is int but you forgot about first one, i.e. Subscriber().inp
.
A quick solution would be to do take input as inp = int(input("Please enter in the current year: "))
or use age = int(Subscriber().inp)-int(self.year)
P.S. I tried age = int(Subscriber().inp)-int(self.year)
approach with your code and it is working fine.