What am I doing wrong?
valid = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun","All"])
value = input("Enter the day of interest or all for all days. Valid Values are Mon,Tue,Wed,Thu,Fri,Sat,Sun,All: ")
count = 0
while count <= 3:
if value in valid:
print("Awesome!! You chose {}".format(value.title()))
break
else:
count += 1
pass
print("Try Again")
else:
print("Too many errors. Read the instructions and come back again when ready!! :-| ")
exit()
So this works if I enter a valid value but if I test for a value outside the set, the else from the if loop ('Try Again') executes 3 times (setting the counter and then jumps to the else of the while loop.
I had wanted the input box to appear again and persist till either:
1. User entered the right value in 3 tries
2. Got a message and got booted out of the program returning them to command prompt.
Thanks in advance. Doing a tutorial project and completely stuck on this. Should I be using try/except? If so, would I still be able to set a counter?
You need to allow the user to enter input again. Place the input entering line below the Try again part.
print("Try Again")
value = input("Enter the day of interest or all for all days. Valid Values are Mon,Tue,Wed,Thu,Fri,Sat,Sun,All: ")
You also do not require the pass statement.
And please note that you're starting count from 0, that actually gives the user 4 chances, not 3. (Start with count=1)
Related
I'm trying to write a program that will help me in my job to write behavioral reports on teenage boys in a therapeutic program. The goal is to make it easier to write the everyday expectations(eating, hygiene, school attendance, etc) so that I can write the unique behaviors and finish the report faster. I'm currently working on how many meals the boy at during the day and am trying to get it to validate that the user input is the correct type of input and within the correct range(0-3). Afterwards I want to change the variable depending on the answer given so it will print a string stating how many meals they ate. I've been able to get the program to validate the type to make sure that the user gave and integer but I cant get it to make sure that the given answer was in the desired range. Any help would be appreciated I only started learning python and programming a month ago so very inexperienced.
Here's what my code looks like so far and what I would like the variable to change to depending on the given answer.
Name=input('Student Name:')
while True:
try:
Meals=int(input('Number of Meals(between 0-3):'))
except ValueError:
print ('Sorry your response must be a value between 0-3')
continue
else:
break
while True:
if 0<= Meals <=3:
break
print('not an appropriate choice please select a number between 0-3')
#if Meals== 3:
#Meals= 'ate all 3 meals today'
#elif Meals==2:
#Meals='ate 2 meals today'
#elif Meals==1:
#Meals='ate only 1 meal today'
#elif Meals==0:
#Meals='did not eat any meals today'
You can check if number of inputted meals falls to valid range and if yes, break from the loop. If not, raise an Exception:
while True:
try:
meals = int(input('Number of Meals(between 0-3):'))
if 0 <= meals <= 3:
break
raise Exception()
except:
print('Please input valid integer (0-3)')
print('Your choice was:', meals)
Prints (for example):
Number of Meals(between 0-3):xxx
Please input valid integer (0-3)
Number of Meals(between 0-3):7
Please input valid integer (0-3)
Number of Meals(between 0-3):2
Your choice was: 2
The for loop is working eventhough the provided value is in the list
Tried to run the code in different IDEs. but code did not work in any of these environments
#Check whether the given car is in stock in showroom
carsInShowroom = ["baleno", "swift", "wagonr", "800", "s-cross", "alto", "dezire", "ciaz"]
print("Please enter a car of your choice sir:")
carCustomer = input()
carWanted = carCustomer.lower()
for i in carsInShowroom:
if i is carWanted:
print("Sir we do have the Car")
break
else:
print("Sorry Sir we do not currently have that model")
Only else block running. when I enter wagonr, the output says "Sorry Sir we
do not currently have that model"
Change this,
if i is carWanted: # `is` will return True, if
to
if i == carWanted.strip(): # strip for remove spaces
Why?
is is for reference equality.
== is for value equality.
*Note: Your input should be wagonr not wagon r
I have been trying to implement this code whose work is to find a particular element using Binary search.Now the code works fine if element is present in the list but it is unable to display the intended block if the search element is not present.I have assumed that the list is sorted in ascending order.Help on this would be appreciated
I have tried giving an else part with the while: but it doesn't help.Its unable to show the error for element not found
def binarysearch(l,item):
low=0
u=len(l)-1
while low<=u:
mid=int((low+u)/2)
if item==l[mid]:
return mid
elif item<l[mid]:
high=mid-1
else:
low=mid+1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
print(item,"found at index",index)
else:
print("Element not found") #i am unable to reach this part
If input is:
Enter the list of elements[8,12,19,23]
Enter search item:10
I expect the result to be "Element not found" .but the program does nothing in this situation
I will give you a tip and later on I will test better this code and try to explain why it is happening.
The tip is to use in to check if the items exist in a list or not. In is more performatic than use a loop.
Exemplo working:
def binarysearch(elem, item):
if item in elem:
return elem.index(item)
else:
return -1 # because your if verifying if the return is equal or greater than 0.
Update 1
When I tried to run your code I got in one infinite loop, it's happening because of the expression mid=int((low+u)/2) - I couldn't understand why you did it. If we run this code happens this:
list [8,12,19,23] and Item 10
u=len(l)-1 u = 3 because 4 - 1
Get in the while because the condition is True
mid=int((low+u)/2) here mid will be (0+3)/2 as you force it to be int the result will be 1
if item==l[mid]: 10 == 12 -- l[mid] - l[1] - False
elif item<l[mid]: 10<12 True
high=mid-1 high will be 1 - 1 = 0
You go to the next iteration starting on the number 3, and that is why you get in an infinite loop
To go through all positions in a list, you could use the low that starts in 0 and increase if the item is not == the value in that position. So you could use the while but in that way:
def binarysearch(l,item):
low=0
u=len(l)-1
while low<=u:
if item==l[low]:
return low
else:
low+=1
return -1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
print(item,"found at index",index)
else:
print("Element not found")
To debug your code you can use [1]: https://docs.python.org/3/library/pdb.html
Basically going through a list a printing related indexes to the list based on the mrp_number input.
I want to print an error statement or at least have it loop back to the user having to input the correct mrp_number again. My issue is that this is a large list with a good amount of rows with missing mrp_numbers. How do I loop through this list and have the error print once only?
I've done the else statement but it'll keep printing error as it reiterates through the list with a missing mrp_controller. I tried learning try and exception handling but I've no clue.
def mrp_assignment():
mrp_number = input("Enter MRP Controller Number ")
for row in polist:
purchasing = row[0]
material = row[7]
mrp_controller = row[8]
description = row[9]
if mrp_number in mrp_controller:
print(mrp_controller, purchasing, material, description)
else:
print('error')
I expected one error to be printed but I got multiple errors printed
Simply put a break after print('error'). This will break your for loop if error occurs.
I have to make a fill in the blank quiz for my online class but I seem to be stuck, and am having trouble finding out why I'm stuck. Any advice would be great, thanks! this is my code so far... When I run the code it gets to the point of asking the first question and is looking for an answer but when I put it in it gives me the "not quite, please try again" prompt so am I not calling the answers right?
print ('Welcome to my computer programming Quiz, in this quiz you will be
asked to select from three difficulty levels, easy, medium, and hard. Each
the level contains 4 - 5 fill in the blank questions')
print ('')
print ('Your score at the end will be based on how many correct answers you
get compared to the number of guesses you take')
print ('')
# opening introduction to the Quiz
level=None
while level not in ['easy', 'medium', 'hard']:
level = input ('Please select a difficulty (easy, medium, or hard):').lower()
# This is where the difficulty is chosen, this is also is the reason I couldn't get my
# code to open until I did some searching around the internet and found that
# raw_input had to be replaced with input in newer versions of python. Also, I found
# that adding .lower() makes the user's input lower case so that it fits with the
# potential answers.
guesses, score = 0, 0
# this is where the number of guesses and the number of right answers will be collected
# and then shown to the user at the end
easy_questions = ['When you give a computer an instruction, its called
giving a computer a _____.',
'The _____ of a computer language is the set of rules that
defines the combination of symbols that are considered to be a correctly
structured document or fragment in that language.',
'A _____ is a value, one that can change based on conditions.',
'One piece of a larger group is called a _____ in computer
programming.',
'_____ are made up of elements, and are enclosed in square brackets.']
medium_questions = ['A _____ starts with the keyword def followed by the its name.',
'A _____ is a character that represents an action, such as x representing multiplication.',
'A _____ is a set of coded instructions that tell a computer how to run a program or calculation.',
'A _____ is traditionally a sequence of characters either as a literal constant or as some kind of variables.',
'An expression inside brackets is called the _____ and must be an integer value.']
hard_questions = ['A sequence of instructions that is continually repeated until a certain condition is reached, is called a _____ function.',
'A control flow statement that allows code to be executed repeatedly based on a true/false statement is called a _____ loop.',
'This is a common thing in programming when a variable is defined and then redefined the variable has gone through a _____.',
'_____ refers to the situation where the same memory location can be accessed using different names']
# The first thing I tried was having all the questions and then all of the answers
# together in two big lists bc of some code I saw online while researching how to
# do this project but couldn't figure out how to make that code work so I started
# over and tried this way with longer code but code I thought I could make work.
easy_answers = ['command', 'syntax', 'variable', 'element', 'lists']
medium_answers = ['function', 'operator', 'procedure', 'string', 'index']
hard_answers = ['loop', 'while', 'mutation', 'aliasing']
if level == 'easy':
questions = easy_questions
answers = easy_answers
elif level == 'medium':
questions = medium_questions
answers = medium_answers
elif level == 'hard':
questions = hard_questions
answers = hard_answers
# this is how I bet thought to get the the right questions and answers to be called up.
number_of_questions = 5
question_number = 0
def check_answer(user_answer, questions, answers):
if user_answer == answers:
print ('')
print ('Correct!')
score = + 1
guesses = + 1
question_number = + 1
# this will increase the score and guesses by one and move the quiz on to
# the next question.
else:
print ('')
print ('Not quite, please try again')
guesses = + 1
# this will only increase the guesses by one, and give the user another
# chance to answer the same question again.
while question_number < number_of_questions:
questions = questions[question_number]
user_answer = answers[question_number]
print('')
user_answer = input (questions + ': ').lower()
# Prompts the user to answer the fill in the blank question.
print (check_answer(user_answer, questions, answers))
# this is where im also having a lot of trouble, ive done some research online and this
# is what i was told to use but it doesn't seem to be working.
print ('')
print ('Congratulations, you have completed the ' + str(level) + ' level, with a score of ' + str(score) + ' out of ' + str(guesses) + ' guesses')
Well the problem seems to be very trivial. When you check if the answer is correct or not in the check_answer with the code line below:
if user_answer == answers:
you're answers is an array containing all the answers while the user_answer is the string that the user has typed. Hence, when you type the first answer as "command" is tries to match the string "command" to an array containing a few strings. which is definitely not gonna match.
use the below code line to solve it:
if user_answer in answers: