Pytest isn't running tests in this one Python file - python

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

Related

How to print new balance after adding amount to the initial one?

I'm learning Python and went with a simple ATM code. I've tested it and everything works DownStream - what I mean by this is:
I have a few options when the class is initialized - Balance, Deposit, Withdraw, Exit.
When I run Balance I receive the amount set.
2.1. I go with Deposit - it shows the new amount the person has in their account
2.2. When I use Withdraw I get correct amount as well
Question - When I Deposit and then type Balance I'm getting the initial Balance of the user - that is expected. How can I change the code so after Depositing Money and select Balance to show me the new Balance?
Is this possible to be performed without much complicating the code?
The code:
class User:
def __init__(self):
self.fname = input('Enter your first name: ')
self.lname = input('Enter your last name: ')
self.age = input('Enter your age: ')
def user_details(self):
print('Details:')
print(f"First Name: {self.fname}")
print(f"Last Name: {self.lname}")
print(f"User age: {self.age}")
def deposit_money(self):
self.deposit_amount = 100
return self.deposit_amount
def withdraw_money(self, withdraw_amount):
self.withdraw_amount = withdraw_amount
return self.withdraw_amount
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
def user_bank_balance(self):
self.user_balance = 300
print ('Your current balance is ${}'.format(self.user_balance))
def deposit_atm(self, user):
self.total_savings = 0
deposit_m = float(input('How much do you want to deposit? '))
if deposit_m > user.deposit_money():
print('You do not have enough money to deposit')
elif deposit_m == user.deposit_money():
print('Amount deposited: ${}'.format(deposit_m))
self.total_savings = self.user_balance + deposit_m
print('Total amount in your account: ${}'.format(self.total_savings))
def withdraw_atm(self):
savings_left = 0
sum_to_withdraw = float(input('How much do you want to withdraw? '))
if self.atm_balance > sum_to_withdraw and self.user_balance > sum_to_withdraw:
savings_left = self.total_savings - sum_to_withdraw
print("You have withdraw {}".format(sum_to_withdraw))
print('You balance is {}'.format(savings_left))
elif self.atm_balance > sum_to_withdraw and self.user_balance < sum_to_withdraw:
print('Daily limit eceeded')
else:
print('ATM out of service')
class ATMUsage:
#classmethod
def run(cls):
print('Bulbank ATM')
instructions = print("""
Type 'Balance' to check your current balance,
Type 'Deposit' to deposit amount into your account,
Type 'Withdraw' to withdraw from your account,
Type 'Exit' to exit from your account,
""")
active = True
user1 = User()
atm1 = ATM()
user1.user_details()
while active:
selection = input("What would you like to do: 'Balance', 'Deposit', 'Withdraw', 'Exit': ")
if selection == 'Balance'.lower():
atm1.user_bank_balance()
elif selection == 'Deposit'.lower():
atm1.deposit_atm(user1)
elif selection == "Withdraw".lower():
atm1.withdraw_atm()
elif selection == 'Exit'.lower():
print('Thanks for passing by. Have a good one!')
break
else:
print('Wrong selection. Please, try again')
ATMUsage.run()
That's because every time you call the user_bank_balance method, you set the user_balance attribute to 300. So it wouldn't matter what updates you did on the user_balance, whenever you call the user_bank_balance method, you'll get 300
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
self.user_balance = 300
def user_bank_balance(self):
print ('Your current balance is ${}'.format(self.user_balance))

Python TypeError: CreateAccount() missing 1 required positional argument

I created this terminal app a while ago and it was working, but I haven't touched in a while and I just opened it back up and I can't figure out what this error is and why I'm having it. It's happening during the account creation part of my program. I tried a couple things out but I'm still not sure what's going on.
**TypeError: CreateAccount() missing 1 required positional argument**
main.py
from Account import Account
from Transaction import Transaction
from enum import Enum
from fcp import CreateAccount
#variables and lists needed for program
new_accounts = []
#do no tneed, just put the balance of 0 straight into the factory class attribute
#balance = 0
user_name = []
Transactions = []
account_number = 0
#***Functions for switch statements***
def create_user():
global new_accounts
global account_number
active_create_account = False
new_username = input("\n\nCreate a username:")
email = input("Write your email: ")
account_number +=1
print(account_number)
# append the createaccount call straight into new_accounts.append
new_accounts.append(CreateAccount(user_name,email, int(input('Choose 1 for Checkings or 2 for Savings: ')), 0, 0))
active_create_account = True
for i in new_accounts:
if account_number == i.account_number:
i.new_account_creation()
account_search_balance = True
if account_search_balance == False:
print("\nThat account does not exist. Please re-enter option 5 and try again.")
main()
fcp.py
from Account import Account
from Transaction import Transaction
#BLANK CLASS TEMPLATE
def CreateAccount(self,user_name,email,account_type,balance,account_number):
account_number +=1
if (account_type == 1): return CreateCheckingAccount(user_name,email,1,balance,account_number)
if (account_type == 2): return CreateSavingsAccount(user_name,email,2,balance,account_number)
else:
return CreatAccount(user_name,email, int(input('Choose 1 for Checkings or 2 for Savings: ')),balance,account_number)
def CreateCheckingAccount(self,user_name,email,account_type,balance,account_number):
return Account(user_name, email,'Checking',balance,account_number)
def CreateSavingsAccount(self,user_name,email,account_type,balance,account_number):
return Account(user_name, email,'Savings',balance,account_number)
transaction.py
import datetime
class Transaction():
def __init__(self,account_number,type_of_transaction,old_balance,new_balance,date = datetime.datetime.now()):
self.account_number = account_number
self.type_of_transaction = type_of_transaction
self.old_balance = old_balance
self.new_balance = new_balance
self.date = datetime.datetime.now()
def to_string(self):
print("\nThe account number is: " + str(self.account_number) + "\nThe type of transaction is: " + self.type_of_transaction + "\nThe old balance was: " + str(self.old_balance) + "\nThe new balance is: " + str(self.new_balance) + "\nThe date of the transaction was: " + str(self.date))
def print_date(self):
print(str(self.date))
Account.py
class Account(object):
def __init__(self,user_name,email,account_type,balance,account_number):
self.user_name = user_name
self.email = email
self.account_type = account_type
self.balance = balance
self.account_number = account_number
def print_balance(self):
print("\nAccount bala is "+ str(self.balance))
return
def new_balance(self):
print("\nThe new account balance is: " + str(self.balance))
def to_string(self):
print("\nUsername: " + self.user_name + "\n\nEmail: " + self.email + "\n\nAccount type: " + (self.account_type) +
"\n\nYour account balance is:" + str(self.balance) +"\n\nAccount number: " + (self.account_number))
def new_account_creation(self):
print("\nCongragulations on your new account! Below is the info:\nUsername: " + self.user_name + "\nEmail: " + self.email + "\nAccount type: " + self.account_type +
"\nYour account balance is:" + str(self.balance) +"\nAccount number: " + str(self.account_number)+ " <--- Do NOT forget this number")
def Deposit(self):
deposit = int(input("\nHow much would you like to deposit?: "))
self.balance += deposit
def withdraw(self,withdraw):
self.balance -= withdraw
you should initiate the class object that contains createAccount() method before invoke.
class TestClass:
def __init__(self):
print("in init")
def createAccount(self, ...):
print("in Test Func")
testInstance = TestClass()
testInstance.createAccount(...)
It looks as though your method definition requires self as an argument but CreateAccount is not in a class. Therefore it is not required.
(remove self in the required arguments)
It's pretty clear, even though you left out the rest of the error message and failed to minimize your code: your function profile requires a self argument that the call didn't bother to provide. Since you used the name self, it seems as if you might want to create a class -- but you didn't do that with the function, nor with the call.
If a class is, indeed, what you want, then please return to your tutorial on class to make sure you implement all of the right items.

Cannot pass returned values from function to another function in python

My goal is to have a small program which checks if a customer is approved for a bank loan. It requires the customer to earn > 30k per year and to have atleast 2 years of experience on his/her current job. The values are get via user input. I implemented regexs to validate the input to be only digits without any strigns or negatives, nor 0.
But the 3rd function asses_customer is always executing the else part. I think everytime the parameters are either None, either 0
here's the source code:
import sys
import re
import logging
import self as self
class loan_qualifier():
# This program determines whether a bank customer
# qualifies for a loan.
def __init__(self): #creates object
pass
def main():
salary_check()
work_exp_check()
asses_customer(salary = 0, years_on_job = 0)
def salary_check():
input_counter = 0 # local variable
# Get the customer's annual salary.
salary = raw_input('Enter your annual salary: ')
salary = re.match(r"(?<![-.])\b[1-9][0-9]*\b", salary)
while not salary:
salary = raw_input('Wrong value. Enter again: ')
salary = re.match(r"(?<![-.])\b[1-9][0-9]*\b", salary)
input_counter += 1
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
else:
return salary
def work_exp_check():
input_counter = 0 #local variable to this function
# Get the number of years on the current job.
years_on_job = raw_input('Enter the number of ' +
'years on your current job: ')
years_on_job = re.match(r"(?<![-.])\b[1-9][0-9]*\b", years_on_job)
while not years_on_job:
years_on_job = raw_input('Wrong work experience. Enter again: ')
years_on_job = re.match(r"(?<![-.])\b[1-9][0-9]*\b", years_on_job)
input_counter += 1
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
else:
return years_on_job
def asses_customer(salary, years_on_job):
# Determine whether the customer qualifies.
if salary >= 30000.0 or years_on_job >= 2:
print 'You qualify for the loan. '
else:
print 'You do not qualify for this loan. '
# Call main()
main()
You have stated:
It requires the customer to earn > 30k per year and to have at least 2 years of experience on his/her current job.
We can write some simple statements that request a number and if a number is not given then ask for that number again.
The following code is a very simple approach to achieving that goal.
class Loan_Checker():
def __init__(self):
self.salary = 0
self.years_on_job = 0
self.request_salary()
self.request_years()
self.check_if_qualified()
def request_salary(self):
x = raw_input('Enter your annual salary: ')
try:
self.salary = int(x)
except:
print("Please enter a valid number")
self.request_salary()
def request_years(self):
x = raw_input('Enter the number of years on your current job: ')
try:
self.years_on_job = int(x)
except:
print("Please enter a valid number")
self.request_years()
def check_if_qualified(self):
if self.salary >= 30000 and self.years_on_job >= 2:
print 'You qualify for the loan. '
else:
print 'You do not qualify for this loan. '
Loan_Checker()
You have a few errors in your code, and I've refactored it to use the class structure you seemed to want to imply.
import sys
import re
import logging
class loan_qualifier():
# This program determines whether a bank customer
# qualifies for a loan.
def __init__(self): #creates object
self.salary = self.salary_check()
self.years_on_job = self.work_exp_check()
def salary_check(self):
input_counter = 0 # local variable
# Get the customer's annual salary.
salary = None
while salary is None:
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
elif input_counter >= 1:
print ("Invalid salary.")
salary = raw_input('Enter your salary: ')
salary = re.match(r"(?<![-.])\b[1-9][0-9]*\b", salary).group(0)
input_counter += 1
# broke out of loop, so valid salary
return salary
def work_exp_check(self):
input_counter = 0 #local variable to this function
# Get the number of years on the current job.
years_on_job = None
while years_on_job is None:
if input_counter >= 6:
print ("No more tries! No loan!")
sys.exit(0)
elif input_counter >= 1:
print ("Invalid year amount")
years_on_job = raw_input('Enter the number of years at your current job: ')
years_on_job = re.match(r"(?<![-.])\b[1-9][0-9]*\b", years_on_job).group(0)
input_counter += 1
# broke out of loop, so valid years_on_job
return years_on_job
def assess_customer(self):
# Determine whether the customer qualifies.
if int(self.salary) >= 30000.0 and int(self.years_on_job) >= 2:
print 'You qualify for the loan. '
else:
print 'You do not qualify for this loan. '
if __name__ == "__main__":
lq = loan_qualifier()
lq.assess_customer()
Some of the errors fixed include the way you were calling assess_customer initially (you were assigning 0's to both values in the function call), as well as the spelling of assess :p. Your condition in assess_customer should also have been an and instead of an or (you wanted both conditions to be true for them to qualify, not for either condition to be true).
You actually don't even really need to do the:
self.salary = self.salary_check()
self.years_on_job = self.work_exp_check()
lines. You could just directly assign the class variables in the functions (i.e. instead of returning, just set self.salary = blah in salary_check). That's kind of a personal choice thing though. I think this makes it clear.
Hopefully this is all clear to you. Let me know if you have any questions. The code can be called by simply typing python NAME_OF_YOUR_FILE.py.
Edit: I didn't realize how broken the salary and years checks were, the new code should fix them.
Edit: Fixed the regex results in this version. My bad.
In this fragment you pass third function always salary = 0 and years_on_job = 0
Try this way:
salary = salary_check()
years_on_job = work_exp_check()
asses_customer(salary, years_on_job)

Functions And While Loop Complication In Python

def main():
totalprofit = 0
stockname = input("Enter the name of the stock or -999 to quit: ")
while stockname != "-999":
sharesbought, purchasingprice, sellingprice, brokercommission = load()
amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss = calc(sharesbought, purchasingprice, sellingprice, brokercommission)
output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofpaidcommission, profitorloss)
stockname = input("Enter the name of the next stock (or -999 to quit): ")
totalprofit += profitorloss
print("\n Total profit is: ", format(totalprofit, '.2f'))
def load():
sharesbought = int(input("Number of shares bought: "))
purchasingprice = float(input("Purchasing price: "))
sellingprice = float(input("Selling price: "))
brokercommission = float(input("Broker commission: "))
return sharesbought, purchasingprice, sellingprice, brokercommission
def calc(sharesbought, purchasingprice, sellingprice, brokercommission):
amountpaid = sharesbought * purchasingprice
amountofpaidcommission = amountpaid * (brokercommission/100)
amountstocksoldfor = sharesbought * sellingprice
amountofsoldcommission = amountstocksoldfor * (brokercommission/100)
profitorloss = (amountpaid + amountofpaidcommission) - (amountstocksoldfor - amountofsoldcommission)
return amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss
def output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss,):
print("\n Stock name: ", stockname, sep = '')
print("Amount paid for the stock: ", format(amountpaid, '.2f'))
print("Commission paid to broker when the stock was bought: ", format(amountofpaidcommission, '.2f'))
print("Amount the stock sold for: ", format(amountstocksoldfor, '.2f'))
print("Commission paid to broker when the stock was sold: ", format(amountofsoldcommission, '.2f'))
print("Profit or loss: ", format(profitorloss, '.2f'))
main ()
The objective of the first function is to allow a user to input the followings as many times as she or he wants until the user decides is done:
Stock name
Shares bought
Selling price
Broker commission
My main problem is then in the main function. I am skeptical whether I am using the while loop correctly or if it's correct at all. I tried to run the program but it won't output anything.
Also, shouldn't I add this at the end of the program with the values inputted to call all the functions above:
def main()
load()
calc()
output()
Or is it fine within the while loop?
I think a while loop is perfectly appropriate for this use case, where you want to loop an indeterminate number of times, stopping when some condition is not met.
There is one obvious problem, on this line:
stockname +=1
This doesn't make any sense. Since stockname is a string, you can't add one to it. Instead, you should be asking the user for the next stock name (or a "special" value to signal they're done). Try replacing that line with something like:
stockname = input("Enter the name of the next stock (or -999 to quit): ")
The rest of your code appears correct, if rather verbose. Unless you think it's likely you'll call some of your other functions in some other place in your code, it might be simpler and cleaner to include all the logic in one function. Functions are nice, but you should balance the benefits of isolating each part of your code in its own function against the effort of passing lots of values between them.

Trying to pass local variables to other modules in Python

I am a beginner to Python and i'm having a hell of a time trying to get this program to work. I need to pass local variables to other modules and I've tried multiple things and I can't get it to work. It's just a Extremely simple program that calculates commission. I've literally spent hours trying to get it to work. I'm using the latest version of Python.
import os
def main():
input_salesperson_data()
commission = calculate_commission(sales_amount)
determine_bonus(years_worked, commission)
output_commission(name, commission)
def input_salesperson_data():
name = (input("\n\t\tWhat is the full name of the salesperson: "))
sales_amount = float(input("\n\t\tWhat is the sales amount of the salesperson: "))
years_worked = int (input("\n\t\tHow many years has the salesperson worked for the company: "))
return(name, sales_amount, years_worked)
def calculate_commission(sales_amount):
commission_rate1 = 0.15
commission_rate2 = 0.25
commission_rate3 = 0.30
if sales_amount <= 20000:
commission = sales_amount * commission_rate1
elif sales_amount > 20000 and sales_amount <= 40000:
commission = sales_amount * commission_rate2
else:
commission = sales_amount * commission_rate3
return(commission)
def determine_bonus(sales_amount, years_worked, commission):
if years_worked > 20:
commission *= 2
return(commission)
def output_commission(name, commission):
os.system("cls")
print("\n\n\t\t\t SALESPERSON COMMISSION REPORT")
print("\n\t\t\tSalesperson Name: ", name)
print("\t\t\tCommission Amount: ", format(commission, ',.2f'))
input("\n\t\tPress enter to exit...")
os._exit(1)
main()
def main():
information = input_salesperson_data()
commission = calculate_commission(information[1])
determine_bonus(information[2], commission)
output_commission(information[0], commission)
In python, the scope of the variable is contained in the function; however, in input_salesperson_data(), you're returning a tuple, but not saving it. information will save what is returned by input_salesperson_data(), and you can access what you need as shown above.
Also, in calculate_commission(), you can simple return commission. Additionally, you don't need to manually exit the program.
Finally, change:
def determine_bonus(sales_amount, years_worked, commission):
to
def determine_bonus(years_worked, commission):
as sales_amount is completely irrelevant.

Categories

Resources