I'm completely new to python, and I wanted to create a program that "loads" a number that the user would have entered.
To do this, I made a function with an input variable,
percentage
that I then tried to transform to an interfer,
percentage_int
To then put in a while loop.
However, I get an error message, why?
def loader():
percentage = input("what percentage do you want?")
percentage_int =int(percentage)
x = 0
print("Goal:{} %".format(percentage_int))
while x < percentage_int:
x+=1
print(x)
loader()
You need to do the type conversion, that is in this case from string to integer.
If you dont do so python will consider percentage_int as the input string itself.
percentage = input("what percentage do you want?")
percentage_int = int(percentage)
Go through this tutorial which will help you learn more about type conversions with python.
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)
I am trying to make a list of weights that are being brought to a trip to outer space. The way I have tried to show how many people are coming is this:
def flcr():
try:
Value1 = int(input())
except ValueError:
print("That was an incorrect format! Try again.")
flcr()
global x
x = Value1
Then the user has to input the weights one by one. This is what I tried:
def enter():
print("How much is each flight crew member bringing on the trip? Enter one entry at a time, this will be Earth weight.")
amount1()
def amount1():
try:
if x > 0:
equation1 = [float(input())]
x - 1
amount1()
else:
print(listFlcr)
except ValueError:
print("That was an incorrect format! Try again.")
enter()
When I input the weights though, I assume x just resets itself instead of subtracting itself by 1, so my input is infinite. I want to have a code that will allow me to enter the right amount of weights, so if I say there are 2 people coming, I can only input two weights.
If someone could help me out I would greatly appreciate it!
There are a number of issues with your current implementation.
You are using recursion to repeat getting inputs, which means you have a function (flcr, amount1) that calls itself until valid inputs are provided. While this could work for user inputs, it is usually unnecessary. There are better ways to ask for user input until they give a valid response, and as mentioned in the comments, use a loop instead.
The code x-1 does not update x. It actually does nothing because the result is not stored anywhere. If you are using an IDE or a linter, it could warn you that this is a "pointless statement". What you probably wanted was x = x - 1.
You are using globals to track how many weights need to be input and how many were input so far. While this could also work, it is again unnecessary. It would be simpler to just pass the number of flight crew members as a function argument.
Here's a solution that replaces the recursive calls with while loops and gets the number of people from one function, then passes the result of that to another function for getting the weights:
def get_num_people():
while True:
try:
return int(input("How many people are coming? "))
except ValueError:
print("That was an incorrect format! Try again.")
def get_weights(num_weights):
print("How much is each flight crew member bringing on the trip?")
all_weights = []
while len(all_weights) < num_weights:
try:
all_weights.append(int(input()))
except ValueError:
print("That was an incorrect format! Try again.")
print(all_weights)
return all_weights
num_people = get_num_people()
get_weights(num_people)
Here's the sample output:
$ python test.py
How many people are coming? 2
How much is each flight crew member bringing on the trip?
12
33
[12, 33]
$ python test.py
How many people are coming? 3
How much is each flight crew member bringing on the trip?
abc
That was an incorrect format! Try again.
89
def
That was an incorrect format! Try again.
100
4
[89, 100, 4]
I know that your question was about how to update the global variable based on user inputs, ... but I think you have a global x because you were using recursive calls. A cleaner solution would be to get rid of both recursion and the global variable.
You don't need global before the comparison of x in that function.
Generally for me, I find it easier to refer to things I want global as globals()[‘x’]. That way I know nothing weird will happen. If globals() refers to global namespace, represented similar to a dictionary, globals()[‘x’] will always point to the global variable x.
If it is intended to be global, declare it globally before everything else. Outside all the functions, x = None, or x = 0, or x = ‘’.
try to replace :
Value1 = int(input())
with :
Value1 = int(str(input("")))
I keep getting the same error.
This is probably a simple mistake, I just haven't coded in a while.
#import
import math
#initailse variables
float(x1)=0.0
float(y1)=0.0
float(x2)=0.0
float(y2)=0.0
float(complete_y)=0.0
float(complete_x)=0.0
float(final_decimal)=0.0
float(heading)=0.0
#get input
print("Welcome user!")
print("please enter your coordinates in format x and y including
negatives")
x1=input()
y1=input()
print("please enter the coordinates of your target in the format x and y
including negatives, you can obtain these from the map")
x2=input()
y2=input()
print("please hold for calculation")
#calculate
y2-y1==float(complete_y)
x2-x1==float(complete_x)
y/x==float(final_decimal)
math.asin(a)==float(heading)
#output
print("fire at a heading of", heading, "not including the negative if
there is one")`enter code here`
print("press enter to close the programme")
Results in an error
expected result is a heading in degrees.
My guess is that you are tying to declare the types before assigning values such as :
float(x)=0.0
x = input()
In python, the type is only known at runtime and you cannot declare type of a variable.
If you do :
x = 0.0
x = input()
print(type(x))
You will see x is a string, because you assigned a string with the input method. If you need a float, you need to convert it.
x = float(input())
As a side note,
#calculate
y2-y1==float(complete_y)
This code is valid if y1, y2 and complete_y are declared before, it just returns a Boolean, True or False. And do not assign any values.
If you need to assign value, use a single = such as
complete_y = y2 - y1
You can't do
float(x)=0.0
You're calling a function float on a value x and trying to assign 0.0 to the result of that call, which Python doesn't understand. Python knows the type of 0.0, you don't have to specify that it's a float. Just do
x = 0.0
Also, I'm not sure what you expect your #calculate section to do, but at the moment it won't have any effect on the rest of the program in any way.
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.
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: ')]