The instructions are very simple, but I am struggling none the less. We have learned very few things in this class so far, so I am looking for a very simplistic answer.
The instructions are as follows "Write a Python program that will prompt the user to enter a weight in pounds, then
convert it to kilograms and output the result. Note, one pound is .454 kilograms"
What i have so far is
print("Pounds to Kilos. Please Enter value in pounds.")
x=input('Pounds: ')
float(x)
print(x * .454)
You are converting the variable x's value to the float, but not assigning it to anything. So, the real value which x variable holds never changed. You did not edit the x variable in fact. You can try something like this;
print("Pounds to Kilos. Please Enter value in pounds.")
x=float(input('Pounds: '))
print(x * .454)
However, using functions in that nested manner is not recommended. Instead, initialize a new variable to hold the new float-converted value;
print("Pounds to Kilos. Please Enter value in pounds.")
x = input('Pounds: ')
x_float = float(x)
print(x_float * .454)
Going from your code example I would do something like this.
print("Pounds to Kilos. Please Enter value in pounds.")
x = float(input('Pounds: '))
print(x * 0.454, "kg")
EDIT
Maybe instead of having the calculation in the print() statement I add a separate variable for it, including the advise about float from the other solution.
print("Pounds to Kilos. Please Enter value in pounds.")
x = (input('Pounds: '))
kg = float(x) * 0.454
print(kg, "kg")
Explanation: First you ask the user's weight using input command, then you can print a message saying converting to kgs.. (it's optional). create a new variable called weight_kgs to convert the user's input to a float, then multiply the input by 0.45. after that convert the weight_kgs variable to a string once again by making a new variable called final_weight, so that you can join the input by user to a string. At the end print a message telling the user's weight. print("you weight is " + final_weight)
```
weight_lbs = input("enter your weight(lbs): ")
print("converting to kgs...")
weight_kgs = float(weight_lbs) * 0.45
final_weight = str(weight_kgs)
print("your weight is " + final_weight + "kgs") # line 5
```
I hope you got it.
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 months ago.
I am a at the very beginning of learning to code in python and am following a tutorial. I attempted to convert this string into an integer to get it to simply add 5 and 6. Here is what I have
No matter what I do, I get 5+6 = 56. Here is what I have:
first_num = (input('Please enter a number '))
second_num = (input('Please enter another number '))
print int((first_num) + int(second_num))
I tried using a comma instead of a plus sign, as a few places suggested. I also tried using int in front of the input line to convert the inputs themselves from strings to integer.
I expect it to add 5 + 6 = 11. I keep getting 56.
I'm not positive what version of Python I'm using, but I know I'm using VS Code and it is Python 3.X. i just don't know what the X is. Here is a screenshot
edit: I have resolved this question. I was not saving the file before I ran it. Therefore every time I tried to change something it was just running the saved, incorrect file. Thanks to those that tried to help me.
In Python when you add two strings together you concatenate the values.
For an easier example:
string_one = "hello"
string_two = " "
string_three = "there"
final = string_one + string_two + string_3
print(final) # hello there
To add them together mathematically, you need to ensure the values are ints, floats, decimals...
one = 1
two = 2
final = one + two
print(final, type(final)) # 3 int
So for your code:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
final = first_num + second_num
print(final) # will give you the numbers added
However, you are casting to ints based on user input, so I would ensure you are also catching the errors that occur when a user enters a value that cannot be cast to an int, like hi. For example:
try:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
print(first_num + second_num) # will give you the numbers added, if ints
except ValueError as ex:
# if any input val is not an int, this will hit
print("Error, not an int", ex)
Try this
first_num = int(input('Please enter a number '))
second_num = int(input('Please enter another number '))
sum=first_num+second_num
print (sum)
def main():
handling_cost = 5
cost_per_item = 4.25
prompt = "Enter number (5 - 20): "
get_number(prompt)
int(prompt)
get_cost(prompt, cost_per_item, handling_cost)
display_details(prompt, cost_per_item)
def get_number(prompt):
return int(input(prompt))
def get_cost(number, cost_per_unit, handling_cost):
total_cost = number * cost_per_unit + handling_cost
return round(total_cost)
def display_details(items, cost_each, handling_cost, final_price):
print("Items: ", items, " Cost per item: $", cost_each, sep="")
print("Handling cost: $", handling_cost, sep="")
print("Total $", final_price, sep="")
main()
Hi there,
I'm having trouble converting a string number into an integer.
On line 6 of my code, I try to convert the prompt into an integer so it can be converted into an integer and then multiplied in the get_cost function. But I get the error message shown below:
How do I fix this?
You are passing int() your prompt instead of the user inputted value. Just get rid of int(prompt) and change line 5 to user_val = get_number(prompt)
...
user_val = get_number(prompt)
get_cost(user_val, cost_per_item, handling_cost)
display_details(user_val, cost_per_item)
I think you may've confused things a little bit (or maybe it's me that didn't get it as you) but let's make things clear:
At line 4 you have:
prompt = "Enter number (5 - 20): "
So prompt is your string that the user will read and then input the value.
At line 5 you call the function that reads the value and casts it to int:
get_number(prompt)
The problem is that you are not assigning the value that this function returns to any variable, so you are losing the read value.
At line 6 you are trying to cast prompt to int, but it is a string (it contains the string that has been assigned to it at line 4)
So what you should do to fix it is to declare a variable at line 5 and assign to it the get_number`() call, like value = get_number(prompt).
You then should have something like:
prompt = "Enter number (5 - 20): "
value = get_number(prompt)
And remember that at line 7 and 8 you are sending prompt as paremeter, but actually it should be your new value variable.
get_cost(value, cost_per_item, handling_cost)
display_details(value, cost_per_item)
I taking input from user in python, How to know user has passed int or string or float etc??
number1 = eval(sys.argv[1])
number2 = eval(sys.argv[2])
if user passed input is float or int, i want to sum them, but how to know which type of data user passed? because all data which user passes is default type is string.
Python advocates the approach of "ask forgiveness, not permission". All user input is probably going to be a string - especially if you're getting it from sys.argv - but the best way to determine this is to attempt to make them numbers (using try/except) and then revert to different behavior if that fails.
num1str, num2str = sys.argv[1], sys.argv[2]
try:
# might as well do float, because every valid integer that can be represented in a
# string is also a valid float
num1 = float(num1str)
num2 = float(num2str)
num3 = num1 + num2
except ValueError:
# this happens if the variable cannot be converted, e.g. the user entered something
# that cannot be interpreted as a float
...
There are built in methods for that:
int()
str()
for example convert, if possible, while type() tells you what it is:
x = "Hi there"
print(type(x))
y = 3
print(type(y))
y = str(y)
print(type(y))
When receiving user input, you can try converting it and if successful, work with the result of the conversion:
_in = input("Some input please ")
try:
_in = int(_in)
except:
try:
_in = float(_in)
except:
pass
print(_in)
print(type(_in))
>>Some input please 3
>>3
>><class 'int'>
>>Some input please 3.5
>>3.5
>><class 'float'>
We can use eval() for that,
import sys
def main():
number1 = eval(sys.argv[1])
number2 = eval(sys.argv[2])
print(number1 + number2)
if __name__ == '__main__':
main()
when the user enters an integer as an input the input() function returns a string, but in the case of eval() it will evaluate the returned value from a string to an integer, same in float . No need to check data type every time.
see 3rd number of below link,
https://towardsdatascience.com/python-eval-built-in-function-601f87db191
I have been trying/looking for this problem and decided to ask.
I want a simple program that gets an integer as input first of all.
a = int(input())
Then, the program will take input as much as the given number, a.
You may want to use a for loop to repeatedly get input from the user like so:
a = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(a):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)
Hello I am new to MATLAB , I wanted to know how can I make my string into function . I want to access the function as a string from user in standard Matlab format (e.g exp(-10*X)-sin(pi*X)-2*tanh(X) ) Here X is the variable. Then I want to replace 'X' with 'low' and 'high' variables to calculate value of function at these limits. I have used 'strrep' for this purpose. I am getting the following errors
1)Undefined function or variable 'X'.
2) I cannot see whether 'X' was replaced with 'low' and 'high'.
Any help will be truly appreciated.
Below is my code.
high=input('Upper Limit of the Interval : ');
low=input('\nLower Limit of the interval : ');
usr_funct=input('Enter The Function in standard Matlab Format.\nEnter "X" for the
variable and * for multiply \n'); % Example exp(-10*X)-sin(pi*X)-2*tanh(X);
middle = (low+high)/2;
Flow =strrep(usr_funct, 'X', 'low');
Fhigh =strrep(usr_funct, 'X', 'high');
sprintf('Flow '); % This was to check if 'X' was replaced with 'low'. It is not printing anything
Use:
usr_funct=input('Enter The Function...', 's');
This will return the entered text as a MATLAB string, without evaluating expressions.
I think that you are looking for the eval function. That will evaluate a string as matlab code.
Here is an example:
str = 'exp(-10*X)-sin(pi*X)-2*tanh(X)' ; % let str be your math expression
high = 10; % Ask the user
low = -5; % Ask the user
% Now we evaluate for High and Low
X = low; % We want to evaluate for low
ResultLow = eval(str); % That will return your value for X = low
X = high; % We want to evaluate for low
ResultHigh = eval(str); % That will return your value for X = high
1) Undefined function or variable 'X'
If you look at the documentation for input, it says that by default, it evaluates the expression. You need to add a second argument of 's' for it to just save a string.
2) I cannot see whether 'X' was replace with 'low' and 'high'
You should type sprintf(Flow) instead of sprintf('Flow'). The latter will just output "Flow" onto the screen while the former will output the value of Flow.
Finally, the eval function may be of use later on when you actually want to evaluate your expression.