sorry I am new to coding so I apologise if this is an amateur question. An exercise has asked that I create code that calculates the 4% interest on an investment for 1,2 and 3 years. I have duplicated a lot of code and would like to know how I could do it differently: in a more condensed way.
For example, is it possible to convert every year in one like such as this float(year1, year2, year3) as appose to having multiple lines of code?
startingBalance = input("Please enter your starting bank balance: ")
startingBalance = int(startingBalance)
year1 = (startingBalance * 1.04)
year2 = (year1 * 1.04)
year3 = (year2 * 1.04)
year1 = "{0:.2f}".format(year1)
year2 = "{0:.2f}".format(year2)
year3 = "{0:.2f}".format(year3)
print("Starting Balance: " + str(startingBalance) + "\n" + "Year 1 Balance: " + year1 + "\n" + "Year 2 Balance: " + year2 + "\n" + "Year 3 Balance: " + year3)
answer=str(input("would you like to withdraw your profits? Y/N: "))
if answer in ['Y', 'y']:
startingBalance = float(startingBalance)
year1 = float(year1)
year2 = float(year2)
year3 = float(year3)
year1Profit = year1 - startingBalance
year1Profit = "{0:.2f}".format(year1Profit)
year2Profit = year2 - startingBalance
year2Profit = "{0:.2f}".format(year2Profit)
year3Profit = year3 - startingBalance
year3Profit = "{0:.2f}".format(year3Profit)
str(year3Profit)
print("Year | Balance | Profit " + "\n" + "Year 1 " + str(year1) + " " + year1Profit + "\n" + "Year 2 " + str(year2) + " " + year2Profit + "\n" + "Year 3 " + str(year3) + " " + year3Profit)
elif answer in ['N', 'n']:
print("Goodbye")
else:
print("Invalid Entry")
Technically this is one line:
year1, year2, year3 = float(year1), float(year2), float(year3)
But I think it would be clearer if you didn't change the type of your variables after initialisation. You can keep them as floats all the time change your print line to:
print("Starting Balance: " + str(startingBalance) + "\n" + "Year 1 Balance: " + "{0:.2f}".format(year1) + "\n" + "Year 2 Balance: " + "{0:.2f}".format(year2) + "\n" + "Year 3 Balance: " + "{0:.2f}".format(year3))
This saves you from converting to string and back again.
This question might be more appropriate in Code Review but:
year1 = "{0:.2f}".format(year1)
Can be replaced by:
year1 = round(year1, 2)
You use .format and print("foo" + bar) in the same code I recommend using one type:
F-strings if Python3.6 or above
print(f"Starting Balance: {startingBalance}\nYear 1 Balance: {year1}\nYear 2 Balance: {year2}\nYear 3 Balance: {year3}")
.format if Python2 or 3 < 3.6
print("Starting Balance: {}\nYear 1 Balance: {}\nYear 2 Balance: {}\nYear 3 Balance: {}".format(startingBalance, year1, year2, year3))
No need to put str() here :
answer=str(input("would you like to withdraw your profits? Y/N: "))
The input() always returns a string.
Use "\t" when you want (i'm guessing) tabulations instead of a bunch of spaces (ugly):
print("Year | Balance | Profit " + "\n" + "Year 1 " + str(year1) + " " + year1Profit + "\n" + "Year 2 " + str(year2) + " " + year2Profit + "\n" + "Year 3 " + str(year3) + " " + year3Profit)
Same thing here use f-strings or .format to format your string.
To avoid writing the same code, you can create a function to compute the final balance and the profit. Then you can use the others answers to know how to format your variable and return them
def compute_year(starting_balance, number_of_year):
return (startingBalance * 1.04 ** number_of_year, startingBalance * 1.04 ** number_of_year - startingBalance)
year1, year1Profit = compute_year(startingBalance, 1)
year2, year2Profit = compute_year(startingBalance, 2)
year3, year3Profit = compute_year(startingBalance, 3)
Yes, it is very much possible!
When you find yourself writing repeating lines of code, try using functions!
In that way you only have to define an expression once!
example:
year1 = (startingBalance * 1.04)
year2 = (year1 * 1.04)
year3 = (year2 * 1.04)
Can be change to
def interest(balance):
return balance * 1.04
year1 = interest(startingBalance)
year2 = interest(year1)
But this still seems repetitive, right?
Now try using a for-loop aswell:
current_balance = startingBalance
for year in range(4):
current_balance = interest(current_balance)
print(current_balance)
Now in each loop, you can print the value of the new balance!
Finally add in the line printg for a pretty output, and you could get something like this:
def interest(balance, years):
return balance * (1.04 ** years)
def print_gains(balance, year):
header = 'Year | Balance | Profit '
print(header)
print('-' * len(header))
for year in range(1 + year):
new_balance = interest(balance, year)
print('%5d| %10.2f | %10.2f' % (year, new_balance, new_balance - balance))
print()
def main():
print_gains(10000, 5)
main()
resulting in the following output:
Year | Balance | Profit
-----------------------------
0| 10000.00 | 0.00
1| 10400.00 | 400.00
2| 10816.00 | 816.00
3| 11248.64 | 1248.64
4| 11698.59 | 1698.59
5| 12166.53 | 2166.53
I hope this helps you!
Related
I have created a class to store the details of all the employees and display the same. But I have to display the sum of salary of all the employees. I am unable to do that. Can anyone help me......???
class Employee :
empid = 0
name = None
salary = 0.0
def getInput(self) :
print("Enter the empid :: ", end ="")
self.empid = input()
print("Enter the name :: ", end ="")
self.name = input()
print("Enter the salary :: ", end ="")
self.salary = input()
def display(self) :
print("Employee id = " + str(self.empid))
print("Employee name = " + self.name)
print("Employee salary = " + str(self.salary))
def main( args) :
e = [None] * (3)
i = 0
while (i < 3) :
e[i] = Employee()
e[i].getInput()
i += 1
print("**** Data Entered as below ****")
i = 0
while (i < 3) :
e[i].display()
i += 1
if __name__=="__main__":
Employee.main([])
How to print sum of salary of employees after storing them using this.???
First of all, you need to get main() out of your class. Then, you should actually add the code that calculate the sum of the salaries. sumsalary() isn't declared anywhere in your code, the reason that you are not getting an error, it's because the value of i is greater than 3, so that part isn't reachable.
I updated your code so that it calculates the sum without creating a function.
class Employee :
empid = 0
name = None
salary = 0.0
def getInput(self) :
print("Enter the empid :: ", end ="")
self.empid = input()
print("Enter the name :: ", end ="")
self.name = input()
print("Enter the salary :: ", end ="")
self.salary = input()
def display(self) :
print("Employee id = " + str(self.empid))
print("Employee name = " + self.name)
print("Employee salary = " + str(self.salary))
def main(args):
e = [None] * (3)
i = 0
while (i < 3) :
e[i] = Employee()
e[i].getInput()
i += 1
print("**** Data Entered as below ****")
i = 0
while (i < 3) :
e[i].display()
i += 1
i=0
sum_salary = 0
while(i<3):
sum_salary += int(e[i].salary)
i += 1
print("sum salary: " + str(sum_salary) )
if __name__=="__main__":
main([])
I keep editing my text but I keep on getting the same error!
My code:
import random
Female_Characters = ["Emily", "Ariel", "Jade", "Summer"]
Male_Characters = ["Blake", "Max", "Jack", "Cole", "Daniel"]
PlacesToMeet = ["Beach", "Park", "Train Station", "Cave"]
SheSaid = ["Lets go explore!", "I'm tired", "I saw a purple frog", "My tounge hurts"]
HeSaid = ["I didnt get much sleep", "I wanna go inside that cave!", "Oh, ok"]
Outcomes = ["They never got to", "They were never found again.", "They enjoyed their day and went to
get Ice Cream!"]
ChosenFemale = random.choice(Female_Characters)
ChosenMale = random.choice(Male_Characters)
ChosenMeet = random.choice(PlacesToMeet)
ChosenShesaid = random.choice(SheSaid)
ChosenHeSaid = random.choice(HeSaid)
print ("There were two friends, their names are ") + (ChosenMale) + (", and ") + (ChosenFemale) + (".") + ("One day when they were at the") + (ChosenMeet) + (", ") + (ChosenFemale) + (" Said, ") + (ChosenShesaid) + (". Then") + (ChosenMale) + (" Said ") + (ChosenHeSaid) + (". After that, ") + random.choice(Outcomes)
Still new to python
You have incorrect parentheses on the print line.
print("There were two friends, their names are " + ChosenMale + ", and " + ChosenFemale + "." + "One day when they were at the" + ChosenMeet + ", " + ChosenFemale + " Said, " + ChosenShesaid + ". Then" + ChosenMale + " Said " + ChosenHeSaid + ". After that, " + random.choiceOutcomes)
Your code was calling
print("There were two friends, their names are ")
which returns None, and then trying to concatenate that with all the other strings.
Maybe you were following Python 2.x instructions. In Python 2, print is a statement so it didn't take an argument in parentheses, but in Python 3 it's an ordinary function.
remove the parenthesis at the end of this string
print("There were two friends, their names are "
and add it at the end of
random.choice(Outcomes)
so it should be:
print ("There were two friends, their names are " + (ChosenMale) + (", and ") + (ChosenFemale) + (".") + ("One day when they were at the") + (ChosenMeet) + (", ") + (ChosenFemale) + (" Said, ") + (ChosenShesaid) + (". Then") + (ChosenMale) + (" Said ") + (ChosenHeSaid) + (". After that, ") + random.choice(Outcomes))
I would like to get help with this program I have made. The function of the code is so the users can input a city anywhere in the world and they will then get data about the weather for that city.
I want it to restart the program from the top, but it only restarts the program from where the results are.
# - Weather Program -
#Import
import datetime
import requests
import sys
#Input
name_of_user = input("What is your name?: ")
city = input('City Name: ')
#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=<app_id_token>&q='
url = api_address + city
json_data = requests.get(url).json()
#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
#Loop
while True:
#Program
if degrees < 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees < 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees >= 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
elif degrees >= 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
#Loop
restart = input('Would you like to check another city (y/n)?: ')
if restart == 'y':
continue
else:
print('Goodbye')
sys.exit()
So this is what happens.. The loop only loops the question with the input and data already filled in.
What is your name?: Test
City Name: Oslo
Good afternoon Test.
The date today is: 01 May 2019
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: y
Good afternoon Test.
The date today is: 01 May 2019
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: n
Goodbye
Process finished with exit code 0
I want the code to loop from the top so I can press y so the program will ask me for another city to input.
You are never updating your values. Let's take a simpler example:
x = int(input("What is the number you choose? "))
while True:
if x >3:
print(x)
continue
else:
break
If I run this, I will get x printed out forever if I choose, say 5. The code defining x will never be re-run because it's outside of the loop. To fix this, I can move my code for x into the while loop:
while True:
x = int(input("What number do you choose? "))
if x>3:
print(x)
else:
break
This will run the code for x every time the loop executes, so x can now change. Applying this to your code:
# loop is now up near the top
while True:
# You want these values to change on each iteration of the while
# loop, so they must be contained within the loop
name_of_user = input("What is your name?: ")
city = input('City Name: ')
#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=<app_id_token>&q='
url = api_address + city
json_data = requests.get(url).json()
#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
if degrees... # rest of your statements
Now the value for City can change, and you can apply that to the other data structures as well
Put your while loop starting above the first input. Don't forget to declare your constant variables above the main loop.
The while loop only covers the code that display the results, the code that takes input and request the results is only executed once.
You need to have everything except the import statements within the while loop
All you need to is put the input section and the API sections inside your while true loop.
I will say, I was unable to actually test my solution, but I am almost completely sure that it will work. Good luck!
I'm currently having a problem with a function in python. This is my code before I tried putting it in a function:
for i in range(4):
for y in Days:
for x in "ABCDEF":
data = input("What was the punctuality for bus " + x + " on " + str(y) + ", Week " + str(Week) + "? ")
Bus = "Bus" + str(x)
Buses[Bus].append(str(data))
print()
Week += 1
And it works like it is meant to, however I tried putting it in a function:
def InputData():
for i in range(4):
for y in Days:
for x in "ABCDEF":
data = input("What was the punctuality for bus " + x + " on " + str(y) + ", Week " + str(Week) + "? ")
Bus = "Bus" + str(x)
Buses[Bus].append(str(data))
print()
Week += 1
And I am getting errors about the whole Week += 1 part. They say:
[pyflakes] local variable 'Week' (defined in enclosing scope on line 11)
referenced before assignment
[pyflakes] local variable 'Week' is assigned to but never used
Any help would be greatly appreciated.
Week = 0
Put this at the beginning of your code.
This program is supposed to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company. When I try to run it, it shows a SyntaxError, and I'm not sure why. Here's my code:
def ccb(balance, annualInterestRate, monthlyPaymentRate):
monthlyInterestRate = annualInterestRate / 12.0
month = 0
for calc in range(12):
minMonthlyPaymentRate = balance * monthlyPaymentRate
unpaidBalance = balance - minMonthlyPaymentRate
interest = monthlyInterestRate * unpaidBalance
print ("Month | Balance | Unpaid Balance | Interest")
print (month + " | " + round(balance) + " | " + round(unpaidBalance) + " | " + Interest)
balance = unpaidBalance + Interest
month += 1
print ("Remaining balance: " + round(balance))
A few things (though none appear to throw SyntaxError - seconding Andrew in the comments, if it's a SyntaxError - share the full message):
1) You can't implicitly make an integer a string, you need to cast it. Ex:
str(round(balance))
instead of
round(balance)
2) 'Interest' is never defined, but 'interest' is.
With those fixed, it runs fine.
Also, this might be relevant ;)