in range loop skipping through - python

salary=0
salaryArray=[]
loop=0
noYears=int(input("How many years do you want to do salaries for? "))
for i in range(0,noYears):
while loop==0:
print()
print("You can add multiple sources of income, one at a time")
salaryType=input("Do you want to put in your salary hourly or yearly? (h/y) ")
if salaryType=="y":
salarySection=float(input("What is your salary? "))
salary=salarySection+salary
else:
salaryHourly=float(input("What are you payed per hour? "))
salaryWeekly=float(input("How many hours per week will you work? "))
salaryYearly=float(input("How many weeks per year will you work? "))
print()
salarySection=salaryHourly*salaryWeekly*salaryYearly
salary=salary+salarySection
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
loop=1
For some reason the for i in range(0,noYears) isn't working?
It just moves on to the next line of code after doing it through once - even though I put the answer to noYears as 3.
Anyone know why this might be as I cannot see what is wrong?
:)

The code isn't working because the while loop never executes. You could solve this two ways.
Use a break statement instead of setting loop to 1:
#previous code
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
break
Reset the variable loop to 0 inside of the for loop:
for i in range(0,noYears):
loop = 0
while loop==0:
# remaining code

Related

How to link input from user to a variable with assigned value?

I am very new to Python (literally just started learning last week). My group got an assignment to code a program to compute system that calculate total price with several conditions. But we are stuck because the user input returns as string but we need it to link with the variable. And also we aren't allowed to use IF, ELSE method and everyone is new to this so we are at dead end. Please help :')
This is what we have coded in the last hour.
min_price=30
oak_type=15
pine_type=0
black=0
white=0
gold_leaf=15
print("Welcome to Mark Daniels Carpenting Service!")
import random
order_num=random.randint(1000,1999)
print("\nYour order number is", (order_num))
cust_name=input("Enter name:")
print("Type of wood available:")
print("1 oak_type \n2 pine_type")
wood_type=input("Enter choice of wood:")
And when we tried to total up the price it comes up as error because the wood_type returns as string while the other data returns as integer.
How to make input from wood_type link to oak_type or pine_type value?
wood_type=input("Enter choice of wood:")
You can use wood_type=int(input("Enter choice of wood:"))
Use integer_x = int(input("Enter... ")) for integer and float_x = float(input("Enter... ")) for float.
You can add the type of your input at the beginning of your input syntax.
So for your case, it will be :
wood_type = int(input("Enter choice of wood:"))

Issue With Infinite While Loop in Python 3.1

I am creating a travel agent game in Python 3.1. I have reached an error with my while loop. It will constantly repeat the print() response. I know this is because it is true as long as here is a response for people, but I have no clue how to fix it.
people = int(input("Will you be travelling by yourself (1), or as a group of
two (2)?: "))
while people:
if people == 1:
print("\nAh, a holiday for one! How adventurous.")
elif people == 2:
print("\nOoh, bringing a friend! Sounds like fun!")
else:
print("\nPlease enter either 1 or 2 to determine the number of
travellers.")
people = int(input("Will you be travelling by yourself (1), or as a
group of two (2)?: "))
There is no any issue with the python version regard to you question.The problem is that, loop will run infinitely because there is no condition to exit from the loop.So to exit from the loop after print statement insert break keyword as follows.
people = int(input("Will you be travelling by yourself (1), or as a group of two (2)?: "))
while people:
if people == 1:
print("\nAh, a holiday for one! How adventurous.")
break
elif people == 2:
print("\nOoh, bringing a friend! Sounds like fun!")
break
else:
print("\nPlease enter either 1 or 2 to determine the number of travellers.")
people = int(input("Will you be travelling by yourself (1), or as a group of two (2)?: "))

How to give an error msg based on user input in my program?

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'm writing a fuel conversion program and its not working :(

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.

How do you use a loop for a function?

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()

Categories