How do you make sure that the user only entered a float that has two decimal places. The number cannot be 4 or 4.999 it has to be 4.00 or 4.99 otherwise an error should appear.
while looping:
try:
number = float(input("Number: "))
string_number = (str(number)).split(".")
check_length = len(string_number)
if check_length != 2:
print ("ERROR!")
looping = True
else:
looping = False
except ValueError:
looping = True
You are currently only checking that there is currently just one decimal point.
number.split(".") will return a list. If number is 4.323, it will return ['4', '323'].
What you really want to check in your if clause is that the length of the second element is 2.
if len(string_number[1]) != 2:
Check the second part of the number.
while True:
try:
number = input('Number:')
integral, fractional = number.split('.')
number = float(number)
if len(fractional) == 2:
break
except ValueError:
pass
print('ERROR!')
looping = True
while looping:
number = input("Number: ")
string_number = number.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
looping = True
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
looping = True
else:
try:
number = float(number)
looping = False
except ValueError:
print("ERROR: Number is not valid!")
looping = True
Making some minor changes eliminates the need for the variable looping. Since our goal is to get a valid number, we can just test for that:
number = None
while not number:
s = input("Number: ")
string_number = s.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
continue
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
continue
try:
number = float(s)
except ValueError:
print("ERROR: Number is not valid!")
I would write this way:
while True:
try:
str_num=input("Number: ")
num=float(str_num) # ValueError if cannot be converted
i, f=str_num.split('.') # also ValueError if not two parts
if len(f)==2:
break # we are done!!!
except ValueError:
pass
print('ERROR! ') # either cannot be converted or not 2 decimal places
print(num)
Related
I'm quite new to coding and I'm doing this task that requires the user to input an integer to the code. The function should keep on asking the user to input an integer and stop asking when the user inputs an integer bigger than 1. Now the code works, but it accepts all the integers.
while True:
try:
number = int(input(number_rnd))
except ValueError:
print(not_a_number)
else:
return number
You can do something like this:
def getPositiveInteger():
while True:
try:
number = int(input("enter an integer bigger than 1: "))
assert number > 1
return number
except ValueError:
print("not an integer")
except AssertionError:
print("not an integer bigger than 1")
number = getPositiveInteger()
print("you have entered", number)
while True:
# the input return value is a string
number = input("Enter a number")
# check that the string is a valid number
if not number.isnumeric():
print(ERROR_STATEMENT)
else:
if int(number) > 1:
print(SUCCESS_STATEMENT)
break
else:
print(NOT_BIGGER_THAN_ONE_STATEMENT)
Pretty simple way to do it, of course you must define ERROR_STATEMENT, SUCCESS_STATEMENT and NOT_BIGGER_THAN_ONE_STATEMENT to run this code as it is, I am using them as place-holder.
I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break
I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break
I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))
I have this program:
number = int(input('Contact Number:'))
def validatePhoneNumber(number):
count = 0
while True:
while number > 0:
number = number//10
count = count+1
if (count == 10) :
break
elif (count > 10) :
print('Invalid phone number')
return -1
elif (count < 10):
print('Invalid phone number')
return -1
validatePhoneNumber(number)
it will appear like this:
Contact Number:1234
Invalid phone number
>>>
I want it to continue to loop until a 10 digit number is entered then it will stop.
Contact Number:1234567890
>>>
The condition is that If the number is missing or invalid, return ‐1.
Am I missing something inside the program?
Thanks
What about this:
number = input('Contact Number:') # it's a str now, so we can use len(number)
def validatePhoneNumber(number):
while len(number) != 10:
number = input("Please enter a 10-digit contact number: ")
return number
number = validatePhoneNumber(number)
It's a more pythonic approach and therefore easier to understand and debug. Also as other comments pointed out, leading 0s aren't stripped away now.
I am getting an infinite loop. I am not sure on how to covert the result as the new number variable and put it back in the while loop.
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except:
ValueError
print('Please type an integer')
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
**result = number**
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
The following works:
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except ValueError:
print('Please type an integer')
sys.exit(1)
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
number = result # set the number to the result
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
Notice that I set the number to the result, in your code the number never changed, and so kept hitting the same block of code over and over. I also added a sys.exit call in the exception, we don't want to continue if someone entered in a bad value.
Distance = input("How far are you from the spacecraft in meters? (full positive numbers) \n")
number = Distance.isdigit()
while number == False:
print ("Please enter a number or full number")
Distance = input("How far are you from the spacecraft in meters? (full positive numbers) \n")
number = Distance.isdigit()
while Distance < 600:
print ("Please move back further from the space craft! \n")
Distance = input("How far are you from the spacecraft in meters? (full positive numbers) \n")
So I am trying to compare a string to a integer but I'm not sure how to fix that with out breaking this part
number = Distance.isdigit()
while number == False:
I think you can use this.
def is_digit(Distance):
try:
if int(Distance) & int(Distance) >0:
return True
return False
except ValueError:
return False