How to create and access dynamic variable names a template function? - python

I wound up having three extremely similar functions in my code, which were to take separate user inputs for their birth year, month, and day. I want to use the best practices I can even though the code is extremely basic, which is why it's a bit overkill. So right now I have a function that acts as a template and takes three args dateType, typeStr, and typeFormat. I'm trying to use these args to name variables in the three functions that I'll create using the template so that I can later print out the birth date of the person. I'm aware of scope, but I've tried making things global etc etc and it hasn't worked. I don't know if I'm even creating variables that are persistent or if it all gets unassigned once the function is done, and if I am creating variables I can't figure out what they're called as I've tried every possibility.
def makeTemplateInput(dateType, typeStr, typeFormat):
def templateInput(dateType, typeStr, typeFormat):
print('You\'re using the template function. Please input your birth {} in the format {}.\n$ '.format(dateType, typeFormat), end='')
while True:
try:
dateType = input()
typeStr = dateType
dateType = int(dateType)
if dateType > 0:
if len(typeStr) != len(typeFormat) and isinstance(dateType, int):
print('Your input doesn\'t have {} digits, please use the format {}.\n$ '.format(str(len(typeFormat)), typeFormat), end='')
print('strlen: ' + str(len(typeStr)))
continue
break
else:
print('Your input is not a positive integer!\n$ ', end='')
continue
except ValueError:
print('Your input is not a valid number, please use the format {} where {} is an integer.\n$ '.format(typeFormat, str(typeFormat[:1])), end='')
print(dateType)
def yearInput1():
makeTemplateInput('year', 'yearStr', 'YYYY')
yearInput1()
print('Your birthdate is: {}/{}/{}'.format(yearInput1.year, monthInput.monthStr, dayInput.dayStr))
I'm sure it's a mess that misunderstands fundamental things about Python, but I really don't understand what's gone wrong.

A few online classes or some good books can help with some of this confusion. I've created some sample code to hopefully answer your question. Thank you.
class Calendar:
def __init__(self, day, month, year): #This can be initialised with the day/month/year
self.day = day
self.month = month
self.year = year
def displayDate(self): #This will display the dates from the object created/set
print('day:{} month:{} year:{}'.format(self.day, self.month, self.year))
def setNewDate(self, otherDay, otherMonth, otherYear): #this sets the class attributes to something else
print('This was the old values day:{} month:{} year:{}'.format(self.day, self.month, self.year))
self.day = otherDay
self.month = otherMonth
self.year = otherYear
print('The new values are day:{} month:{} year:{}'.format(self.day, self.month, self.year))
cal = Calendar(6,11,2020)
cal.displayDate()
cal.setNewDate(3,4,2099)

Related

Input from user to print out a certain instance variable in python

I have created a class with programs:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
Channel 1, start:16.00 end:17.45 viewers: 100 name: Matinee:The kiss on the cross
Channel 1, start:17.45 end:17.50 viewers: 45 name: The stock market today
Channel 2, start:16.45 end:17.50 viewers: 30 name: News
Channel 4, start:17.25 end:17.50 viewers: 10 name: Home building
Channel 5, start:15.45 end:16.50 viewers: 28 name: Reality
I also have created a nested list with the programs:
[[1,16:00, 17,45, 100, 'Matinee: The kiss on the cross'],[1,17:45, 17,50, 45,'The stock market today'],[2,16:45, 17,50, 30,'News'], [4,17:25, 17,50, 10,'Home building'],[5,15:45, 16,50, 28,'Reality']
Now we want the user to be able to write the name of a program:
News
The result should be:
News 19.45-17.50 has 30 viewers
I thought about how you could incorporate a method to avoid the program from crashing if the input is invalid/ not an instance variable
I have tried this:
Check_input():
print('Enter the name of the desired program:')
while True: #Continue asking for valid input.
try:
name = input('>')
if name == #is an instance?
return name
else:
print('Enter a program that is included in the schedule:') #input out of range
except ValueError:
print('Write a word!') #Word or letter as input
print('Try again')
I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)
I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory"
Do you have any suggestions how to combat the problem?
All help is much appreciated!
I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)
Well if all your programs have a unique name then the easiest approach would probably be to store them in a dictionary instead of a nested list like:
programs = {
"News": Program("2", "16:45", "17:50", "News", "30", "60"),
"Reality": <Initialize Program class object for this program>,
...
}
Then you could just use the get dictionary method (it allows you to return a specific value if the key does not exist) to see if the asked program exists:
name = input('>')
program = programs.get(name, None)
if program:
print(program)
else:
# raise an exception or handle however you prefer
And if your programs don't have a unique name then you will have to iterate over the list. In which case I would probably return a list of all existing objects that have that name. A for loop would work just fine, but I would switch the nested list with a list of Program objects since you already have the class.
I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory" Do you have any suggestions how to combat the problem.
I would say that the most elegant solution is to override the __str__ method of your Program class so that you can just call print(program) and write out the right output. For example:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
def __str__(self):
return self.name + " " + self.start + "-" + self.end + " has " + self.viewers + " viewers"
should print out
News 19.45-17.50 has 30 viewers
when you call it like:
program = programs.get(name, None)
if program:
print(program)

Function to transfer values in dictionary Python

I am new to Python and trying to make a function for an assignment that will transfer money from a checking to a savings account,. We were given this initial code:
class portfolio:
def __init__(self):
self.checking = {}
self.saving = {}
self.credit = {}
self.stock = {}
And then the start of this code to make the function to transfer the money:
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
I've tried numerous code, but none will pass the test cases. Can someone explain to me why this won't work?
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
try:
self.checking[account_id_checking] -= amount
self.saving[account_id_savings] += amount
except:
return None
If the account id doesn't exist or if there are no funds in the checking account, the function is to do nothing.
Any suggestions would be greatly appreciated! I've worked on this all day and haven't been able to solve it.
This is the test case it must pass:
myportfolio.invest_in_savings_account('discover_saving_3785', 1000, 'discover_7732')
if (myportfolio.saving == {'chase_saving_4444': 0, 'discover_saving_3785':1000}) and (myportfolio.checking == {'chase_6688': 100, 'discover_7732':5500}):
print('Pass')
else:
print('Fail')
There are a few things going on here, most simple first, always start a class with a capital letter, it isn't necessary but it's good practice:
def class Portfolio:
After reading your comments it appears you need this to work without money in the accounts. You can write the code but you won't be able to test it, so really you need to make functions to create accounts and to add / remove money. If you haven't created any accounts your dictionaries will always come back empty. If you don't put money into them then the function will never do anything, I'm confused as to how you would go about moving something that doesn't exist.
Try something like this:
def create_checking_account(self,account_id):
self.checking[account_id] = None
def add_funds_checking(self,account_id,amount):
self.checking[account_id] += amount
def invest_in_savings(self, account_id_savings, amount, account_id_checking):
if self.checking[account_id_checking] >= amount:
self.checking[account_id_checking] -= amount
self.savings[account_id_savings] += amount
else:
print('error')

Writing dictionary output to file - Python

I have a small program to track monthly balances. This worked fine as is, and then I added in the section to write to a .txt file at the bottom. I did some searching but can't figure out a way to make it work. Basically I want to keep appending to this test.txt file. Every time I enter a new month/account/balance I want that appended to the file.
The alternative is to append to the test.txt file after 'exit', so it doesn't do it every loop. Not sure which way is more efficient
***EDIT****
This updated code now creates test.txt file but the file is blank after each loop
Secondary question - I have heard this would be better off using a Class for this, but I haven't any idea how that would look. If someone wants to demonstrate that would be awesome. This isn't homework, this is strictly learning on my own time.
Any ideas? Thanks
# create program to track monthly account balances
savings = []
def add_accounts(date, account, balance):
savings.append({'date': date, 'account': account, 'balance':
balance})
def print_accounts():
print(savings)
while True:
date = input('Enter the date, type exit to exit program: ')
if date == 'exit':
break
account = input('Enter the account: ')
balance = int(input('Enter the balance: '))
add_accounts(date, account, balance)
print_accounts()
with open('test.txt', 'a') as f:
for row in savings():
print (row)
f.write(str(savings[-1]))
file.close()
The problem with your original code is that print_accounts() doesn't return anything, yet you attempt to perform operations on its (nonexistent) return value.
Here is a version of your program made using classes, and with a few corrections:
class Account:
def __init__(self, id, date, balance):
self.id = id
self.date = date
self.balance = balance
def getString(self):
return self.id + "," + self.date + "," + str(self.balance)
savings = []
def add_account(date, account, balance):
savings.append(Account(date, account, balance))
def print_accounts():
for account in savings:
print(account.getString())
while True:
date = input("Enter the date, type exit to exit program: ")
if date.lower() == "exit":
break
else:
account = input('Enter the account: ')
balance = int(input('Enter the balance: '))
add_account(date, account, balance)
print_accounts()
with open("test.txt", "w") as file:
for account in savings:
file.write(account.getString() + "\n")
Some explanation regarding the class: The Account class has 3 fields: id, date, and balance. These fields are defined in the constructor (__init__()). The class also has a method, getString(), which I use to get the string representation of each instance.
Over all, the following changes have been made:
Create an Account class, which serves as the template for the object which holds the data of each account.
Use a loop to print accounts and write them to the file.
Turn date into lowercase before checking to see if it is equal to "exit". This is a minor change but a good habit to have.
Removed f.close(), as it is unnecessary when using a with open() statement.
Created a custom string representation of each instance of Account, consistent with what you would otherwise get.
That last one is achieved via defining the getString method in the account class. There is nothing special about it, it is merely what we use to get the string representation.
A better but quite more advanced way to achieve that is by overriding the __str__ and __repr__ methods of the base object. These are essentially hidden functions that every class has, but which python defines for us. The purpose of these two specific ones is to give string representations of objects. The default code for them doesn't produce anything meaningful:
<__main__.Account object at 0x0000000003D79A58>
However, by overriding them, we can use str() on instances of Account, and we will get a string representation in the exact format we want. The modified class will look like so:
class Account:
def __init__(self, id, date, balance):
self.id = id
self.date = date
self.balance = balance
def __repr__(self):
return self.id + "," + self.date + "," + str(self.balance)
def __str__(self):
return self.__repr__()
This also eliminates the need to loop through savings when writing to the file:
with open("test.txt", "w") as file:
for account in savings:
file.write(account.getString() + "\n")
Turns into:
with open("test.txt", "w") as file:
file.write(str(savings))
This wouldn't have worked before, as str() would have given us the gibberish data you saw earlier. However, now that we have overridden the methods, it works just fine.
Try this code (use -1 to exit):
savings = []
def add_accounts(date, account, balance):
savings.append({'date': date, 'account': account, 'balance':
balance})
def print_accounts():
print(savings)
while True:
date = input('Enter the date, type exit to exit program: ')
if date == -1:
break
account = input('Enter the account: ')
balance = int(input('Enter the balance: '))
add_accounts(date, account, balance)
print_accounts()
with open('test.txt', 'a') as f:
for row in savings:
print (row)
f.write(str(savings[-1]))
f.close()

If = 1 then answer is day shift else answer is night shift

with this program the outcome should display employee name, number , shift (day or night based on the number imputed) and hourly pay rate.
I've tried a few different ways and can "almost" get the desired results. Any assistance would be appreciated.
# This Employee class holds general data about employess and will
# end up as the superclass for this example.
class Employee:
#__init__ method initialzes the attributes.
def __init__(self, emp_name, emp_number):
self.__emp_name = emp_name
self.__emp_number = emp_number
# The set_emp_name method gets the employee name.
def set_emp_name(self, emp_name):
self.__emp_name = emp_name
# The set_emp_name method gets the employee number.
def set_emp_number(self, emp_number):
self.__emp_number = emp_number
# The get_emp_name method returns the employee name.
def get_emp_name(self):
return self.__emp_name
# The get_emp_number method returns the employee number.
def get_emp_number(self):
return self.__emp_number
# The ProductionWorker class holds the general data from superclass Employee
# as well as Employee shift time and pay rate making it a subclass
# of Employee.
class ProductionWorker(Employee):
# __init__ method initializes the attributes.
def __init__(self, emp_name, emp_number, shift, payrate):
# Call the superclass
Employee.__init__(self, emp_name, emp_number)
self.__shift = shift
self.__payrate = payrate
# The set_shift method get employee shift.
def set_shift(self, shift):
self.__shift = shift
# The set_payrate method gets employee hourly pay rate.
def set_payrate(self, payrate):
self.__payrate = payrate
# The get_shift method returns the employee shift.
def get_shift(self):
if self.shift == 1:
self.shift = 'Day shift'
elif self.shift == 2:
self.shift = 'Night shift'
return self.__shift
# The get_payrate method returns the employee hourly pay rate.
def get_payrate(self):
return self.__payrate
# This program will test the Employee superclass and ProductionWorker subclass
# by returning and displaying the gathered information.
import sys
# Get the Employee info.
emp_name = input('Employee Name: ')
emp_number = input('Employee Number: ')
shift = float(input ('Shift Number 1 or 2: '))
payrate = input('Hourly Pay Rate: $')
# Determine True or False for mailing list.
#if shift == 1:
#print('Day')
#else:
#print ('Night')
# Create an instance of the ProductionWorker class.
my_productionworker = ProductionWorker(emp_name, emp_number, shift, payrate)
# Display the object's data.
print('Employee Information')
print('---------------------')
print('Employee Name:', my_productionworker.get_emp_name())
print('Employee Number:', my_productionworker.get_emp_number())
print('Shift:', my_productionworker.get_shift())
print('Hourly Pay Rate:$', my_productionworker.get_payrate())
In your method
def get_shift(self):
if self.shift == 1:
self.shift = 'Day shift'
elif self.shift == 2:
self.shift = 'Night shift'
return self.__shift
you're mixing up .shift and .__shift In the if and elif, it should be .__shift and in the assignments it should be just shift (a local variable, not a member variable) and then you should return that local variable (or maybe just return directly from inside the if and elif, depending on how you feel about multiple exit points).
Also, it's a good practice to include a final else in your if / elif, possibly something like this:
else:
shift = 'Cannot convert {} to a valid shift.'.format(self.__shift)
or
else:
raise Exception('Invalid shift value {}.'.format(self.__shift)
which will alert you to the fact that you fell through all the valid options, and give you a hint as to what value is causing the problem.
BTW, you should not be using double underscore variables in this way and, in general, should not try to write Java code in Python. I'd get rid of the getters and setters and just read and write the member values directly.

Can't get python to read/display my variable

I have been working on this one program for hours now and I am still having no luck. I am trying to create a "search engine" where you can look products with a SKU number.
class SKU:
def __init__(self, name, product):
self.name = name
self.product = product
def displaySKU(self):
print "Sku Number : ", self.name, ", Product: ", self.product
sku90100 = SKU("90100", "10310, 00310")
sku90101 = SKU("90101", "10024, 00024")
sku90102 = SKU("90102", "10023")
sku90103 = SKU("90103", "10025")
sku90104 = SKU("90104", "10410")
search = input("Please type SKU Number")
if search in range(90100, 90106):
"sku",search.displaySKU
My problem is that I can't seem to get display the SKU information; I have tried removing, changing, and adding characters to the variables without success. I may have missed something thou, but all I now is that nothing that I try works. Please help me figure this out, and thank you for taking the time to read my question.
Instead of storing each product as its own variable, use a dict:
skus = {}
skus[90100] = SKU("90100", "10310, 00310")
skus[90101] = SKU("90101", "10024, 00024")
skus[90102] = SKU("90102", "10023")
skus[90103] = SKU("90103", "10025")
skus[90104] = SKU("90104", "10410")
Then you can check membership using in, and call the .displaySKU() method to print:
if search in skus:
skus[search].displaySKU()
Lastly, for Python 2, it's preferred to use raw_input instead of input. raw_input gives you a string though, so you want to convert that to an int to match your skus keys:
search = int(raw_input("Please type SKU Number"))

Categories