I tried of making and Celcius to Faharanite converter and visa-versa.
I made extra if-else ladder to ensure that the user doesn't get stuck and when the user enters something wrong.
But i tried compiling this after the first statement gets terminated.
ch = raw_input("""What you want to convert :
1) Celcius to Faharanite.
2) Faharanite to Celcius.\n""")
if (type(ch)==int):
if (ch==1):
cel=raw_input("Enter to temperature in Celeius : ")
if (type(cel)!='float'):
cel = 1.8*(cel+32)
print "The Conversion is :" + cel
else :
print "YOu should enter values in numeric form"
elif (ch==2):
fara=raw_input("Enter to temperature in Faharanite : ")
if (type(fara)==float):
print "The Conversion is :" + 1.8*(fara-32)
else :
print "YOu should enter values in numeric form"
else :
print "Wrong choice"
Because the first if statement is never true. The result of raw_input is always a string.
devnull's comment suggesting adding ch = int(ch) will work as long as the user input is a number.
For more robust handling, I would do something like:
is_valid = False
while not is_valid:
ch = raw_input("""What you want to convert :
1) Celsius to Fahrenheit.
2) Fahrenheit to Celsius.\n""")
try:
ch = int(ch) # Throws exception if ch cannot be converted to int
if ch in [1, 2]: # ch is an int; is it one we want?
is_valid = True # Don't need to repeat the while-loop
except: # Could not convert ch to int
print "Invalid response."
# The rest of your program...
which will continue to to prompt the user until they enter a valid choice.
Note that you'll have to use a similar try/except construct to parse the temperature-to-convert into a float (with the float() method).
Related
I am a beginner programmer, working on a project for an online course. I am trying to build a tip calculator. I want it to take input from the user for three values: Bill total, how many are splitting the bill, and the percent they would wish to tip. My conditional statement only has one if:
if meal_price >= 0.01:
example(example)
else:
example(example)
There are no elifs, only an else clause, stating to the user to enter only a numerical value. The program is designed to loop if the else clause runs, or continue if the 'if' condition is met. I would like this program to be completely user-friendly and run regardless of what is typed in. But instead of the else clause being ran when a user enters a string value, the terminal returns an error. How would I check the datatype the user enters, and run my conditional statement based off of that instead of the literal user response?
Note, I've tried:
if isinstance(meal_price, float):
Converting the user input into a string, but then the conditional statement becomes the problem
Thank you all for the help. I started my coding journey about 3 months ago and I am trying to learn as much as I can. Any feedback or criticism is GREATLY appreciated.
enter image description here
def calculation():
tip_percent = percentage / 100
tip_amount = meal_price * tip_percent
meal_and_tip = tip_amount + meal_price
total_to_return = meal_and_tip / to_split
return total_to_return
print("\nWelcome to the \"Bill Tip Calculator\"!")
print("All you need to do is enter the bill, the amount of people splitting it, and the percent you would like to tip.\n")
while True:
print("First, what was the total for the bill?")
meal_price = float(input("Bill (Numerical values only): "))
if meal_price >= 0.01:
meal_price2 = str(meal_price)
print("\nPerfect. The total is " + "$" + meal_price2 + ".")
while True:
print("\nHow many people are splitting the bill?")
to_split = int(input("People: "))
if to_split >= 1:
to_split2 = str(to_split)
print("\nAwesome, there is", "\"" + to_split2 + "\"", "person(s) paying.")
while True:
print("\nWhat percent would you like to tip?")
percentage = float(input("Percentage (Numerical values only, include decimals): "))
if percentage >= 0:
percentage2 = str(percentage)
print("\nGot it.", percentage2 + '%.')
calculation()
total = str(calculation())
#total2 = str(total)
print("\n\nEach person pays", "$" + total + ".")
exit()
else:
print("\nPlease enter only a numerical value. No decimals or special characters.")
else:
print("\nPlease respond with a numerical value greater than 0.\n")
else:
print("Please remember to enter only a numerical value.\n")
Included image snapshot in case copy & paste isn't accurate.
The user's input will be a string, so you need to check if the parse to the float was successful. You can do that with a try/except, and then loop back over asking for more input:
print("First, what was the total for the bill?")
meal_price = None
while meal_price == None:
try:
meal_price = float(input("Bill (Numerical values only):"))
except ValueError:
print("That didn't look like a number, please try again")
print(meal_price)
Adding on to #OliverRadini's answer, you use the same structure a lot for each of your inputs that could be generalized into a single function like so
def get_input(prompt, datatype):
value = input(prompt)
try:
a = datatype(value)
return a
except:
print("Input failed, please use {:s}".format(str(datatype)))
return get_input(prompt, datatype)
a = get_input("Bill total: ", float)
print(a)
Perhaps the main point of confusion is that input() will always return what the user enters as a string.
Therefore trying to check whether meal_price is something other than a string will always fail.
Only some strings can be converted into floats - if you try on an inappropriate string, an exception (specifically, a ValueError) will be raised.
So this is where you need to learn a bit about exception handling. Try opening with this block:
meal_price = None
while meal_price is None:
try:
meal_price = float(input("Bill (Numerical values only): "))
except ValueError:
print("Please remember to enter only a numerical value.\n")
This will try to execute your statement, but in the event it encounters a value error, you tell it not to raise the exception, but to instead print a message (and the loop restarts until they get it right, or a different kind of error that you haven't handled occurs).
Thank you all! After looking into your comments and making the amendments, my program works perfectly! You lot rock!!
def calculation():
tip_percent = tip / 100
tip_amount = bill * tip_percent
meal_and_tip = tip_amount + bill
total_to_return = meal_and_tip / to_split
return total_to_return
def user_input(prompt, datatype):
value = input(prompt)
try:
input_to_return = datatype(value)
return input_to_return
except ValueError:
print("Input failed, please use {:s}".format(str(datatype)))
return user_input(prompt, datatype)
print("\nWelcome to the \"Bill Tip Calculator\"!")
print("\nAll you need to do is:\n1.) Enter your bill\n2.) Enter the amount of
people (if bill is being split)\n3.) Enter the amount you would like to
tip.")
print("\n\n1.) What was the total for the bill?")
bill = user_input("Total Bill: ", float)
print("\nAwesome, the total for your meal was " + "$" + str(bill) + ".")
print("\n\n2.) How many people are splitting the bill?")
to_split = user_input("Number of People: ", int)
print("\nSo the bill is divided", str(to_split), "way(s).")
print("\n\n3.) What percent of the bill would you like to leave as a tip?
(Enter a numeral value only. No special characters.)")
tip = user_input("Tip: ", int)
print("\nYou would like to tip", str(tip) + "%! Nice!")
total = calculation()
print("\n\n\n\nYour total is " + "$" + str(total), "each! Thank you for using
the \"Bill Tip Calculator\"!")
So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
user_input = float(input("Please enter a multiplier!")
if user_input == int:
print " Please enter a number"
else:
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
The program will run effectively, as for any number entered by the user the result will be effective, yet I wish to know a function that allows the user to ask for a number when they enter a letter.
Use a try/except inside a while loop:
while True:
try:
user_input = float(raw_input("Please enter a multiplier!"))
except ValueError:
print "Invalid input, please enter a number"
continue # if we get here input is invalid so ask again
else: # else user entered correct input
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
break
Something that's a float is not an int. They're separate types. You can have a float that represents an integral value, like 1.0, but it's still a float.
(Also, user_input == int isn't checking whether user_input is an int, it's checking whether user_input is actually the type int; you wanted isinstance(user_input, int). But since that still won't work, let's skim over this part…)
So, can you check that a float has an integral value? Well, you can do this:
if int(user_input) == user_input
Why? Because 1.0 and 1 are equal, even though they're not the same type, while 1.1 and 1 are not equal. So, truncating a float to an int changes the value into something not-equal if it's not an integral value.
But there's a problem with this. float is inherently a lossy type. For example, 10000000000000000.1 is equal to 10000000000000000 (on any platform with IEEE-854 double as the float type, which is almost all platforms), because a float can't handle enough precision to distinguish between the two. So, assuming you want to disallow the first one, you have to do it before you convert to float.
How can you do that? The easiest way to check whether something is possible in Python is to try it. You can get the user input as a string by calling raw_input instead of input, and you can try to convert it to an int with the int function. so:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
If you need to ultimately convert the input to a float, you can always do that after converting it to an int:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
else:
user_input = float(user_input)
You could use the assert-statment in python:
assert type(user_input) == int, 'Not a number'
This should raise an AssertionError if type is not int. The function controlling your interface could than handle the AssertionError e.g. by restarting the dialog-function
I am trying to write a program that will ask the user to input a string in all uppercase that ends with a period. Then have it come back with responses when the input doesn't meet the criteria. I understand how to check if it has a characteristic like uppercase I don't however understand how to check if it does not have a characteristic. This was my attempt using the != (as in, if the string does not = uppercase) but it didn't work. Thanks for any input, I'm very new so sorry if this is a dumb question.
"""Making sure they use uppercase and end with a period"""
s = input("Please enter an upper-case string ending with a period: ")
if s.isupper() and s.endswith("."):
print("Input meets both requirements.")
elif s!=upper():
print ("Input is not all upper case.")
elif s!=endswith("."):
print ("Input does not end with a period.")
else :
print ("You just don't want to do this, do you?")
Using not will reverse the logical statement
not True --> False
not False --> True
Here is the code:
"""Making sure they use uppercase and end with a period"""
s = input("Please enter an upper-case string ending with a period: ")
if s.isupper() and s.endswith("."):
print("Input meets both requirements.")
elif not s.isupper(): #not False -> True
print ("Input is not all upper case.")
elif not s.endswith("."): #not False -> True
print ("Input does not end with a period.")
else :
print ("You just don't want to do this, do you?")
You don't want to check if it does not equal uppercase --- that doesn't make sense anyway, because "uppercase" is an abstract notion that can't be equal to any particular string. You want to check if isupper() is not true. Just do elif not s.upper() and then elif not s.endswith(".").
Just made few adjustments to your code.
s = raw_input("Please enter an upper-case string ending with a period: ")
if s.isupper() and s.endswith('.'):
print("Input meets both requirements.")
elif not s.isupper():
print ("Input is not all upper case.")
elif not s.endswith("."):
print ("Input does not end with a period.")
else :
print ("You just don't want to do this, do you?")
When checking for not upper case or not ends with '.', you should not use != operator here. Because, both of these methods isupper() and endswith() returns booleans. Therefore to check if it is not True, you only have to use not operator.
Hi I am having trouble with the end of my loop. I need to accept the input as a string to get the "stop" or the "" but I don't need any other string inputs. Inputs are converted to float and then added to a list but if the user types "bob" I get the conversion error, and I cant set the input(float) because then I can't accept "stop".
Full current code is below.
My current thinking is as follows:
check for "stop, ""
check if the input is a float.
if its not 1 or 2, then ask for a valid input.
Any ideas please? If its something simple just point me in the direction and i'll try churn it out. Otherwise...
Thanks
# Write a progam that accepts an unlimited number of input as integers or floating point.
# The input ends either with a blank line or the word "stop".
mylist = []
g = 0
total = 0
avg = 0
def calc():
total = sum(mylist);
avg = total / len(mylist);
print("\n");
print ("Original list input: " + str(mylist))
print ("Ascending list: " + str(sorted(mylist)))
print ("Number of items in list: " + str(len(mylist)))
print ("Total: " + str(total))
print ("Average: " + str(avg))
while g != "stop":
g = input()
g = g.strip() # Strip extra spaces from input.
g = g.lower() # Change input to lowercase to handle string exceptions.
if g == ("stop") or g == (""):
print ("You typed stop or pressed enter") # note for testing
calc() # call calculations function here
break
# isolate any other inputs below here ????? ---------------------------------------------
while g != float(input()):
print ("not a valid input")
mylist.append(float(g))
I think the pythonic way would be something like:
def calc(mylist): # note the argument
total = sum(mylist)
avg = total / len(mylist) # no need for semicolons
print('\n', "Original list input:", mylist)
print("Ascending list:", sorted(mylist))
print ("Number of items in list:", len(mylist))
print ("Total:", total)
print ("Average:", avg)
mylist = []
while True:
inp = input()
try:
mylist.append(float(inp))
except ValueError:
if inp in {'', 'stop'}:
calc(mylist)
print('Quitting.')
break
else:
print('Invalid input.')