entering int or float using input() - python

I need to enter different values to input(), sometimes integer sometime float. My code is
number1 = input()
number2 = input()
Formula = (number1 + 20) * (10 + number2)
I know that input() returns a string which is why I need to convert the numbers to float or int.
But how can I enter a float or integer without using number1 = int(input()) for example? because my input values are both floats and integers so I need a code that accepts both somehow.

If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?

You can always just use float:
number1 = float(input())
If you'd like to cast any of your result to integer you always can easily do this
int_res = int(res) # res was float; int_res will be an integer

You could check for the presence of a decimal point in your string to decide if you want to coerce it into a float or an int.
number = input()
if '.' in number:
number = float(number)
else:
number = int(float(number))

number1 = float (input(‘ enter first value ‘) )
number2 = float (input(‘ enter second value ‘) )
Formula = print ( (number1 + 20) * (10 + number2) )

Related

Why i am unable to use (or) operator on the code given below in python 3.7 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
try:
x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
y = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
I know I am wrong, I was just wondering why I am unable to use it. As I am not getting any errors. When I try to put float value inside the input it returns me to my second case, which is Error, Invalid Input. I am using (or) operator so that I can validate integer and float values in one place. (or) the operator should execute the code when one of the conditions is true right? But why cannot we use Or operator with an integer? The code will work if you remove int from the code.
While you can use the or operator to select the the first truthy value between to values (or the latter, if the first one is falsy), it doesn't work in this case because trying to convert into int a string which represents a float value doesn't return a falsy value, it raises an Exception, which is why you go into your except clause
A logically sound way to write your code would be
x = input("Enter Your Number first = ")
try:
num = int(x)
except:
num = float(x)
Not the best way to do it, but it works
Another example:
x = 10/0 or 3 #ZeroDivisionError
x = 0/10 or 3 # x is 3 because 0 is a falsy value
Generally, we use or case to check some conditions. For example if x<3 or x>5: This if block works of both cases. However, in your situation you are trying to get some input from user and using x = int(input("Enter Your Number first = ")) or float(input("Enter Your Number first = ")). So, when I enter a value it gets number as string and when you write int(input()) it convert it to integer and assign to x. So OR is not logically suitable for here. What will computer work it this situation? What you want to achieve? If you want take argument as float just write float(input()) because when you enter integer it can be taken as float also.
try:
x = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
y = float(input("Enter Your Number first = ")) or int(input("Enter Your Number first = "))
except:
print("Error,Invalid Input")
operators = input("Choose operations (*, -, +, /)")
if operators == "*":
print(float(x*y)) or print(int(x*y))
elif operators == "-":
print(float(x-y)) or print(int(x-y))
elif operators == "+":
print(float(x+y)) or print(int(x+y))
elif operators == "/":
print(float(x/y)) or print(int(x/y))
well, i just figured it out,

How can I use round() while forcing the digits to be as much as I firstly entered

import random
userask = float(input("enter number: "))
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + str(userask))
Let's say my input is 123.0123
I want the program to force the new value after such operation to have the same number of digits as my initial input, rounding the result.
An example: my input is 102.31, the new value should have two digits and be rounded.
I have read round() docs but could not find something useful for this. how would you do it?
You can try this:
import random
userask = input("enter number: ")
lst = userask.split('.')
digits = 0 if len(lst)==1 else len(lst[1])
userask = float(userask)
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + '{:.{}f}'.format(digits).format(userask))
You can do the following:
import random
import re
inp = input("enter number: ")
if '.' in inp:
num_digits = len(inp.split('.')[1])
else:
num_digits = 0
val = float(inp)
val = val + ((random.randrange(20)*val)/random.randint(3, 100))
if num_digits:
res = round(val, num_digits)
else:
res = int(val)
print("new value is " + str(res))
This code will work also for int's as well for float's, notice that the second if is not mandatory if you don't mind that your output will be printed as float, meaning that for an int it will have a 0 in the decimal place (13 -> 13.0)
Notice
You should always check the input entered to match the desired behaviour of your program, in this case you should probably check that the value entered has the proper "looks" of a number either float or int.
In this case you could do something like:
checker = re.compile('^[0-9]+.?[0-9]*$')
is_valid = bool(checker.match(inp))
and if is_valid isn't True then the value entered is problematic

print the double of a number

I want to print the double of a number.
If I input 5, why does this print 55:
number = input("Input number \n")
double = number * 2
print(double)
and why does this print 10, as expected:
number = int(input("Input number \n"))
double = number * 2
print(double)
In the second case you convert the input to an integer, which can be multiplied by two to get the expected result. In the first case, you multiply a string (instead of an integer) by two, which results in the string twice, hence '55'.
There is a difference between python2's input() and python3's input() function.
In python2 we had 2 functions, raw_input() for reading input as a string and input() for numeric input.
In python 3 there is no raw_input() but only one method which is input() that by default read as a string.
so if you are trying to input some number you have to typecast it.
num = int(input("Input number \n"))
if you want to evaluate a expression of numbers you can use eval
>>> a = eval(input("Input Number: "))
2+3+4
>>> a
9
Do not use eval on production though!

TypeError: can't multiply sequence by non-int of type 'float' 3.3

Ok I have edited the code to where it would hopefully work but I get the TypeError: can't multiply sequence by non-int of type 'float'.
Heres the code that I have:
uTemp = input("Enter Temperature Variable: ")
cOrF = input("Do you want C for celcius, or F for Farehnheit?: ")
if cOrF:
F = 1.8 * uTemp + 32
The error is telling you that you can't multiply uTemp, a string, by a floating-point number (1.8). Which makes perfect sense, right? What is eight tenths of a string? Convert uTemp to a float:
uTemp = float(input("Enter Temperature Variable: "))
Your next problem is that cOrF is treated as a Boolean (true/false) value, which means F will be calculated if the user enters anything at that prompt since all non-empty strings are truthy in Python. So instead you would write:
if cOrF == "F":
F = 1.8 * uTemp + 32
input() returns a string in python 3.x.
Convert it to float (or to int - depends on your needs):
uTemp = float(input("Enter Temperature Variable: "))

Display number int in Python

How to display numbers integer in python ?
For example:
number1 = raw_input('Write one number: ')
number2 = raw_input('Write other number: ')
result = number1 + number2
print "The sum of the numbers is: %d" % result # here, display the result of the operatio n.
You want
result = int(number1) + int(number2)
raw_input returns strings.
raw_input returns strings. If you mean for them to be integers, then use int(x) to convert them to ints.
You have to convert the inputted strings into numbers:
result = int(number1) + int(number2)
Like this;
In [1]: numstr="5"
In [2]: int(numstr)
Out[2]: 5
So in your code result = int(number1) + int(number2)
You'd want to do some input sanitation check though. Users have a bad habit of making mistakes.

Categories

Resources