We're creating a small text-based bank application using python2, and we have to use the user's money for many of the functions. For instance: I create a variable a = 100 and I used the variable in the function with global a. But my teacher doesn't allow us to use the term global so i have to use something other than global.
For example:
a = 100
def withdraw():
global a
ko = input("Please enter the amount you want to withdraw:")
if ko > a:
print "You don't have " + " " + str(ko) + " " + "in your account."
print "Going back to main menu..."
else:
a = a - ko
print str(ko) + "Dollar" + "withdrawn from your account"
In this particular example, I'd simply pass a in, and return it back to the caller:
# Renamed a to balance
def withdraw(balance):
# Take input as before
return balance - ko
a = 100
a = withdraw(a)
Whenever possible, pass any relevant data in, and return any results back.
You can make the global variable (we are going to use account instead of a for this example) a local variable in your main and use it in every function that requires it. In this case something like this:
def withdraw(account):
# ... code here
account -= ko
print str(ko) + " Dollar withdrawn from your account"
return account
and you would call it like this
account = withdraw(account)
There are many ways you can avoid using global variables in your code for e.g. by using instance variables.
As your teacher suggests, you should avoid global variables because you may mistakenly declare another variable with the same name and then while reading the code, it will not be obvious which variable is getting accessed, making it hard to debug your code.
I suggest something similar to this:
class BankAccount():
def __init__(self, initial_balance):
self.balance = initial_balance
def withdraw(self, withdraw_amount=0):
if withdraw_amount > self.balance:
print "You don't have " + " " + str(withdraw_amount) + " " + "in your account."
print "Going back to main menu..."
else:
self.balance -= withdraw_amount
print str(withdraw_amount) + "Dollar" + "withdrawn from your account"
Following this you can create an instance of a bank account and withdraw form it in the following way:
bank_account = BankAccount(initial_balance=1000)
bank_account.withdraw(withdraw_amount=100)
Related
I cannot get Pytest to test anything involving this code. It always says no tests ran when I use the code below. I'm trying to just get it to test and from there I can tinker with the rest, I'm just a bit stuck on this and can't figure it out. The code runs well, exactly as intended it's just when I try to pytest with it that I'm reciving a problem.
import datetime
tday = datetime.date.today()
balance = 1000.0
amount = float
transaction_list = []
class Account(amount):
def get_balance(self):
print("\n This is your account balance: " + str(balance))
def deposit(self, amount):
global balance
amount = float(input("\n How much would you like to deposit? "))
if amount > 10000:
print("\n Do you want to swim in the vualt? ")
transaction_list.append("You deposited " + str(amount))
balance = balance + amount
print("\n You're balance is now " + str(balance))
def withdrawl(self, amount):
global balance
amount = float(input("\n How much do you wanna take out? "))
while amount > balance:
amount = float(input("\n You don't have enough funds. Enter a new value "))
transaction_list.append("\n You withdrew " + str(amount))
balance = balance - amount
print("\n You're balance is now " + str(balance))
class Transaction(amount):
def transaction(self):
print("\n")
print(" " + str(card_number) + " " + str(tday))
print("\n Recipt: HM21-1926\n")
print("\n Account: Chequing. Primary\n")
print("\n Here is your transaction history!\n")
for i in transaction_list:
print(i)
print("\n Account Balance: " + str(balance))
print("\n Limited time offer: get a personal loan starting at Prime + 1.99%*")
print("\n Offer valid until September 2, 2022.")
print("\n Conditions apply & approval required. Ask us for details.\n")
account = Account()
transaction = Transaction()
if __name__ == "__main__":
mike_lane = Account()
print(repr(mike_lane))
print(str(mike_lane))
The code below is the code I'm trying to use pytest on. I don't know if there is something wrong with what I'm trying to test or if there is something wrong with the main code. I'm just starting out with programming and this is a bit complicated for me still (However, I have to learn to do this for the class so I'm not able to come back to learn TDD later on)
import bank_program
def test_deposit():
account = Account(100)
assert balance.amount == 1100
def test_depos():
with pytest.raises(ValueError):
assert amount = Account("ABC")
def test_transactions():
account = Account(100)
assert tday() >= now
Can anyone tell me what's wrong with this code. I have to follow guidelines for this class so they want it so your weekly pay is calculated by a "calc_weekly_wages" function and then for a "main" function to call the other and print it in a sentence rather than just a number output. I get an error that my "finalPay" variable is not defined, can anyone help?
hoursWorked = requestInteger("Enter weekly hours worked")
hourlyWage = requestNumber("Enter your hourly wage")
def calc_weekly_wages():
if hoursWorked <= 40:
finalPay = hoursWorked * hourlyWage
return (finalPay)
elif hoursWorked > 40:
finalPay = 40 * hourlyWage + (hoursWorked - 40)*(hourlyWage * 1.5)
return finalPay
def main():
calc_weekly_wages()
print ("Wages for " + str(hoursWorked) + "at $" + str(hourlyWage) + "is " + str(finalPay))
main()
Yes, finalPay is indeed out of scope on the line that does the print. The local variables of a function are inaccessible outside of that function.
Fortunately, finalPay is returned by calc_weekly_wages(). So, you could capture the return value in a variable by the same name:
finalPay = calc_weekly_wages()
That would fix things. Or you could substitute the problematic reference to finalPay with the call to your function:
print ("Wages for " + str(hoursWorked) + "at $" + str(hourlyWage) + "is " + str(calc_weekly_wages()))
And that would work too.
I am trying to create a def file within a py file that is external eg.
calls.py:
def printbluewhale():
whale = animalia.whale("Chordata",
"",
"Mammalia",
"Certariodactyla",
"Balaenopteridae",
"Balaenoptera",
"B. musculus",
"Balaenoptera musculus",
"Blue whale")
print("Phylum - " + whale.getPhylum())
print("Clade - " + whale.getClade())
print("Class - " + whale.getClas())
print("Order - " + whale.getOrder())
print("Family - " + whale.getFamily())
print("Genus - " + whale.getGenus())
print("Species - " + whale.getSpecies())
print("Latin Name - "+ whale.getLatinName())
print("Name - " + whale.getName())
mainwindow.py:
import calls
import animalist
#import defs
keepgoing = 1
print("Entering main window")
while True:
question = input("Which animal would you like to know about?" #The question it self
+ animalist.lst) #Animal Listing
if question == "1":
print(calls.printlion())#Calls the animal definition and prints the characteristics
if question == "2":
print(calls.printdog())
if question == "3":
print(calls.printbluewhale())
'''if question == "new":
def new_animal():
question_2=input("Enter the name of the new animal :")'''
What I am trying to do is that question == new would create a new def in the calls.py and that I would be able to add a name to the def and the attributes as well.
I was hoping you could lead me to a way of how to do this, and if it is not possible please just say and I will rethink my project :)
What you're trying to do here seems a bit of a workaround, at least in the way you're trying to handle it.
If i understood the question correctly, you're trying to make a python script that takes input from the user, then if that input is equal to "new", have it be able to define a new animal name.
You're currently handling this using a whole lot of manual work, and this is going to be extremely hard to expand, especially considering the size of the data set you're presumably working with (the whole animal kingdom?).
You could try handling it like this:
define a data set using a dictionary:
birds = dict()
fish = dict()
whales = dict()
whales["Blue Whale"] = animalia.whale("Chordata",
"",
"Mammalia",
"Certariodactyla",
"Balaenopteridae",
"Balaenoptera",
"B. musculus",
"Balaenoptera musculus",
"Blue whale")
whales["Killer Whale"] = ... # just as an example, keep doing this to define more whale species.
animals = {"birds": birds, "fish": fish, "whales": whales} # using a dict for this makes you independent from indices, which is much less messy.
This will build your data set. Presuming every whale class instance (if there is one) inherits properties from a presumptive Animal class that performs all the printing, say:
Class Animal():
# do some init
def print_data(self):
print("Phylum - " + self.getPhylum())
print("Clade - " + self.getClade())
print("Class - " + self.getClas())
print("Order - " + self.getOrder())
print("Family - " + self.getFamily())
print("Genus - " + self.getGenus())
print("Species - " + self.getSpecies())
print("Latin Name - "+ self.getLatinName())
print("Name - " + self.getName())
You can then have a Whale class:
class Whale(Animal)
Which now has the print_data method.
for whale in whales:
whales[whale].print_data()
With that out of the way, you can move on to adding input:
In your main.py:
while True:
question = input("Which animal would you like to know about?" #The question it self
+ animalist.lst) #Animal Listing
try:
id = int(question)
# if the input can be converted to an integer, we assume the user has entered an index.
print(calls.animals[animals.keys[id]])
except:
if str(question).lower() == "new": # makes this case insensitive
new_species = input("Please input a new species")
calls.animals[str(new_species)] = new_pecies
# here you should process the input to determine what new species you want
Beyond this it's worth mentioning that if you use dicts and arrays, you can put things in a database, and pull your data from there.
Hope this helps :)
Here is my code:
# This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def randomPosition():
""" This gets the robot to drive to a random position """
result = randint(1, 2)
if(result == 1):
forward(random(), random())
if(result == 2):
backward(random(), random())
def scan():
""" This allows the robot to rotate and print the numbers that each light sensors obtains """
leftLightSeries = [0,0,0,0,0,0]
centerLightSeries = [0,0,0,0,0,0]
rightLightSeries = [0,0,0,0,0,0]
for index in range(1,6):
leftLight = getLight("left")
leftLightSeries[index] = leftLightSeries[index] + leftLight
centerLight = getLight("center")
centerLightSeries[index] = centerLightSeries[index] + centerLight
rightLight = getLight("right")
rightLightSeries[index] = rightLightSeries[index] + rightLight
turnRight(.5,2.739)
return leftLightSeries
return centerLightSeries
return rightLightSeries
def printResults():
""" This function prints the results of the dice roll simulation."""
print " Average Light Levels "
print " L C R "
print "========================="
for index in range(1, 6):
print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index])
def main():
senses()
pressC()
randomPosition()
scan()
printResults()
main()
So, I am getting this error when I run my program.
NameError: global name 'leftLightSeries' is not defined
I understand that I must be doing something wrong related to the return statement. I'm not sure if I can only return one variable at the end of a user-defined function. If that were to be true, then I should probably separate the scan(): function. Anyways, I would appreciate any help on how to fix this error. Also, this is the result that I am looking for when I successfully complete my program:
Click Here
I am looking to complete the average values like the picture shows, but I am not worried about them at this point, only the list of values from the light sensors. I do not need to reach those exact numbers, the numbers will vary in the simulator.
If you want to return multiple items from scan(), don't use three separate return statements. Instead, do this:
return leftLightSeries, centerLightSeries, rightLightSeries
Also, when you call the function, you have to assign variable(s) to the returned values; it won't automatically create new local variables with the same names. So in main, call scan() like this:
leftLightSeries, centerLightSeries, rightLightSeries = scan()
OK - I am trying to get a Python function to accept variables from two other functions. Is this possible ?
A sample of what I am trying to do it below (I have simmed down the original code - for input here). Hopefully you get theidea of what I am trying to do. In a nutshell, I have Rectangle () which calls Extras() and the I want the output from Rectangle and Extras to be sent to the Calculate_Deposit ().
Is this possible ?
def calculate_deposit(total_cost, extras):
deposit_percent = float(raw_input("Enter Deposit % (as a decimal) of Total Cost: "))
months_duration = float(raw_input("Enter the number of months client requires: "))
if deposit_percent >0:
IN HERE JUST SOME CALCULATIONS
else:
print "The total amount required is: ", total_cost
def rectangle(width, height, depth, thickness):
type = raw_input("Enter lowercase c for concrete: ")
if type == 'c':
output = IN HERE JUST COME CALCULATIONS
else:
return raw_input("Oops!, something went wrong")
print output + extras()
total_cost = calculate_deposit(output, extras)
def extras():
type = float(raw_input("Enter 1 for lights: "))
if type == 1:
light = 200
print "The cost of lights are: ", light
return light
else:
return raw_input("No extras entered")
In rectangle, you call extras(), then you send just the function extras to calculate_deposit(). You want to send the result of the extras() call, not a reference to the function itself. You can make a minor change and save that value, referring to it when you print and when you go into calculate_deposit.
Change this:
print output + extras()
total_cost = calculate_deposit(output, extras)
To this:
extra = extras()
print output + extra
total_cost = calculate_deposit(output, extra)