Basic Error Capture - for inputs - Python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to error capture my variables that are set by a user input. So far I have done this but was wandering if there are any simpler or more efficient ways of doing this:
while number1error == 1:
try:
number1 = float(input("Please enter the value of number1"))
break
except ValueError:
print("Please enter an integer")
As you can see this would take up a lot of space if I had a lot of inputs from the user. Any better suggestions would be appreciated.

Would this help?
totalReTries = 10
acquiredValue = None
PROMPT_MESSAGE = "Please enter the valid value: "
typeOfInteredData = float
rangeOfData = range(10, 20)
for currentRetry in range(1, totalReTries):
print "Attempt %d of %d" % (currentRetry, totalReTries)
try:
acquiredValue = input(PROMPT_MESSAGE)
except ValueError:
print("Incorrect data format. Please try again.")
continue
if type(acquiredValue) != typeOfInteredData:
print "Incorrect data type. Please try again."
continue
elif not acquiredValue in rangeOfData:
print "Incorrect data Range. Please try again."
continue
break
if not acquiredValue:
print "ERROR: Failed to get a correct value"
else:
print "The acquired value is: " + str(acquiredValue)
Adapting this into a function, as suggested above, would be a good idea too.
Regards

Related

Tips For an Intro Python Program [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Below is my first python program. I am trying idea not yet covered in class as i hate staying stagnant and want to solve issues that may arise if i were to just use the info we've learned in class. As for my question, the program works but what were be ways to condense the code, if any? Thanks!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge
class colors:
ERROR = "\033[91m"
END = "\033[0m"
#input validation
while True:
while True:
try:
nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
else:
break
while True:
try:
number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
while True:
try:
campers=int(input("Enter the Number of Campers:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
break
#processing
while True:
try:
campsite=nightly_rate*number_of_nights
tax=(ELECTRICITY*0.07)+(campsite*0.07)
ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
total=campsite+ELECTRICITY+tax+ranger #total paid per camper
total_per=total/campers
except ZeroDivisionError: #attempt to work around ZeroDivisionError
total_per=0 #total per set to zero as the user inputed 0 for number-
break #-of campers
#Output #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper------------------- $%4.2f"%total_per)
The else in try statement is unnecessary. You can just put the break in the the end of the try statement. REF
In the end, in the print statements, I recommend you to use another types of formatting. You can use '...{}..'.format(..) or further pythonic is f'...{val}'. Your method is the oldest. More ref
You can remove both the outer while loops, as break is seen there at the top level, so the loops runs once only.
You can convert colors to an Enum class if desired (this is more of a stylistic choice tbh)
The line tax=(ELECTRICITY*0.07)+(campsite*0.07) can be represented as x*0.07 + y*0.07, which can be simplified to 0.07(x+y) or 0.07 * (ELECTRICITY + campsite) in this case.
Instead of manually padding the - characters in the print statements, you can use f-strings with simple formatting trick.
For example, try this out:
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')

python quiz with subject options [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
print("plese choose a topic of your liking")
History = ('History')
Music = ('Music')
Computer_science = ('Computer science')
print (History, Music, Computer_science)
History = print("when did the Reichstag fires begin?")
one = ("1) 1937")
two = ("2) 1933")
three = ("3) 1935")
print (one, two, three)
guess = int(input())
if guess == 2: #this makes it so any option appart from 2 is outputed as 'wrong'
print ("well done")
else:
print("wrong")
I have created the first part of my python quiz, It took me a while to figure out, I have also created a list that contains 3 different subjects, Do any of you know how to assign a button to each element within my subject list? If this does not make any sense, please let me know (I'm new to this site)
to get this sort of behaviour you can make an input before everything else which determines what subject you choose based on user input. so something REAL simple like:
subject = int(input("Please choose what subject you would like
(number):\n[1]History\n[2]Maths\n[3]Geography\n"))
if subject == 1:
print("You have chosen History")
elif subject == 2:
print("You have chosen Maths")
elif subject == 3:
print("You have chosen Geography")
else:
print("that is not an available option")
This is probably the simplest it can get with menus... If you type 1 and press enter you get history and so on. i dont know how your program works but do what fits in.
There are probably better ways too this is just what I remember doing back in the day. Very simple stuff

How would I implement the try/except/else structure to my code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
for my Informatics class assignment it is asking me to use a try/except/else structure to my code. I know im not supposed to post beginner friendly questions on this website but I am in need of help.
Check that the user enters a valid month number and a valid day number. Use a try/except/else structure to ensure numeric data is entered. I already have the if/else structure.
I do not know if the question is asking me to use one of them or all three.
Here is my code and it works perfectly fine:
#This program will ask the user to enter a month (in numeric form), a day in a months, and a two-digit year.
#Then, determine if this is a special date(the month times the day equals the year).
#Special Date
print("The date February 10, 2020 is special because when it is written in the following format the month times the day equals the year : 2/10/20.")
#Inputs
userInputMonth = int(input("Please enter a valid month:"))
userInputDay = int(input("Please enter a valid day:"))
userInputYear = int(input("Please enter a valid two-digit-year:"))
print()
if userInputMonth * userInputDay == userInputYear:
print("The date you provided " + str(userInputMonth) + "/" + str( userInputDay) + "/" + \
str(userInputYear) + " is the special date.")
else:
print("The date you provided " + str(userInputMonth) + "/" + str(userInputDay) + "/" + \
str(userInputYear) + " is not the special date.")
I just need to figure out how to implement the try/except/else structure to make sure that its a valid month, valid day, valid year.
Try-except-else in Python works roughly in this way:
try:
dosomething() # see if something works
except:
handleproblem() # it didn't work, handle the problem
else:
domorestuff() # it did work, proceed normally
In your case, parsing user input would be something that could fail, like if the user input was abc instead of a number.
try:
usermonth = int(input("Please enter a valid month:"))
except ValueError as e:
print("Please provide a numeric input next time")
else:
print("Thank you, month is ok")
That is not a full solution to your problem, but should get you started.
Use a try/except/else structure to ensure numeric data is entered.
My interpretation of this requirement of your assignment is that you are supposed to do just what I lined out above, use try-except-else to make sure the user did in fact enter numeric data.
To give a litte hint on how the structure of your final program could look like:
collect user input into variables (do not parse yet, just store it)
try to parse stored user input with int()
if (2) fails with exception, print a scolding message
else print nice message, do that special date thing, etc
Are you looking for something like this?
try:
userInputMonth = int(input("Please enter a valid month:"))
except ValueError as error:
print(str(error))
else:
print("Input month is ok!")
If userInputMonth is wrong, the above program will print an error message.
Edit: You can modify your code as follows.
while True:
try:
userInputMonth = int(input("Please enter a valid month:"))
except ValueError:
print("Please provide a numeric input for the month. Try again...")
else:
break
while True:
try:
userInputDay = int(input("Please enter a valid day:"))
except ValueError:
print("Please provide a numeric input for the day:")
else:
break
while True:
try:
userInputYear = int(input("Please enter a valid two-digit-year:"))
except ValueError:
print("Please provide a numeric input for the year.")
else:
break

Command line: Show list of options and let user choose [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Assuming I have a list of options:
options = ["Option 1", "Option 2", "Option 3"]
And I would like the user to choose an option on the command line, e.g. something like this:
Please choose:
1) Option 1
2) Option 2
3) Option 3
Enter number: <user input>
So I am looking for the implementation of the following:
choice = let_user_pick(options) # returns integer
How would one go about this in python?
def let_user_pick(options):
print("Please choose:")
for idx, element in enumerate(options):
print("{}) {}".format(idx+1,element))
i = input("Enter number: ")
try:
if 0 < int(i) <= len(options):
return int(i)
except:
pass
return None
You might want to instead return int(i)-1 in order to use the result as an index of your options list, or return the option directly. It might also be good to instead of returning None loop over the whole thing until the user enters a correct choice.

python - Is it possible to combine 2 functions together to create 1 function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to combine these functions together to create 1 function?
def checkinput():
while True:
try:
name=input("whats your name?")
return name
except ValueError:
print("error!")
Combined with:
def checkage():
while True:
try:
age=input("whats your age?")
return age
except ValueError:
print("error!")
Thanks in advance!
You can refactor the code to create one function that handles both cases, by recognizing the parts that are the same, and parameterizing the other parts.
def check_value(prompt):
while True:
try:
val=input(prompt)
return val
except ValueError:
print("error!")
The only difference between the two functions (other than trivial differences like variable names) was the prompt shown by the input function. We make that a parameter to the new unified function, and call it like this:
x = check_input("What's your name?")
y = check_input("What's your age?")
Why you expect input to possibly raise a ValueError is a different question.
If you want to generalize your code, you could write one function that can ask any number of questions.
You can create a function that looks like this:
def ask_a_question(prompt):
while True:
try:
answer = input(prompt)
except ValueError:
print("Error!")
else:
return answer
For example, in your main() function, you could have a list of prompts:
prompts = {
'name': 'What is your name?',
'age': 'How old are you?',
'dog': 'Do you love dogs more than cats? (yes, you do)',
}
And finally you would create a loop that would ask all your questions one by one:
answers = {} # a dictionary of answers
for key, prompt in prompts.items():
answers[key] = ask_a_question(prompt)
Hopefully that gives you some ideas on how to reduce duplication of similar functions.
You can easily call a function from other functions:
def check_user_data():
checkinput()
checkage()
But really, this is a silly thing to do. If you just want their name and age you'd be better off doing something like this:
def get_user_info():
name = input("What is your name? ")
age = input("What is your age? ")
return name, age
You're never going to get a ValueError when you're just taking input - if you were doing int(input('What is your age? ')) you could get a ValueError, but otherwise the rest of your code is superfluous.
Yes!
def check_input_and_age():
return checkinput(), checkage()

Categories

Resources