I am trying to write a program to do some simple power usage and cost calculations, the logic is correct and the algorithm works for VB but I want to use Python. Being new to Python I am a little confused as to what I am missing, the code is below. I have used some conventions here to help me understand what is happening
IntWatts = input ("What is the Watt rating? ")
IntHoursOfUse = input ("How many hours is the device on for? ")
IntTariff = input ("What is the Tariff in cents? ")
IntEnergyRating = int(IntWatts)/1000
IntUsageKWH = int(IntEnergyRating) * IntHoursOfUse
IntCostInCents = IntUsageKWH * int(IntTariff)
IntCostInDollars = float(IntCostInCents) / 100
print('the Cent cost is :',IntCostInCents)
print("the Dollar cost is ;", IntCostInDollars)enter code here
I have been using the inputs of
Watts 240
HoursOfUse 5
Tariff 34.1
Thanks
As to why the error is happening, it is simply a matter of typecasting the wrong variable, note the example below.
watts = input('What is the Watt rating?')
hours_of_use = input('How many hours is the device on for?')
tariff = input('What is the Tariff in cents?')
energy_rating = int(watts) / 1000
usage_kwh = energy_rating * int(hours_of_use)
cost_in_cents = usage_kwh * int(tariff)
cost_in_dollars = cost_in_cents / 100
print('The cent cost is :', cost_in_cents)
print('The dollar cost is :', cost_in_dollars)
This code should produce the results you are looking for. As to what some of the problems are here.
A few things to note, you only need to cast the input() values here since they are coming in as strings and need to be interpreted in your program as integers.
In Python there are two forms of division / which results in expected results according to how we as humans learn math, and // which will floor your result; this is why you do not need to cast to floats.
There are many pythonic things here to take away as you learn this language, while I won't go into great depth, do note the naming conventions. Python variables are typically _ delimited, lowercase and self-documenting. Additionally it is considered fairly poor practice to label variables with type, this is an old convention that has fallen out of practice.
For additional reading on Python, check out the coding guidelines:
https://web.archive.org/web/20111010053227/http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting
you need to type-cast IntHoursOfUse to int while initializing IntUsageKWH as:
# v Type casting this to int()
IntUsageKWH = IntEnergyRating * int(IntHoursOfUse)
# ^ No need to type-cast this as you are already doing it in previous line
I needed to change the inputs to be
IntWatts = int(input ("What is the Watt rating? "))
IntHoursOfUse = int(input ("How many hours is the device on for? "))
IntTariff = float(input ("What is the Tariff in cents? "))
and then remove all other int/float commands
Thanks for the help
Related
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for i in range(len(quizes)):
grade = eval(input("Enter", quizes[i][0],"grade:"))
quizes[i].append(grade)
print(quizes[i])
Hey guys so I been working on this for the past week and can't solve this. I am trying to get my program to ask "Enter [person1] grade: " and so on and append a second element to each sublist which will be their grade and then print the contents of the entire list. Any help is appreciated
The problem is input takes 1 string as a parameter, you are passing 3 instead. So:
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
grade = eval(input(f"Enter {l[0]} grade:"))
l.append(grade)
print(l)
However, I respectfully don't understand the point of using eval here. Eval turns data into code. Using eval on user input creates a great security hole. In the above code, what if the user input quizes.clear()? The whole array will be emptied. What if he inputs something eviler?
Consider (assumes valid grades only contain numbers):
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
while True:
try:
grade = float(input(f"Enter {l[0]} grade:"))
except ValueError:
print("Please input a number.")
else:
l.append(grade)
break
print(quizes)
The main problem is that input() accepts only one argument as the input prompt, unlike print which can take any number of arguments - you're giving 3 parameters to the input function - "Enter", quizes[i][0], and "grade:".
You can try concatenating them - like input("Enter "+str(quizes[i][0])+" grade:") (the str() conversion is not needed if you know that all the quizes[i][0] will be strings already),
or even use string formatting - "Enter {} grade".format(quizes[i][0]) or f"Enter {quizes[i][0]} grade:"
This should be enough, but there are 2 more changes you can make to your code if you like -
Iterate over the nested lists directly (for sub_list in quizes:)
Using int() or float() to convert a returned input string containing a number will also work in place of eval
For example
for quiz in quizes:
grade = eval(input("Enter {} grade:".format(quiz[0])))
quiz.append(grade)
print(quiz)
EDIT: Python docs on string formatting The f"..." syntax works only for Python 3.6+
You need to change:
grade = eval(input("Enter", quizes[i][0],"grade:"))
to
grade = eval(input("Enter " + quizes[i][0] + " grade:"))
input does not behave as print does. You can't use commas to join text in any other function (except for a very small number of custom functions and modules), and you should stay away from them at if that's confusing for you to only use them sometimes.
With that change, does your code work now? You didn't tell us why it wasn't working the way you expected.
Now that I'm looking at it, what did yours do wrong?
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for quiz in quizes:
grade = eval(input("Enter " + quiz[0] + " grade:"))
quiz.append(grade)
print(quiz)
print(quizes)
Trying to create a financial calculation program. I know I have to use loop but how do I loop continuously when the user input float value? I believe I'm wayyyyy off but I am quiet curious how this program can be written for myself so I can utilize this.
I would like something like if I input 10000 then ask for another input for expense... This would give me remaining till I stop input. So it would look something like this
10000 #income
3400 # expense
6600 # remaining
600 #transportation
6000 #remaining
100 #utility expense
5900 #remaining
Do I have the concept right?
def financial_plan ():
c = input ("How much income do you have? ")
income = ()
y = input ("expense?")
expense = ()
z = (income - expense)
for income1 in z:
income1 -= y
print(income1)
This seems like a homework, but still you are a bit on right track so I am answering it for you. Note that you need to convert the input to float, other way around doesn't works.
Few points to clarify your doubts:
If you don't know how many times the loop will run, use while loop.
Use the input function to take input, and apply the float on it to get float value of it.
Put the code inside the function it is supposed to be in if you want it work.
Call the function at the end of the program cause Python is not like C like languages with main function which is called by default.
It is a python code.
def financial_plan ():
income = float(input("How much income do you have? "))
while True:
expense = float(input("Expense: "))
if (income >= expense):
income = income - expense
print("You have remainder balance: " + str(income))
else:
print("Insufficient account balance!!")
continue
if (income == 0):
print("Balance Nil!")
print("Program Ended!")
financial_plan()
Please mind I am very new to the Python world.
I've been looking for an answer to this online and can't seem to find the right solution, based on my understanding I feel the logic is correct. In the end, though my results are just not there.
I am compiling with Idle.
Point of the solution: Is to take a string value of Kilometers from the console. Then convert it to Miles, then output the string.
Seems simple but debugging the below code over and over again I cannot seem to figure out why after I enter my kilometer number the print with the conversion value never displays.
def main(distanceMile=None):
# Declare and initialize variables
# string called distancekilo
distanceKilo = ""
# distancemile = ""
# conversion = 0.6214
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
I would simply like to know where I am going wrong here?
Your code has three main bugs. One is the indentation at the end of calcConvert (return should be indented). Another is that the main definition at the top doesn't seem to do anything. Another is that you want to save calcConvert(distanceKilo) to a variable. This code works:
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
distanceMile = calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
If you're new to Python, I would suggest also reading some posts and articles about the way people normally style code (like calc_convert vs calcConvert) in Python :) It's not entirely necessary, but it makes it easier for other Python users to read your code.
I am in an intro to programming class and we're making a calculator to figure out how many times a human heart has beaten given the number of years someone has been alive, and I keep getting unexpected EOF while parsing on the last line of code, can someone help me figure out why?
input("What is your name? ")
age= float(input("How old are you? "))
print("The average human heart beats 70 times a minute.")
beats_per_hour = 70 * 60
beats_per_day = beats_per_hour * 24
beats_per_year = beats_per_day * 365
beats_age = beats_per_year * age
print(format("Beats per minute: 70"))
print(format("Beats per hour:",beats_per_hour))
print(format("Beats per day:",beats_per_day))
print(format("Beats per year:",beats_per_year))
print(format("Your heart has taken",beats_age,"beats, since you were born.")enter code here
I believe that your immediate problem is that you forgot the closing parenthesis on the last line: note how you have only one R_PAREN at the end of that one, but two on all the others. Also, do you want to save the user's name in line 1?
Here's a link to help with keyboard input.
Bear with me, i'm extremely new to the world of programming. I'm trying to design a simple data entry/answer program for ICD-9 codes related to medical billing.
Example:
Enter ICD-9: "487.1"
Answer: "Influenza with respiratory manifestations"
Enter ICD-9 Code: "844.2"
Answer: "Cruciate Ligament Tear of Knee"
I sketched this out in a few minutes, but I have no idea how to get the program to read a range of numbers instead of just the one number. I'm also getting ValueErrors: invalid literal for int() with base 10: 844.2, so I used 844 just to test.
Filename: icd9wizard.py
number = 844
running = True
while running:
guess = int(input('Enter ICD-9 Code: '))
if guess == number:
print('Cruciate Ligament Tear of Knee')
elif guess < number:
print('Invalid entry')
else:
print('Invalid entry')
I know it's basic.. I just need an arrow pointing me in the right direction.
Thanks!
If you've got a predefined set of numbers that you'd like to use, you can test for inclusion in a dictionary:
good_numbers = {"487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee",
"133.7": "Being awesome at code"}
running = True
while running:
guess = raw_input('Enter ICD-9 Code: ')
if guess in good_numbers:
print good_numbers[guess]
else:
print('Invalid entry')
In Python, the int data type can hold only whole integers, with no fractional part. For your application, since you won't be doing any actual arithmetic with the entered numbers, it's probably best to keep them as a string. So don't call int at all:
number = "844"
guess = input('Enter ICD-9 Code')
Notice how I changed number so that "844" appears in quotes. This means it could contain any character values, such as "844.2" or "fred".
There is another data type called float that holds floating point values (numbers with fractional parts). However, this type is not suitable for your application because you're not going to do calculations with these numbers.
You can fix the ValueError by using float() instead of int(). An int is incapable of storing non-integers, i.e. numbers with values after the decimal point.
As for the rest of your question, you should think about using a dictionary (see the python documentation) with the ICD-9 codes as the keys and the answer/description as the values. This way you can put in a ton of codes and descriptions without having to use a giant block of if and elif. Consider filling this dictionary by reading in a file or something.
For example (once you have filled the dictonary):
number = 844.2
running = True
while running:
guess = float(input('Enter ICD-9 Code: '))
if guess in icd_9_dict.keys():
print(icd_9_dict[guess])
else:
print('Invalid entry')
don't use input() which tries to interpret the value given by the user (and can pose some security problems). Prefer raw_input() which always return a string. Then you can compare strings instead of numbers.
A Python dictionary is also a nice structure for what you are trying to build.
You should cast it to float() instead of int(). After you convert to float, you can get the integer part with int().
s = "100.3"
f = float(s) # 100.3
i = int(f) # 100
To read a range of values, you can do something like this:
s = input("Enter some values separated by space: ")
a = [float(value) for value in s.split(" ")] # array of floats
If you want N values, you can use a loop:
for i in range(N):
s = input("Enter a value: ")
# do something with this value
Your question is not clear, please improve it if you want a better answer.
First of all, 844.2 is float, not int :)
For range of numbers - you mean like this?:
487.1 456.4 654.7
Than use split(' ') on your input. Use raw_input to always get whole line as a string, than you can do with it whatever you can do with strings.
edit as noted in other answers - if this codes has nothing to do with numbers (beside digits in them;] ) - leave them as strings.
I'm just going to put it out there that it's always better to ask for forgiveness than to ask permission. This is a python best practice, which may not be relevant to you as a beginning programmer, but it's good to get started on the right foot.
try just says "try to do the following stuff" and except says "if there was one of the following errors when you tried to do the above stuff, do this stuff instead". You can tell that KeyError is the right error to put here if you try to access your dictionary with an invalid key (try it yourself in the interactive interpreter, it will always list the exception) just like you were getting ValueError exceptions before:
good_numbers = {"487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee",
"133.7": "Being awesome at code"}
while True:
try:
guess = input('Enter ICD-9 Code: ')
print(good_numbers[guess])
break
except KeyError:
print('Invalid entry')
continue
Oh and just to mention also that break says to quit looping out of the inner-most loop and continue says to go back to the beginning of aforementioned loop.
Enter ICD-9 Code: asd
Invalid entry
Enter ICD-9 Code: 487.1
Influenza with respiratory manifestations
>>>
Now just to point you in the right direction, you might be wanting to read input from a file; in this case, you're going to want to investigate the open command. To parse the input you can probably use split or something:
med_codes = open('IDC-9-2011.txt', 'r')
code_list = med_codes.read().split()
Then you can feed your codes into your dicitonary one at a time like:
for code in code_list:
try:
print (good_numbers[guess])
except KeyError:
print ( code, 'is an invalid IDC-9 code')
I think the main advantage here is that you know that you have some finite input, so you don't have to mess around with while loops and running counters or anything.
Oh yeah and remember to close your file when done!
med_codes.close()
Create a dictionary of results indexed by the values you're looking for like:
ICDCODES = { "487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee" }
Then just compare and match:
print ICDCODES[input('Enter ICD-9 Code: ')]