How to find if the value contains characters - python

Right now am planning to add items into the database. The item name, price and all are all entered by the users. How do I find if theres any alphabets when entering the price? i tried using .isnumber() but it seems to be reading my decimal point as a character as well.
while True:
itemPrice = input("Please Enter Item Price: ")
if str(itemPrice).isnumeric() == False:
print("Please enter a value!")
else:
print(itemPrice)
break
For example, they allow if i enter 5 but not 5.5 and since this is item price it should have decimals.

You can catch exceptions,
while True:
itemPrice = input("Please Enter Item Price: ")
try:
itemPrice = float(itemPrice)
print(itemPrice)
break
except ValueError:
print("Please enter a value!")

you can use try/except block
a = 3.5345
a=str(a)
try: #if it can be converted to a float, it's true
float(a)
print(True)
except: # it it can't be converted to a float, it's false
print(False)

You could try using a for loop to check:
def containsAlpha(x):
if True in [char.isalpha() for char in x]:
return True
return False
while True:
itemPrice = input("Please Enter Item Price: ")
if containsAlpha(itemPrice):
print("Please enter a value!")
else:
print(itemPrice)
break

Related

Trying to control the user's input to strictly a positive number only

I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number.
I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
boolChoice = False
except ValueError:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
elif l < 0:
print("Your number is not positive")
print("Try again")
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.
You can use try...except to check if its an integer or letters
def input_validation(prompt):
while True:
try:
l = int(input(prompt))
if l<0: #=== If value of l is < 0 like -1,-2
print("Not a positive number.")
else:
break
except ValueError:
print("Your input is invalid.")
print("Try again")
return l
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
try
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
if x < 0:
print ("Your input is a negative number\n Please enter a postive number")
elif x == 0:
print("Your input is zero\n Please enter a postive number ")
else:
boolChoice = False
except Exception as e:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
else:
print(f"Failed to accept input due to {e}")
print("Try again")
continue
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()

Try loop raises KeyError

When I use a try/except, I get a KeyError, but when I don't use try it works as intended. I'm sure this is a simple fix but I've been banging my head on this for over an hour by now, any help is appreciated. Here is the code, forgive the simplicity!
def return_book():
"""Return a book to the library"""
print("To return the book, you will need the ISBN")
isbn = str(input("Please enter the book's ISBN: "))
amount = input("How many books are you returning? ")
try:
isbn = int(isbn)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
try:
amount = int(amount)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
library[isbn][2] = library[isbn][2] + int(amount)
print(library)
A KeyError occurs when we try to access a key from a dictionary that does not exist, you are transforming a string into a integer and using that integer as the key! Use str(isbn) to make isbn a string again:
try:
isbn = int(isbn)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
try:
amount = int(amount)
except ValueError:
print()
input("That is not a number, press enter to try again ")
return_book()
library[str(isbn)][2] = library[str(isbn)][2] + int(amount)
print(library)

How can I create a 'while'-exception loop?

I am working on a small coding challenge which takes user input. This input should be checked to be a digit. I created a "try: ... except ValueError: ..." block which checks once whether the input is a digit but not multiple times. I would like it to basically checking it continuously.
Can one create a while-exception loop?
My code is the following:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than
one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
uinput = int(input("You entered not a digit. Please try again: "))
flag = True
while flag:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
flag=False
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
print('Wrong input')
Output :
(python37) C:\Users\Documents>py test.py
Please enter a number: qwqe
Wrong input
Please enter a number: -123
Number is negative. Please try again: 123
123 is a prime number!
I add flag boolean to not make it repeat even when the input is correct and deleted input in except because it would ask 2 times.
If you press Enter only, the loop terminated:
while True:
uinput = input("Please enter a number: ")
if uinput.strip()=="":
break
try:
uinput=int(uinput)
except:
print("You entered not a digit. Please try again")
continue
if uinput<=0:
print("Not a positive number. Please try again")
continue
for i in range(2, uinput):
pass; # put your code here

Not sure what is wrong with this code for Python for Everybody 5.2

I'm taking Coursera and doing a python course.
I'm struggling with the last assignment.
Here is the assignment:
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
My code:
# largest = None
# smallest = None
store=[]
while True:
s = input("Enter a number: ")
if s == "done":
break
try:
store.append(int(s))
except:
print("Invalid input")
largest = max(store)
smallest = min(store)
# print("Invalid input")
print("Maximum is ",largest)
print("Minimum is ",smallest)
Please help.
Thanks
store=[]
while True:
s = input("Enter a number: ")
if s == "done":
break
try:
store.append(int(s))
except:
print("Invalid input")
largest = max(store)
smallest = min(store)
print("Maximum is ",largest)
print("Minimum is ",smallest)

Specific Try and Except

continue = True
while continue:
try:
userInput = int(input("Please enter an integer: "))
except ValueError:
print("Sorry, wrong value.")
else:
continue = False
For the code above, how would I be able to catch a specific ValueError? What I mean by that is if the user inputs a non-integer, I would print out "Sorry, that is not an integer.". But if the user input is an empty input, I would print out "Empty Input.".
Move the call to input outside of the try: block and place only the call to int inside it. This will ensure that userInput is defined, allowing you to then check its value with an if-statement:
keepgoing = True
while keepgoing:
userInput = input("Please enter an integer: ") # Get the input.
try:
userInput = int(userInput) # Try to convert it into an integer.
except ValueError:
if userInput: # See if input is non-empty.
print("Sorry, that is not an integer.")
else: # If we get here, there was no input.
print("Empty input")
else:
keepgoing = False
Perhaps something like this:
keepgoing = True
while keepgoing:
try:
userInput = input("Please enter an integer: ")
if userInput == "":
print("Empty value")
raise ValueError
else:
userInput = int(userInput)
except ValueError:
print("Sorry, wrong value.")
else:
keepgoing = False

Categories

Resources