Function to detect integers instead string in Python [duplicate] - python

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 ...

Related

Why isn't my 'Else' expression showing in this scenario when i try to run my code? [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
What's the canonical way to check for type in Python?
(15 answers)
How can I read inputs as numbers?
(10 answers)
Closed last year.
I am a beginner when it comes to coding. I am trying to run a program on python that takes in kilometers(user input) and returns it in miles(output). I know how to do the task but I wanted to challenge myself by using if statements to check if the user has entered a number:
Kilometers = input("Please insert number of Kilometers: ")
if type(Kilometers) == int or float:
print("This is equivalent to", float(Kilometers)/1.609344, "Mile(s)")
else:
print("This is not a number")
I understand that whatever the user inputs will be saved as a string. However, whenever I run the code, the program always tries to convert the input into miles.
I have specified in the if statement that the type has to equal a float or an int, so shouldn't the output always be "This is not a number" until I change the first line to:
Kilometers = float(input("Please insert number of Kilometers: "))
or
Kilometers = int(input("Please insert number of Kilometers: "))
When programming if statements in Python, each condition must be fully rewritten. For example, you would write if type(Kilometers) == int or type(Kilometers) == float rather than if type(Kilometers) == int or float. Another important thing in your code is that if someone inputs 5.5, you would expect a float value, but Python interprets that to be a string. In order to circumvent this, you can use a try/except clause like this:
Kilometers = input("Please insert number of Kilometers: ")
try:
Kilometers = float(Kilometers)
print("This is equivalent to", Kilometers/1.609344, "Mile(s)")
except ValueError:
print("This is not a number")
What this is doing is trying to set Kilometers as a float type, and if the user inputs a string that cannot be interpreted as a float, it will cause a ValueError, and then the code inside except will run. You can find more on try/except clauses here: Python Try Except - W3Schools
One more thing I noticed is that you should name your variables according to the standard naming conventions, so Kilometers should be kilometers. You can find more on the naming conventions here: PEP 8

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.

Is there something wrong with this line of code? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I want to take from the user an input integer, and turning to a string in my code.
My line of code for that is:
num1 = input(int(str("Enter a number: ")))
But the console says: ValueError: invalid literal for int() with base 10: 'Enter a number: '
If this line isn't correct can you show me a way how can I turn an integer that is given by the user to a string in my code?
You have the functions in the wrong order: First you need to turn the input into a Python object, so input() has to be the innermost function (to be applied first). Also, input() will cast the input as a string by default, so you don't need str().
So the line should read:
num1 = input("Enter a number: ")

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)

Categories

Resources