This question already has answers here:
Assigning variables from inputs in FOR loop in python
(2 answers)
Closed 9 years ago.
I'm doing a Python programming course and I've been trying to wrap my head around how I can make it happen. I've written some code and I'm trying to fix any errors that pop up but I'm getting confused and not solving anything which is why I turn to you guys. I would appreciate any ideas and suggestions that pop up when you see what I've managed to write so far. I'm especially having trouble figuring out how to do the last part where I have to get the value that is above or below $2.
I'm doing this exercise:
Create a change-counting game that gets the user to enter the number of coins necessary to make exactly two dollars. Implement a Python program that prompts the user to enter a number of 5c coins, 10c coins, 20c coins, 50c coins, $1 coins and $2 coins. If the total value of those coins entered is equal to two dollars, then the program should congratulate the user for winning the game. Otherwise the program should display a message advising that the total was NOT exactly two dollars, and showing how much the value was above or below two dollars.
Update: I made a few changes to the last function and it worked perfectly fine.
#Global Variables
v_five = float(0.05)
v_ten = float(0.10)
v_twenty = float(0.20)
v_fifty = float(0.50)
v_one_dollar = int(1)
v_two_dollar = int(2)
dollar = 0
def main():
"""The main function defines the variables that are needed by taking input
from the user. The main() function is calling all the other functions one
by one to execute their intended commands and give the results"""
intro() #Displays the rules of the game
#Takes input from the user. One input per denomination
five=float(input(" Enter number of FIVE CENT coins: "))
ten=float(input(" Enter number of TEN CENT coins: "))
twenty=float(input(" Enter number of TWNETY CENT coins: "))
fifty=float(input(" Enter the number of FIFTY CENT coins: "))
one_dollar=int(input(" Enter the number of ONE DOLLAR coins: "))
two_dollar=int(input(" Enter the number of TWO DOLLAR coins: "))
#Shows what the user entered
show_change(five,ten,twenty,fifty,one_dollar,two_dollar)
#Converts the value of the total into dollars and cents from
#what the user has entered
calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar)
#Calculates and Prints the total along with what the final number
#was
#CalculateAndPrint(five,ten,twenty,fifty,one_dollar,two_dollar)
CalculateAndPrint(dollar)
def intro():
"""This function simply prints out the instructions for the user"""
print("")
print(" Welcome to the Coin Change game!")
print(" Enter a number for each denomination below")
print(" Your total should be $2 and no more.")
print(" Good Luck!\n")
def show_change(five,ten,twenty,fifty,one_dollar,two_dollar):
"""This function shows what the user has entered after taking input from
the user"""
print("")
print(" You entered: \n\n {} five cent(s) \n {} ten cent(s) \n {} twenty cent(s) \n {} fifty cent(s) \n {} one dollar \n {} two dollar coins".format(five,ten,twenty,fifty,one_dollar,two_dollar))
def calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar):
"""This function will convert the entered values into cents so that they
can be calculated and checked if they exceed the $2 amount."""
fiveAmount = v_five * five
tenAmount = v_ten * ten
twentyAmount = v_twenty * twenty
fiftyAmount = v_fifty * fifty
oneAmount = v_one_dollar * one_dollar
twoAmount = v_two_dollar * two_dollar
global dollar
dollar = fiveAmount + tenAmount + twentyAmount + fiftyAmount + oneAmount + twoAmount
"""This function checks whether the total was over or under $2 and displays a
win or loose message for the user. Also shows the total that the user entered"""
def CalculateAndPrint(dollar):
if dollar == 2.00:#Checks if the dollar value being passed from the previous function
#is 2 or not
print(" \n Congratulations! You've hit a perfect 2!")
print("")
else:
if dollar < 2.00:
print(" \n Oops! You were a little under 2!")
print("")
print(" Your total was: ", dollar)
else:
if dollar > 2.00:
print(" \n Oh no! You went over 2!")
print("")
print(" Your total was: ",dollar)
main()
well, actually there're a couple of errors:
the function calculate_value does return a value but it's not assigned at all
return_dollar = calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar)
and you have to pass that value to CalculateAndPrint.
CalculateAndPrint(return_dollar)
you have also to change the definition of CalculateAndPrint:
def CalculateAndPrint(dollar):
i don't have python 3.0 installed on this PC so i cannot test all your program, but those are two problem i can see right now.
Just as a matter of style, why don't you put all your coins in a list:
coin_list = [five, ten, twenty, fifty, one_dollar, two_dollar]
show_change(coin_list)
calculate_value(coin_list)
CalculateAndPrint(coin_list)
Note: you'll need to change the def's of the above functions.
Related
Assignment description, code below.
Im having and issue with printing the result of my code, no matter what I have tried im not back to get it to print my overspending or underspending
budget = float(input('Enter the allocated budget for this month: '))
expenses = 0
check = 0
while check >= 0:
check = float(input('Enter a cost (<0 stops the loop): '))
if check != -1:
expenses += check
balance = budget - expenses
if balance < 0:
print ("Your expenses are within budget by $")
else:
print ("Your expenses are over budget by $")
As Myousefi said, you are not passing the variable balance to the print command (I'm considering you refer Overspending or underspending to that variable)
You can print string texts using "" or variables of different kind (int, float, strings itselfs), or both. However, you have to separate them with commas (,). Take a look on this:
a="world"
print("Hello",a,"!")
You will get this
>>>Hello world !
Just a reminder that each comma adds a blank space.
So, for your problem, you just have to add the variable balance on the print instruction, like this
#Your instruction
print ("Your expenses are within budget by $")
#The solution
print ("Your expenses are within budget by $",balance)
However, you will get something like this
>>Your expenses are within budget by $ -15.0
I guess you want the number before the dollar sign, so you will have to put that at the end, as i did with the ! sign on the example
#Previous sentence
print ("Your expenses are within budget by $", balance)
#With $ sign at the end
print ("Your expenses are within budget by", balance,"$")
I'm writing a small game in python in which certain events happen and effect variables which need to stay in certain parameters. I have the main file and then another file which has all of the events in them. Some of the values are changed in the function then supposed to change the overall values in main (Sorry if that doesnt make sense)
Here's the part in main:
while (army > -100 and army < 100 and people > -100 and people < 100 and church > -100 and church < 100 and affairs > -100 and money < 100 and money > -100):
os.system('clear')
#Top Bar. Should Stay throughout game.
print("[-]==[King: " + king + "]==[Years in power:" + str(years) +"]==[Army: " + str(army) + "]==[People: " + str(people) + "]==[Church: " + str(church) + "]==[Foreign Affairs: " + str(affairs) + "]==[Economy: " + str(money) +"]==[-]")
print(people)
event1(army, people, church, affairs, money, years)
That loops until one of the parameters falls below 0 then there's losing conditions
Right now there is only one event, and it's not quite finished, but I only need one thing to at least see a change in the values.
Here that:
def event1(army, people, church, affairs, money, years):
#Feilds are Flooding
print("")
print("Sire! The Feilds in the eastern baronies are flooding! What should we do?")
print("")
print("Choices:")
print("1: The rain will pass, do nothing. (~Money, People)")
print("2: Have the Royal Builders build flood protection! (~Money, People)")
print("")
c=input("Your choice sire: ")
while True:
if c > 2:
print("")
print("Please chose a valid option")
print("Your choice sire: ")
continue
if c == 1:
time.sleep(2)
print("")
print("You do nothing, your people starve from flooded feilds (-People, +Money)")
money = money+20
people = people-20
years = years+1
raw_input("Press Enter to go to the next year")
return money
return years
return people
break
After it runs the event the values people, money and years are all supposed to change, but when it loops, nothing changes.
Any help is appreciated! Thank you!
Those are local variables. As soon as you leave the method scope, the value is lost, unless you return and actually use the returned values.
In your caller, assign your variables with the new returned values:
money, years, people = event1(army, people, church, affairs, money, years)
and in event1, perform only one return (others are unreachable) of the tuple containing the 3 values you want to return (which is unpacked to the 3 upper level eponymous variables):
return money, years, people
YOU DO NOT NEED THE RETURN!!!!!!!!!!!!!!!!!!!! COMPLETELY REMOVE IT! READ THIS! (should help)
The return in fact ruins your command, and there is a really easily explainable way to understand how it works.
First I need to explain something, because I am kind of confused about your code. Return is used to make the value of your command whatever you have returned. Return is used like this:
def AddThreethousandTwohundredSeventyNineToNum(num):
num = num + 3279
return num
and then
print AddThreethousandTwohundredSeventyNineToNum(4)
It should print "3283". (3279 + 4)
print printThreethousandTwohundredSeventyNineToNum(2)
It will print "3281".
You can also do cool things like:
if AddThreethousandTwohundredSeventyNineToNum(x) == y:
DoSomething
All return does is make the value OF THE FUNCTION whatever you want it to be. In the last code, the function looks for what I made num, and sees that it is 4 or 2, so it does num = num + 3279, so num gets increased by 3279 (3273 or 3271). When you do return num, it makes THE FUNCTION equal num.
That means what you have done is changed all those beatiful values in lines 21-23 (money, people, etc.) and technically that is all you had to do. However, when you returned the numbers, you made your command not only change those values, but also become a number, and obviously you cant just have a number lying around in your command. Or else the interpreter will not understand.
I hope I was clear enough, and if not, please please PLEASE tell me (please).
So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work correctly.
I've tried something like:
hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.
An optimized version of #JamesRusso code :
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = int(input("Enter the watts of appliance, or total watts of appliances"))
hours = int(input("Enter the number of hours that appliance(s) run per day"))
# Check that the hours number is good before getting to the cost
while (hours > 24) or (hours < 0):
print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
hours = int(input("Enter the number of hours that appliance(s) run per day "))
cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
# We don't need an auxiliary variable x here
total = (watts * hours / 1000.0 * 30) * cost
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
if __name__ == '__main__':
playagain = 'yes'
while playagain == 'yes':
main()
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
# Checking that the user's input is whether yes or no
while playagain not in ['yes', 'no']:
print "It's a yes/no question god damn it"
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
I put your error message in an if statment, and the calculation code in an else. This way it won't do the calculation when the hour isn't correct and instead will exit main and go back to the while loop and ask the user if they will like to play again. Also as other user's have pointed out following what I did below you should add more error testing and messages for negative numbers, etc.
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
My python skills are a little rusty, but when I have to do stuff like checking input, I usually use a structure something like this:
hours = 0
while True:
hours = input("How many hours per day? ")
#first make sure they entered an integer
try:
tmp = int(hours) #this operaion throws a ValueError if a non-integer was entered
except ValueError:
print("Please enter an integer")
continue
#2 checks to make sure the integer is in the right range
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
continue
if hours < 1:
print("Enter a positive integer")
continue
#everything is good, bail out of the loop
break
Basically, it starts by going into an 'infinite' loop. It gets the input, goes through all the checks to see if it is valid, and hits the break (leaving the loop) if everything went okay. If the data was bad in any way, it informs the user and restarts the loop with the continue. hours = 0 is declared outside the loop so it is still accessible in the scope outside, so it can be used elsewhere.
Edit: adding an idea to the example code that I thought of after seeing #Ohad Eytan's answer
The input you get from the user is a string type, but you compare it to int type. That's an error. You should cast the string to int first:
hours = int(input("How many hours per day? "))
# ----^---
Then you can do something like:
while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
If you don't sure the user will input a number you should use a try/catch statemant.
Except from this you should validate you indent the code correctly
I am a novice python code writer and i am starting small with a fuel conversion program. The program asks for your name and then converts a miles per gallon rate or a kilometers per litre rate. Currently, the program runs fine until it gets to the convert to MPG line. then once you press y, it does nothing. funny thing is, no syntax error has been returned. please help as i cannot find anything on it :(
import time
y = 'y', 'yes', 'yep', 'yea', 'ye'
n = 'n', 'no', 'nup', 'nay'
name = str(input("Hey, User, whats your name? "))
time.sleep(1.5)
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
time.sleep(1.5)
str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if y is True:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = (galls/miles)
print("The MPG Rate is: ", int(mpgc))
time.sleep(2)
print("test print")
if y is (not True):
input(str("Would you like to convert KPL instead? (y/n): "))
time.sleep(1.5)
if y is True:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = ( litres / kilometers )
print("The KPL Rate is: ", int(kplc))
time.sleep(3)
exit()
if y is not True:
print("No worries")
time.sleep(1.5)
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
time.sleep(1.5)
print("Have a good day!")
time.sleep(1.5)
exit()
else :
print("Sorry, invalid response. Try again")
exit()
elif not y:
print("Please use y/n to answer" )
time.sleep(2)
elif not n:
print("Please use y/n to answer" )
time.sleep(2)
sorry if you think that is bad but i just started python and i need some help :)
Severely trimmed down and indentation fixed (I think....)
if y is True and similarly if y is not True make no sense here.
Also, speaking of is.. is and == may be work as equivalent expressions sometimes for checking for "equality", but not necessarily. == checks for equality whereas is checks for object identity. You should use == for checking for equality between two objects. Except for None in which case it's generally preferred to use is instead of == for this.
You're converting to str in a bunch of places unnecessarily. They're already strings.
In your mpg conversion you already have a floating point number (possibly an int). There's no need to convert to an int here. Suppose mpg is < 1. Then int casting will make this return zero
Your math is also backwards. miles per gallon. Similarly, kilometers per gallon.
name = input("Hey, User, whats your name? ")
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
mpg = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if mpg in y:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = miles / galls
print("The MPG Rate is: ", mpgc)
else:
kpl = input("Would you like to convert KPL instead? (y/n): ")
if kpl in y:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = kilometers / litres
print("The KPL Rate is: ", kplc)
else:
print("No worries")
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
print("Have a good day!")
The is keyword in python checks if two variables point to the same location in memory. y will never point to the same memory location as the singleton True because it's value is a string. I suspect what you mean to do is something like
inp = str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if inp in y:
...
You cannot directly take y as pressed from the keyboard, you have to take it as an input(Pressing enter would be required), store it, check if it satisfies the conditions, then apply the logic.
I see you tried to define y and n as a tuple (deliberately or not), In that case I assume you also want to take those other words as yes or or too.
In that case you can apply this logic;
inp = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if inp in y: # Check if inp corresponds any of the words defined in y
# Things to do if `yes` or anything similar entered.
Some notes:
You don't need to use str() after you take input if you are using
Python3 (Which seems you are). Because input() returns string.
In somewhere you did something like this:
input(str("Would you like to convert KPL instead? (y/n): "))
Which is even more reduntant because the value you entered is already
a string.
You also didn't assign some inputs to any variable throughout the
code. You should assign them If you are to use them later.
Please take care of these issues.
I have written most of the codes already, but I am still having a hard time figuring out the code to loop the program (for a function) as many times the user desires until the user is done. Also, I am unable to use a For loop.
def load():
a=input("Name of the stock: ")
b=int(input("Number of shares Joe bought: "))
c=float(input("Stock purchase price: $"))
d=float(input("Stock selling price: $"))
e=float(input("Broker commission: "))
return a,b,c,d,e
def calc(b,c,d,e):
w=b*c
x=c*(e/100)
y=b*d
z=d*(e/100)
pl=(x+z)-(y-z)
return w,x,y,z,pl
def output(a,w,x,y,z,pl):
print("The Name of the Stock: ",a)
print("The amount of money Joe paid for the stock: $",format(w,'.2f'))
print("The amount of commission Joe paid his broker when he bought the stock: $",format(x,'.2f'))
print("The amount that Jim sold the stock for: $",format(y,'.2f'))
print("The amount of commission Joe paid his broker when he sold the stock: $",format(z,'.2f'))
print("The amount of money made or lost: $",format(pl,'.2f'))
def main():
a,b,c,d,e=load()
w,x,y,z,pl=calc(b,c,d,e)
output(a,w,x,y,z,pl)
main()
To let the user decide if they want to keep looping and not any fixed number of times, ask the user:
# in place of the call to main() above, put:
while input('Proceed? ') == 'y':
main()
So it keeps looping over main() as long as the user enters 'y'. You can change it to 'yes', 'Yes', etc. as needed.
Side note:
1. You should use more than 1 space for indent. Typically 4 spaces, or at least 2.
2. read up on if __name__ == "__main__".
Calling a function in a loop is fairly simple, you wrap in either in a while or a for loop and call it inside. The below code executes the brookerage function 10 times. I suppose you can use this as an example and customize the entire thing for your needs.
def brookerage():
a,b,c,d,e=load()
w,x,y,z,pl=calc(b,c,d,e)
output(a,w,x,y,z,pl)
def main():
for i in range(0,10):
brookerage()
main()