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: ')]
Related
I'm an absolute beginner - like I'm Today-years-old with this.
So I'm mucking about with a silly little piece of code to try and help me understand If statements:
print ('How many sausages have you eaten today?')
userInput = ('>5' or '<5')
if userInput input == int ('> 5'):
print ('Whoa! Slow down Fatty!')
elif userInput input == ('< 5'):
print ('Ok, but better call it a day now')
I'm trying to alter the printed message based on how many sausages the user inputs - e.g. above 5 or below 5.
I know that I'm doing something (probably many things) wrong.
Can anyone help to tidy this up?
Here is a fixed version:
There is some notes to help you understand
# To get an input you need to use input()
userInput = input('How many sausages have you eaten today?')
# Turn the input from text to a number with int()
userInput = int(userInput)
if userInput > 5:
print ('Whoa! Slow down Fatty!')
elif userInput < 5:
print ('Ok, but better call it a day now')
Your code has a few problems. First, you cannot use int() to get user input. Instead, you must use input(). Second, you cannot convert inequalities into integers. Like this:
print('How many sausages have you eaten today?')
userInput = int(input())
if userInput > 5:
print('Whoa! Slow down Fatty!')
else:
print('Ok, but better call it a day now')
Notice how I get user input with input(), which will return a string. Then, I convert it to an integer with int(). If the user inputs something that is not an integer, then the program will crash because the input to int() must be able to be converted into an integer.
In the if-else statement, I check if userInput, which is an integer, is greater than 5. I also used an else statement, not an elif, because if userInput is exactly 5 then neither statement would have been true.
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)
So, I am working on a small project. I am making a text-based temperature calculator but I have run into a problem with an if statement in the program, just as the title of this question suggests.
This is the code that I am having issues with.
running = True
fahr = "fahrenheit"
cel = "celsius"
kel = "kelvin"
temperatures = [fahr, cel, kel]
while running == True:
try:
temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n"))
except ValueError:
print("I do not understand. Please try again.")
continue
if temperature_type == any(temperatures) and not all(temperatures):
break
else:
print("Please enter a valid input.")
continue
It seems that there is something wrong with the logic that I am not seeing, and I have tried multiple combinations, even ones that are suggested from this post and none of them seem to work the way I want it to. The way I want it to work is to let the variable temperature_type be equal to only one of the temperatures such as Fahrenheit and then ask another question (which is not shown here). If the variable temperature_type does not equal any of the three, then I want to loop to repeat. The issue I am having is that no matter what I input, it always asks for the temperature. If anyone has an answer I would be thrilled to know what I am doing wrong and I would also love an explanation of the logic because I am not the best with this sort of logic yet. Thanks again for any answers and/or guidance!
any and all return True or False, not some object that can be compared meaningfully to a str. All non-empty str are "truthy", so you're checking if temperature_type == True and not True, which of course will never pass.
You're desired logic would probably be:
if temperature_type in temperatures:
It's impossible for someone to enter multiple temperature types in your design, so you don't need any equivalent to the all test, you just want to know if the entered string matches one of the three known strings.
Here's a simpler version of the check that simply checks that the input string is one of the valid temperatures. It uses the in operator to check that the provided string is in temperatures.
running = True
fahr = "fahrenheit"
cel = "celsius"
kel = "kelvin"
temperatures = [fahr, cel, kel]
while running:
temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n"))
if temperature_type in temperatures:
break
print("Please enter a valid input.")
OR:
while 1:
if input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n").lower() in temperatures:
break
print("Please enter a valid input.")
Explanation:
all and any returns True or False so it will not work so use in
I removed running because just use 1
You can do True too, see:
>>> 1==True
True
Maybe expand to include all of the scales, and make it the user interface easier.
scales = ['F', 'R', 'C', 'K']
while True:
if input("What temperature scale are you using [F, C, K, R]? ")[0].upper() in scales: break
[0]
I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
Have your function return values, instead of simply printing. This is good practice.
Use if not a to test if your string is empty. This is a Pythonic idiom.
Convert your input string to numeric data, e.g. via int.
Catch ValueError and return an appropriate message in case the user input is invalid.
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
Receive your user inputs.
Compute the data.
Print accordingly.
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False (it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else, is if you handled your error case, then your input must be right, so you compute your data accordingly.
In your second line, it should be
if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))
Hey I would like to know if there is a way I can make sure nobody type "1004gg0" into the game and crash it? It asks for a number and the number is an integer but I always get people either accidently or on purpose writing in strings into an integer place.
Instead of checking before, let int check it for you. Just catch the conversion exception and reject the number:
def get_number_from_user(message):
while True:
user_input = raw_input(message)
try:
number = int(user_input)
break
except ValueError:
# Keep asking
pass
return number
And you would use it as:
param = get_number_from_user("Insert number here: ")
print param
If you are using Python 3, then replace raw_input with input.
Convert the string to int, and let the user know if it fails:
try:
number = int(s)
except ValueError:
# This is not an int