python gives me unexpected variable [duplicate] - python

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

Related

Function to detect integers instead string in Python [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
How can I check if string input is a number?
(30 answers)
Closed 1 year ago.
I'm trying to make a function that count the numbers of characters in a string and detect when an integer is typed, the condition is use "if" function. I'd expect that if I type any integer like"4464468" instead a string, the program displayed: "Sorry, you typed an integer". But, instead, counts the total number and displayed "The word you type has 7 characters".
My code is next:
def string_lenght(mystring):
return len(mystring)`
#Main Program
mystring = (input("Type a word: "))
if type(mystring) == int or type(mystring) == float:
print("Sorry, you typed an integer")
else:
print("The word you typed has",string_lenght(mystring), "characters")
I'm Newbie at Python. I really appreciate your help and patience.
Best regards.
input() always returns a string so you can try to convert it into int/float, if the operation is successful then it's a number, else it is a string:
try:
float(mystring)
print("Sorry you typed an integer")
except ValueError:
# Rest of the code ...

Problem with checking if input is integer (very beginner) [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm just starting to learn Python (it's my first language). I'm trying to make a simple program that checks if the number the user inputs is an integer.
My code is:
number = input('Insert number: ')
if isinstance(number, int):
print('INT')
else:
print('NOT')
I have no idea why, but every number gets it to print 'NOT'. If I just make a statement 'number = 1' in the code, it prints 'INT', but if I input '1' in the console when the program asks for input, it prints 'NOT' no matter what. Why is that?
(I'm using Python 3.8 with PyCharm)
When you input something, the type is always a str. If you try:
number = input('Insert number: ')
if isinstance(number, str):
print('INT')
else:
print('NOT')
you will always get:
INT
If all you want is to detect whether the input is an integer, you can use str.isdigit():
number = input('Insert number: ')
if number.isdigit():
print('INT')
else:
print('NOT')

Errors when converting input() function into an integer [duplicate]

This question already has an answer here:
Python - How to break while loop after empty value in a int turning input? [duplicate]
(1 answer)
Closed 2 years ago.
I have been trying to simply turn an input() function into an integer as the title of this question suggests. I am essentially trying to run a program that takes in as many inputs as the user inputs, but when an empty string is inputted, it breaks out of a loop and returns the average of all inputted numbers. Currently, my code looks like this:
count = 0
sum = 0.0
number = 1.0
while number != 0:
number = int(input(""))
sum = sum + number
count += 1
if number == 0:
continue
if number == "":
break
else:
print("Average is {}".format(sum / (count-1)))
The issue i face is the error:
ValueError: invalid literal for int() with base 10: ''
Does anyone have a simple solution for this? I feel like i'm overlooking something rather simple?
if number == "":
break
In the case where you want this to happen, number got its value as int(input()). That is, the attempt to convert to int happens first. Since an empty string cannot be converted to int, this test is not reached before the exception is thrown.
You should test for the exception anyway, using try:/except:. But if you want to compare a string to a string, you need to do it at the point where you still have the strings you want to do the comparison with.

Semantic Error using Conditionals statements [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 4 years ago.
I'm trying to build a code which executes the length of a string
This code should be able to accept only Strings and return their length but when integer or float values are given, it counts their length too.
def length(string):
if type(string)== int:
return "Not Available"
elif type(string) == float:
return "Not Allowed"
else:
return len(string)
string=input("Enter a string: ")
print(length(string))
Output:
Enter a string: 45
2
You expect to get output 'Not Available' for the input 45. But it won't happen because,
while reading input from keyboard default type is string. Hence, the input 45 is of type str. Therefore your code gives output 2.
input returns a string so if you check its type it will always be string. To check if its an int or a float you have to try to cast it.
try:
int(input)
except ValueError:
# not an int
return "Not Available"
try:
float(input)
except ValueError:
# not a float
return "Not Allowed"
return len(string)

How can I convert and integer into a string? [duplicate]

This question already has answers here:
How to print list item + integer/string using logging in Python
(2 answers)
Closed 7 years ago.
I am coding in Python, and have reached an error that I cannot seem to solve. Here's the part of the code that it affects.
import random
a = raw_input("Enter text")
b = random.randrange(1,101)
print (a+b)
When I try to run the code, I get the error "TypeError: cannot concatenate 'str' and 'int' objects"
I want to know how to print the result of a+b.
To answer to the question in the title, you can convert an integer into a string with str. But the print function already applies str to its argument, in order to be able to print it.
Here, your problem comes from the fact that a is a string while b is an integer. The + operator works on two strings, or two ints, but not a combination of this two types. If you have two strings, the + will mean concatenate. If you have two ints, the + will mean add. It then depends on the result you want to get.
You can convert a string to an integer by using int.
Try this code:
import random
a = int (raw_input ("Enter int "))
b = random.randrange (1, 101)
print a + b

Categories

Resources