How to format how data inputted using python input() function appears - python

I'm trying to use an input function in python and want to format how the input actually displays in python.
The code is currently:
price = float(input("Enter value: "))
and prints out the following if I input 9.0 (note that python does this automatically without using a print statement).
Enter value: 9.0
How do I format the output so that it only shows the value with 0 decimal points i.e., should print out
Enter value: 9
Using a print() statement and {:,g} is not an option in this exercise.

You can modify your code as:
price = float(input("Enter value: "))
price = int(price)
print(price)
This will convert float into an integer.

Related

python gives me unexpected variable [duplicate]

This question already has answers here:
How to check if input is float or int?
(4 answers)
Determine the type of an object? [duplicate]
(15 answers)
Closed 2 years ago.
def check(checked):
checked = {}
if checked == float:
return format(checked, '.2f')
else:
checked = "not a float"
return checked
# convert to float and check
a = input('Enter price for item 1 : ')
a = check(a)
b = input('Enter price for item 2 : ')
c = input('Enter price for item 3 : ')
d = input('Enter price for item 4 : ')
e = input('Enter price for item 5 : ')
print(a)
whenever I use input for a and expect it to change it returns as not a float even when it has a decimal point. I am trying to get a number to a 2 decimal point limit and if it's not a float value to ignore it. I put the else statement to see what's been going wrong I tried using is instead of == but I still get the same result.
You’re reassigning the checked variable. Don’t do that.
def check(checked):
if isinstance(checked, float):
return format(checked, '.2f')
else:
return "not a float"
Not sure what you were trying to achieve with checked = {} but all it seemed to be doing was ensuring that checked was always a dictionary, never a float, and never the actual bout value.
To test if something is a float you use isinstance, not == or is
And then reassigning checked to a message which was returned “not a float” is just bad practice.
See the above for a cleaner and (hopefully) working implementation
In python whatever input you take integer,float or any other ,The Input will be of String data type.
Here is the solution of your problem , It will only work if the input is positive value and the input is either float or integer.
Code:
def check(checked):
if checked.isdigit():
return checked
else:
return format(float(checked), '.2f')
a = input('Enter price for item 1 : ')
print(check(a))
This code will return float value upto 2 decimal places if float value is entered and will leave the number as it is if its not a float value

Why did i have to convert the variables?

def main():
account_value = input("Enter your account value: ")
AV = account_value
years = input("Enter how many years you want to save: ")
IR = input("enter the interest rate per year: ")
for i in range(int(years)):
aftervalue = int(AV) + (float(IR)*int(AV))
print(aftervalue)
Why did i have to convert them in the expression in the loop?
Why werent they already treated as ints and a float?
In Python 3, input() returns a string. If you want to use it in arithmetic operations, you have to convert it to int or float first.
You don't need to do it in the loop, it's best to do it just once when you assign the variables.
If you ran your script in Python 2, you wouldn't need to do the conversions. Its input() function evaluates the input as a Python expression, you have to use raw_input() to get the original input as a string.

Error in a basic python code [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
so I just started Python today. Tried a basic program, but I'm getting an error "can't convert int object to str implicity"
userName = input('Please enter your name: ' )
age = input('Please enter your age: ')
factor = 2
finalAge = age + factor **ERRORS OUT ON THIS LINE**
multAge = age * factor
divAge = age / factor
print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge )
print('Your age divided by', factor, 'is', divAge )
When I do enter int(age)+factor, instead of age, it works perfectly. But the author says that python auto detects the variable type when you key it in. So in this case when I enter age=20, then age should become integer automatically correct?
Looking forward to any help!!
From the doc
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
As you can see, the input() function in python 3+ returns a string by converting whatever input you are given, much like raw_input() in python 2.x.
So, age is clearly a string.
You can't add a string with an integer, hence the error.
can't convert int object to str implicity
int(age) converts age to an integer, so it works in your case.
What you can do:
Use:
age = int(input('Please enter your age: '))
To cast your input to an integer explicitly.
Your problem is that input returns a string (since in general, input from the command line is text). You can cast this to an int to remove the error, as you have done.
Python only automatically detects the type of your variables in your program if they don't already have a type - it does not automatically convert typed variables to different types.
Python does not know what operation you're trying to make, provided the '+' operator can be used both to concatenate strings and adding numbers.
So, it can't know if you're trying to do
finalAge = int(age) + factor #finalAge is an integer
or
finalAge = age + str(factor) #finalAge is a string
You need to explicitly convert your variables so it won't be ambiguous.
In your case, int(age) returns an integer, which is the proper way to get what you want.

Math with direct input

I just started my first day at uni and there is one of the exercises I am already struggling with. This is the problem: Make code that inputs two given mumbers and output one minus the other
I did this:
number1 = int(raw_input("Type your first number: "))
number2 = int(raw_input("Type your second number: "))
result = number1 - number2
print result
But it was wrong because the input is direct so when the program tested my code it said:
I have always done code that first asks for the information so I have no idea if this is even possible in python or how you do it. Any suggestions are appreciated, thanks.
you need to use :
number1, number2 = map(int, raw_input().split())
result = number1 - number2
print result
In the sample input both the numbers are separated by space, and there is no prompt for the user such as "Type your first number: ", So all yo need to do is take input using raw_input(), then splitting the input on " "(space) by using .split() and then converting each string after splitting to int using the map function.

how to print decimal values in python

print("enter start() to start the program")
def start():
print("This script converts GBP into any currency based on the exchange rate...")
print(" ") #enters a line
exchangeRate = int(input("Enter the exchange rate (Eg: 0.80)"))
print("how much would you like to convert???")
gpb = int(input())
print(gpb*exchangeRate)
If I put the exchange-rate at 0.81 and I enter £1 it always returns 0.
Use float() instead of int() with your input() call. I.e.,
gpb = float(input())
otherwise if the user enters 0.81, int() will truncate this to 0 during the conversion.
By using float() you'll keep the decimal value supplied as input and your computation should yield the result you expect.
You specified type as int.....those are whole numbers (0,1,2,3,4,5,6,7,8....) when you multiply 1 by 0.81 you get 0.81.....key number for integers is the one before dot,in this case zero.So like previous answer shortly said just change type of variable.

Categories

Resources