How to fix this error in a Pythagorean theorem - python

So i have easy program that will tell me if this Pythagorean theorem a2 + b2 = c2 is true or false.
But there is one problem if I try to activate it like 2 times without typing something program will fail
Is there anything how to fix it.
a=int(input("enter a number a:"))
b=int(input("enter a number b:"),)
c=int(input("enter a number c:"),)
result= (((a**2)+(b**2)) == (c**2))
print(f"result = {result}")
here is error ValueError:
invalid literal for int() with base 10:

It sounds like you just pressed Enter without typing any numbers. If you do that then input() will return an empty string and int("") will cause the error. This is because int expects a valid numerical string passed to it.
To solve the problem, you need to disallow empty input. You can add error handling with a while loop to check the entered value and ask the user to enter a correct value.

Related

Why does false = isinstance(a, Int) when a is a integer

I’m trying to make a online calculator without any errors.
When a , b and c gets a input it is supposed to calculate the answer and print it
But when a or b is not an integer then it is supposed say “ the first input and the second input needs to be a number”
a image of the code
Although a and b were a integer/number it still responded with “the first input and the second input needs to be a number”
use isdigit() method to check whether it is a number or not
On your code:-
a = input()
if a.isdigit():
However, if you want to take the user's input as an integer directly and you expect the input to be a number, then it would be more efficient to use the int() function. This function will try to convert the input to an integer, and if it is not a number, it will raise a ValueError exception which you can catch and handle as appropriate.
try:
a = int(input("Enter a number: "))
print("The number you entered is: ", a)
except ValueError:
print("Invalid input, please enter a number.")

How to change my string with dot to int in python [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed last month.
I'm new to the whole coding thing...so here goes.
Just trying to write a simple number guess game, but also do input validation. So that only integers are accepted as input. I've figured out how to weed out alphabetic characters, so I can convert the numbers into an integer. I'm having trouble when I put in a float number. I can't get it to convert the float number over to an integer. Any help is appreciated. As I said I'm on about day 3 of this coding thing so try to be understanding of my little knowledge. Thanks in advance.
Here's the function from my main program.
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
if userGuess.isalpha() == False:
userGuess = int(userGuess)
print(type(userGuess), "at 'isalpha() == False'")
break
elif userGuess.isalpha() == True:
print("Please enter whole numbers only, no words.")
print(type(userGuess), "at 'isalpha() == True'")
return userGuess
Here's the error I'm getting if I use 4.3 (or any float) as input.
Traceback (most recent call last):
File "C:\\*******.py\line 58, in <module>
validateInput()
File "C:\\*******.py\line 28, in validateInput
userGuess = int(userGuess)
ValueError: invalid literal for int() with base 10: '4.3'
Actually int() function expects an integer string or a float, but not a float string. If a float string is given you need to convert it to float first then to int as:
int(float(userGuess))
Don't use isalpha to screen the output. EAFP -- convert it and handle that exception. Either the ValueError is exactly what you want, in that you can handle it and tell the user to correct their input. Or for some odd reason you want to silently correct their input from "4.3" to "4".
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
try:
int(userGuess)
return userGuess # you shouldn't really keep this string...
except ValueError as e:
print("Please enter whole numbers only, no words.")
First, why do you want to convert the float string to an integer? Do you want to treat 4.7 as meaning the user has guessed 4? Or 5? Or a legal but automatically-invalid guess? Or as actually the value 4.7 (in which case you don't want integers at all)? Or…?
Second, the way you're approaching this is wrong. userGuess.isalpha() only tells you that the guess is made entirely of letters. That means you're still going to treat, say, "Hello!" as a number, because it has at least one non-letter.
If you want to know if a string is a valid integer, just call int on it, and use a try/except to handle the case where it isn't:
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
try:
userGuess = int(userGuess)
print(type(userGuess), "after int succeeeded")
break
except ValueError:
print("Please enter whole numbers only, no words.")
print(type(userGuess), "after int failed")
return userGuess
If you want to handle actual words differently from other kinds of failure, e.g., so you can print a more specific error message, then you can check isalpha inside the except clause.
If you want to handle check whether it's a float so you can give a different error, do the same thing—try to call float(userGuess)—inside the except clause. Or, if you want to truncate floats, change that int(userGuess) to int(float(userGuess)).
You may also want some other checks even inside the try part. For example, what if they type -23 or 178? Those are integers, but they're not numbers between 1 and 100.
Obviously, the more validation you want, the more code it takes, because each test is another line of code. So, you may want to consider moving the validation out to a separate function from the looping over input, to make it more readable.
You could use string manipulation and typecasting.
int(userGuess.split('.')[0])

In this code you have a code for the door and a keypad for it

I have a door and there's a keypad code for it. If you get the code right you say Correct, if you get it wrong it just prints the wrong code (Just for debugging). However, I don't understand why nothing's happening when I code it. This is python btw:
realnumber = [12345]
inputnumber = []
def main():
integer = input("Input a list of numbers to open the door:")
if integer == realnumber:
print(realnumber)
print("Correct")
else:
inputnumber.append(integer)
main()
This is largely guess work but two issues stand out to me here:
integer = input("Input a list of numbers to open the door:")
You may not be a aware that the variable named integer here is going to a string regardless of your input. Might I suggest you try:
integer = int(input("Input a list of numbers to open the door:"))
or even better, something like this to catch nonsense input:
try:
integer = int(input("Input a list of numbers to open the door:"))
except ValueError:
print("Invalid Input")
Secondly,
if integer == realnumber:
Here you are trying to compare the variable "integer" (which is currently a string but with my suggested change will be an "int" variable) with realnumber, but realnumber is a list of variables that has only one input.
I suggest you choose one of these changes:
if integer == realnumber[0]:
or
realnumber = 12345

isinstance returning False when I expect it to return true

I am pretty new to Python. I'm just trying out a piece of code where the expected behaviour is:
It checks if an user input is an integer and if yes, outputs the square root of it. If not an integer, the system simply says its not an integer and does not do any calculation. Calculating the square root here is not important - I know there are inbuilt functions for calculating it, I am just practicing writing some lines of code.
However I have run into two problems
I'm trying to use ininstance to check whether the user input is really an integer. The problem is that the following check is returning a false even when I give an integer (say 64) as the input. I'm at a loss to understand why:
number1 = input("Please enter an integer ")
print(number1)
result = isinstance (number1, int)
print(result)
Second is the IF Else loop. I defined a function SQUARE_ROOT(), and tried calling it only when the input is an integer. However, if the input is a string, e.g. "Sun"", the Else part is still executed and and returns a value error.
ValueError: invalid literal for int() with base 10: 'sun'.
I'm not sure what the issue here is again. I did try checking the indentation and does not seem very wrong to my rather inexperienced eyes
funtion to output the squuare root of a number
#import math
#print("Please enter a number")
def SQUARE_ROOT(number2):
#Sq_root = math.pow(int(number2),0.5)
Sq_root = int(number2)**0.5
print(Sq_root)
number1 = input("Please enter an integer ")
print(number1)
result = isinstance (number1, int)
print(result)
if(result == "False"):
print("You have not entered an integer. the program will quit")
#Print(quit)
#sys.exit()
else:
print ("You have correctly entered an integer")
SQUARE_ROOT(number1)
when you are taking the input you are getting a string not an integer that's why it is returning false.
number1 = int(input("Please enter an integer "))
print(number1)
result = isinstance (number1, int)
print(result)
So basically in Python 2.7, we are having two ways to accepts inputs from the user.
raw_input: always returns string
input: Data & it's type get preserved.
So if user enters 1234 then the datatype would become int and if it's in string then str and so on.
Now Coming to the Python 3.x, function raw_input has been removed and input function behaviour get replaced with them.
In nutshell, everything that input function accepts and returns is of str type just like how the raw_input works in Py2.
Therefore, as per your question, the solution is you have to typecast after finding the types if its of desirable one. You may take help of isdigit method to know if its a number instead of using isinstance which would be true anyway once you convert them to int.
number1 = input("Please enter an integer ")
if number1.isdigit():
print ("You have correctly entered an integer")
SQUARE_ROOT(int(number1))
else:
print("You have not entered an integer. the program will quit")
#Print(quit)
#sys.exit()
Your else is executing because if statement is not true because you are comparing string with boolean. To do so you have to either convert book to string or just remove quotes from false. And second thing is you have to convert your input from string format into integer then try calling is instance. Hopefully it should work then.
You are using int(...) in the function but as #buran said input(...) returns string and you are asking if it's int. That is why it's returning False.
You can check that by adding print(type(number1)) after the input.
thanks everyone for pointing me in the right direction. I did some more work and wanted to the code to handle the situation where the user could enter int or float or a string (by mistake). the code I have finally come up with is given below. gieven i am a beginner am sure this is not possibly the best way to write the code (i used while when i am not looping) but it does the job for now. thanks again
def SQUARE_ROOT(message):
while True:
try:
number2 = float(message)
except ValueError:
print("Not a number! The program will exit.")
break
else:
Sq_root = float(number2)**0.5
print("The square root of", number2, "ïs",Sq_root)
print("Good Bye")
break
userInput = input("PLease enter a number to get it's square root, or type exit ")
if userInput == "exit" :
print ("Good Bye")
else :
number1 = SQUARE_ROOT(userInput)

Return a statement based on the type of the input(float/int/str)

I am a beginner in coding python and I stumbled upon an issue with a particular exercise. This exercise involves asking an input string from the user and to print out the length of the string. If the user types an int, it should say "You can not calculate the length of an int" and if the user enters a float it should say, "You can not calculate the length of an int". Here is my code.
def string_length(mystring):
if mystring.isdigit():
return "You can not calculate that length!"
if isinstance(mystring,float):
return "You can not calculate that length!"
else:
return len(mystring)
mystring = input("Enter some random string ")
print(string_length(mystring))
This does not print out any error but the function itself does not work when I enter in a float as an input. I have tried
type(mystring) == int/float
but it is not working. How can i modify my code to solve this problem?
The misunderstanding is that the built-in input gives a type dependent on the value input. This isn't true. It always gives string / str output in Python 3.x.
One way you can test for a potentially non-string input is to try converting to float. If successful, print your error message. If not successful, compute and return the length of the string:
def string_length(mystring):
try:
float(mystring)
return 'You cannot calculate the length of a number'
except ValueError:
return len(mystring)
mystring = input("Enter some random string ")
print(string_length(mystring))

Categories