As said in the title, I am creating a currency exchange program
I want to create a program that converts every single type of currency into another but I'm not sure the most efficient way of doing it
My Thinking
My intial plan was to create functions for all currency conversions and create if statements that would execute the function when both conditions are true. But this will take me ages...
# what currency they want to exchange
currency = input("What currency would you like to exchange: ").lower()
# what currency they want to exchange to
exchange_currency = input("What currency would you like to exchange to: ").lower
# how much they want to exchange
amount_of_currency = input("How much %s would you like to exchange: " % (currency))
# calculates pound to dollar
def pound_to_dollars(amount_of_currency):
result = float(amount_of_currency) * 1.28
print("That would be",result,exchange_currency)
# calculation takes place if both conditions are true
if currency == "pound" or "£" and exhange_currency == "dollar" or "$":
pound_to_dollars(amount_of_currency)
Questions
Is there a way to have one function that would be able to take care of all the conversions?
How would you guys go about creating a currency conversion system efficiently?
# build a dictionary of rates
exchange_rates = {
# MADE UP RATES
("USD", " EUR"): .85,
("BRL", "YEN"): 150,
# Add as desired
}
def convert(original_currency, new_currency):
# get the relevant rate from the dictionary
rate = exchange_rates[(original_currency, new_currency)]
# prompt user for how much he wants to exchange.
user_value = raw_input("How much would you like to exchange {}? ".format(original_currency))
# explicitly define type of input
amount = float(user_value)
# perform conversion
conversion = amount * rate
print " %s %s is equal to %s %s." % (user_value, original_currency, conversion, new_currency)
If you notice, all of those x_currency_to_y_currency functions all have a similar structure, this is typically a sign that a more general purpose function can be made to perform a task. This concept in programming falls under the term "DRY" an acronym for "Don't repeat yourself".
An example use of this function would look like:
convert('USD', 'EUR')
Which would output "x USD is equal to y EUR" where x is amount of currency to convert input by the user.
Related
I'm trying to write a program that will help me in my job to write behavioral reports on teenage boys in a therapeutic program. The goal is to make it easier to write the everyday expectations(eating, hygiene, school attendance, etc) so that I can write the unique behaviors and finish the report faster. I'm currently working on how many meals the boy at during the day and am trying to get it to validate that the user input is the correct type of input and within the correct range(0-3). Afterwards I want to change the variable depending on the answer given so it will print a string stating how many meals they ate. I've been able to get the program to validate the type to make sure that the user gave and integer but I cant get it to make sure that the given answer was in the desired range. Any help would be appreciated I only started learning python and programming a month ago so very inexperienced.
Here's what my code looks like so far and what I would like the variable to change to depending on the given answer.
Name=input('Student Name:')
while True:
try:
Meals=int(input('Number of Meals(between 0-3):'))
except ValueError:
print ('Sorry your response must be a value between 0-3')
continue
else:
break
while True:
if 0<= Meals <=3:
break
print('not an appropriate choice please select a number between 0-3')
#if Meals== 3:
#Meals= 'ate all 3 meals today'
#elif Meals==2:
#Meals='ate 2 meals today'
#elif Meals==1:
#Meals='ate only 1 meal today'
#elif Meals==0:
#Meals='did not eat any meals today'
You can check if number of inputted meals falls to valid range and if yes, break from the loop. If not, raise an Exception:
while True:
try:
meals = int(input('Number of Meals(between 0-3):'))
if 0 <= meals <= 3:
break
raise Exception()
except:
print('Please input valid integer (0-3)')
print('Your choice was:', meals)
Prints (for example):
Number of Meals(between 0-3):xxx
Please input valid integer (0-3)
Number of Meals(between 0-3):7
Please input valid integer (0-3)
Number of Meals(between 0-3):2
Your choice was: 2
Just started programming in python 3 and I am trying to pull from an input() where I have placed the input() command in the first line and then further down use the output() to retrieve the input().
Here is an example:
rent = eval(input("How much does rent cost per year? $"))
Now I want to get the input I put in (10,000) and retrieve it from the input automatically using output() or another command.
print output("The family rent is", _______ , "per year."
What code would go in the ________ so I can retrieve what I put in for the input?
Thanks - newbie
the code as is :
# get user input
user_input = input("How much does rent cost per year? $")
# cast to int or whaterver you're expecting
try :
cost = int(user_input)
except :
print ("expecting a number")
# stop here maybe return
# print output
print ("The family rent is", cost , "per year.")
Use string formatting:
print('The family rent is {} per year'.format(rent))
See here for documentation of string formatting:
https://docs.python.org/3/library/string.html#format-string-syntax
First of all here is the code I have so far for my small project.
# Problem: working out a percentage of minutes
# Inputs: percentage constant, empty list [activities], total activity time
PERCENTAGE = 100
activities = []
total_minutes = int(input('What was the total mobile phone usage (minutes) '))
# Loop: take users activity inputs
while sum(activities) < total_minutes:
activity_name = input('What was the activity? ')
activity_time = int(input('How many minutes on this activity? '))
# Add the activity to the list
activities = activities + [activity_name, activity_time]
print(activities)
'''Now, what I am aiming to do is have the activity name with the time spent on the activity in the list [activities]. I want to be able to retrieve either the activity name or time individually and to also "activities.sort()" by the integer value while obviously coinciding with the correct activity name.
Please make your answer as simple as possible (for someone in his early stage of university, second module)
Thanks in advance :)'''
I am having trouble with making a simple calculator work. There are some requirements I need to meet with it:
Need to be able to calculate the average of however many grades the user wants
Be able to calculate within the same program separate grade averages
for multiple 'users'
Give the option to exclude the lowest value entered for each person
from their individual average calculation.
I have some code, it is pretty much a mess:
def main():
Numberofstudents=eval(input("How many students will enter grades today? "))
Name=input("What is your frist and last name? ")
numberofgrades=eval(input("How many grades do you want to enter? "))
gradecount=0
studentcount=1
lowestgradelisty=[]
while studentcount<=Numberofstudents:
gradetotal=0
while gradecount<numberofgrades:
gradeforlisty=eval(input("Enter grade please: "))
gradetotal=gradetotal+gradeforlisty
gradecount=gradecount+1
Numberofstudents=Numberofstudents-1
studentcount=studentcount+1
lowestgradelisty.extend(gradeforlisty)
min(lowestgradelisty.extend(gradeforlisty))
Drop=(min(lowestgradelisty.extend(gradeforlisty))), "is your lowest grade. do you want to drop it? Enter as yes or no: "
if (Drop=="yes"):
print(Name, "The new total of your grades is", gradetotal-min(lowestgradelisty.append(gradeforlisty)/gradecount))
elif (Drop=="no"):
print("the averages of the grades enetered is", gradetotal/gradecount)
gradecount=0
studentcount=1
main()
Here's a function that does what it sounds like you wanted to ask about. It removes the smallest grade and returns the new average.
def avgExceptLowest(listofgrades):
# find minimum value
mingrade = min(listofgrades)
# remove first value matching the minimum
newgradelist = listofgrades.remove(mingrade)
# return the average of of the new list
return sum(newgradelist) / len(newgradelist)
A number of notes on your code:
The indentation of the code in your question is wrong. Fixing it may solve some of your problems if that's how it appears in your python file.
In Python the convention is to never capitalize a variable, and that's making your highlighting come out wrong.
If you code this correctly, you won't need any tracking variables like studentcount or gradecount. Check out Python's list of built-in functions and use things like len(lowestgradelisty) and loops like for i in range(0, numberofstudents): instead to keep your place as you execute.
I've kind of run into a brick wall with one of my latest assignments where I have to calculate the class average from a text file that is created after a certain amount of inputs from a user.
Code:
f=open('class.txt','w')
title=['name','english','math','science']
f.write(str(title)+""+"\n")
name=input("enter student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
s=int(input("enter science score:"))
o=input("do you wish to continue?: y/n:")
f.write(name + " " +str(m)+ " "+str(e)+" "+str(s)+" "+"\n")
name =[]
while o !='n':
name=input("enter a student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
s=int(input("enter science score:"))
o=input("do you wish to continue?: y/n:")
f.write(name + " " +str(m)+ " "+str(e)+" "+str(s)+" "+"\n")
f.close()
Basically, the text file needs a header, hence the line with "title" in it, and after the user hits 'n' the text file gets saved.
Now I'm having trouble figuring out how to write the code that reads the text file, calculates the total score of each, calculates the average score of each student and then prints it all into three columns. If I could get any pointers as to how I should go about doing this it would be much appreciated! Thanks!
(I am not a phython programmer so the syntax may not be exactly right)
I am assuming that you are to write the code that produces the text file and calculates the average at the same time. If so then no need write file then re-read it, just keep running total and calculate average when you're done.
numberOfStudents = 0
int totalMathScore = 0
# Only showing math score add lines to do same with english / science
# see below about how loop should be structured
while continue != 'n':
numberOfStudents += 1
m=int(input("enter math score:"))
totalMathScore += m
# Now calculate average math score
averageMathScore = totalMathScore / numberOfStudents
Look for bits of repeated code and refactor. e.g. where you're getting the scores both outside and inside the loop. Thats poor style and should be either
a) Put that in a function
b) Or more likely for this simple example change loop to something like
continue = 'y'
while (continue != 'n'):
name=input("enter a student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
...
Other bonuses
Use descriptive variable names - e.g. mathScore rather than m
Error handling - what happens if someone types in "BANANA" for a score?