trying to create a fill in the blank quiz in python - python-3.x

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:

Related

Defining a function to find the unique palindromes in a given string

I'm kinda new to python.I'm trying to define a function when asked would give an output of only unique words which are palindromes in a string.
I used casefold() to make it case-insensitive and set() to print only uniques.
Here's my code:
def uniquePalindromes(string):
x=string.split()
for i in x:
k=[]
rev= ''.join(reversed(i))
if i.casefold() == rev.casefold():
k.append(i.casefold())
print(set(k))
else:
return
I've tried to run this line
print( uniquePalindromes('Hanah asked Sarah but Sarah refused') )
The expected output should be ['hanah','sarah'] but its returning only {'hanah'} as the output. Please help.
Your logic is sound, and your function is mostly doing what you want it to. Part of the issue is how you're returning things - all you're doing is printing the set of each individual word. For example, when I take your existing code and do this:
>>> print(uniquePalindromes('Hannah Hannah Alomomola Girafarig Yes Nah, Chansey Goldeen Need log'))
{'hannah'}
{'alomomola'}
{'girafarig'}
None
hannah, alomomola, and girafarig are the palindromes I would expect to see, but they're not given in the format I expect. For one, they're being printed, instead of returned, and for two, that's happening one-by-one.
And the function is returning None, and you're trying to print that. This is not what we want.
Here's a fixed version of your function:
def uniquePalindromes(string):
x=string.split()
k = [] # note how we put it *outside* the loop, so it persists across each iteration without being reset
for i in x:
rev= ''.join(reversed(i))
if i.casefold() == rev.casefold():
k.append(i.casefold())
# the print statement isn't what we want
# no need for an else statement - the loop will continue anyway
# now, once all elements have been visited, return the set of unique elements from k
return set(k)
now it returns roughly what you'd expect - a single set with multiple words, instead of printing multiple sets with one word each. Then, we can print that set.
>>> print(uniquePalindromes("Hannah asked Sarah but Sarah refused"))
{'hannah'}
>>> print(uniquePalindromes("Hannah and her friend Anna caught a Girafarig and named it hannaH"))
{'anna', 'hannah', 'girafarig', 'a'}
they are not gonna like me on here if I give you some tips. But try to divide the amount of characters (that aren't whitespace) into 2. If the amount on each side is not equivalent then you must be dealing with an odd amount of letters. That means that you should be able to traverse the palindrome going downwards from the middle and upwards from the middle, comparing those letters together and using the middle point as a "jump off" point. Hope this helps

working on code to see if the input car model is there in the collection provided... however only else block working

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

Entering a word and then searching through and array of words to find the word

I am trying to create a program which checks to see if words entered (when run) are in an array. I would like to use a loop for this.
I have created a list of words and tried a for loop however the code is proving to be erroneous.
def Mylist():
Mylist= [Toyota,BMW,Pontiac,Cadillac,Ford,Opel]
Search=input("Enter a word")
Mylist[1]="Toyota"
for loop in range (1,6):
if Mylist[loop]==Search:
print("found")
break
I have repeated line 4 for the other car manufacturers.
TypeError: 'function' object does not support item assignment
First, here some recommendations to start:
Indentation in Python is IMPORTANT, be careful to have the right indentation. You must take special care when posting code here in SO so your code does not look like complete gibberish.
You should read Naming conventions. TL;DR we use snake_case for naming functions and variables.
If you are not using an IDE (such as PyCharm) to program, or something intelligent that shows the information on functions, you should always check out the documentation (it is beautiful).
Check out the difference between "Toyota" and Toyota. The first one has quotes, it is a string (i.e. chain of characters), it is a primitive type such as integer and boolean; the second is a token that is to be evaluated, it has to be defined before, such as variables, functions and classes.
Search in the docs if there is an in-built function that already does the job you want.
Check out return values in functions. Functions evaluate to None when you do not explicit a return value.
Now to your question. As some people pointed out, there is the in keyword that does exactly what you want.
CAR_BRANDS= ["Toyota", "BMW", "Pontiac", "Cadillac", "Ford","Opel"]
def check_car():
word = input("Enter a word: ")
if word in CAR_BRANDS:
print("found")
return True
print("not found")
return False
If you don't care about the print you can just do return word in CAR_BRANDS
If you actually want to challenge yourself to write the logic, you were right in choosing a for-loop to iterate over the list.
Index in Python starts from 0, and that range does not give you all the indexes to iterate over your list, you are missing the 0 index. Also, we don't like magic numbers, instead of hard-coding the length of your list of car brands, better compute the length!
for i in range(len(CAR_BRANDS)):
if CAR_BRANDS[i] == word:
print("found")
But even better you can directly iterate over the items in your list, no need to do the range, which will give you something like:
CAR_BRANDS= ["Toyota", "BMW", "Pontiac", "Cadillac", "Ford","Opel"]
def check_car():
word = input("Enter a word: ")
for brand in CAR_BRANDS:
if brand == word:
print("found")
return True
print("not found")
return False
If you have any more questions, do not hesitate! Happy coding.

Python for loops: applying a value to one index and another one to the other indexes

I am trying to create a program that will allow a game reviewer to input what categories the game falls under, it should then print the appropriate category with a checkbox, and the other categories with a blank box.
I have managed to write a for loop that prints out the correct category with the checkbox, but am struggling to loop through the rest of the values to print them with a blank box.
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
print ("===[ Audience: ]===")
for i in audience_list: #cycles through the list of audience options
if i == audience_list[audience-1]: #for the audience option that was selected, print it with a check box
print ("%s %s" % (yes, audience_list[audience-1]))
else: #for the audience options weren't selected, print them with a blank checkbox
print ("%s %s" % (no, audience_list))
Is there a way for me to print every index other than the one that has been assigned to the 'audience' variable?
I'm using Python 3.2.3.
Just print i! If you print audience_list, you will output the whole list of every element; whereas i is the one you are currently checking.
for i in audience_list:
if i == audience_list[audience-1]:
print ("%s %s" % (yes, audience_list[audience-1]))
else:
print ("%s %s" % (no, i))
and a test (having entered 3) gives a neat output of:
☐ Kids
☐ Everyone
☑ Casual Players
☐ Pro Players
Consider enumerating the list items:
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
choice = 3 # Casual.
for (index, name) in enumerate(audience_list, start=1):
if index == choice:
print("[X] " + name)
else:
print("[ ] " + name)
Output:
[ ] Kids
[ ] Everyone
[X] Casual Players
[ ] Pro Players
I'm going to answer this because I feel the other answers haven't answered your underlying question.
Here's the code I propose:
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
selection = audience_list[audience-1]
print ("===[ Audience: ]===")
for option in audience_list: #cycles through the list of audience options
print ("%s %s" % (yes if option == selection else no, option))
There are two major changes here.
First, I created the variable selection, outside of your for loop. This cleans up your loop and is closer to what you're doing. You don't care about the number, you care about what the user selected.
Second, I put the if part of your for loop into the print statement. This is to highlight something important: the only difference you want in each iteration of your loop is whether or not the box is checked. Either way, you want to print the element of audience_list. This print statement shows that. You either print an empty box or a checked one, and either way, you print the element.
Note that some confusion may have come from your for i..., because typically an i like that is an int. Consequently, I changed my for loop iterator to be named option, which is much more clearly a string.
I think your main question gets addressed by this. You could have printed audience_list[audience-1] in both your yes and no lines, or you could more simply have printed i in both of your lines. (Or, as per Joe's code at this time, you could have made one audience_list[audience-1] and one i, since as it's written, they're both the same.) But since you're looping through all the options, other than the box, you should print the same option string, whether it's selected or not.
Note, in my comments with Joe, I mentioned that you could squeeze the for loop and below all on to one line. Then your code would look like this:
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
selection = audience_list[audience-1]
print ("===[ Audience: ]===")
_ = list(map(lambda o: print ( "%s %s" % (yes if o == selection else no, o)), audience_list))
This is logically equivalent, but a lot harder to read, so while it's fun to do, I wouldn't recommend it. (Briefly: map takes a function, in this case, the unnamed lambda function, and runs every member of the iterator audience_list through that function. list is necessary to make the map object actually do the processing, and the _ = is just to tell any other readers that we know we're throwing away the list.)
As Joe mentions, there is a less ugly way to do it that doesn't require mapping. The last line could be:
_ = [print ( "%s %s" % (yes if o == selection else no, o)) for o in audience_list]
This is slightly less confusing, since it removes the list(map( noise.
These are pretty much all functionally equivalent. And while it's fun to toss things in to a single line, don't get lost in that. Readability, maintainability and the ability to easily debug are the most critical.

Creating a function that creates two lists in Python 3

I am trying to create a function, getStocks, that gets from the user two lists, one containing the list of stock names and the second containing the list of stock prices. This should be done in a loop such that it keeps on getting a stock name and price until the user enters the string 'done' as a stock name. The function should return both lists. My main issues are figuring out what my parameters are, how to continuously take in the name and price, and what type of loop I should be using. I am very new to programming so any help would be appreciated. I believe I'm close but I am unsure where my errors are.
def getStocks(name,price):
stockNames = []
stockPrices = []
i = 0
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while i < len(stockNames):
stockNames.append(name)
stockPrices.append(price)
i += 1
else:
if name = done
return stockNames
return stockPrices
Your question is a bit unclear but some things off the bat, you cant have two return lines, once you hit the first, it leaves the function. Instead you'do write something like
return (stockNames, stockPrices)
Secondly while loops dont have an else, so you'd actually set up your while loop, then setup an if statement at the beginning to check if the string is 'done', then act accordingly. Break will get you out of your last while loop, even though it looks like it's associated with the if. So something like this:
while i < len(stockNames):
if name.upper() == 'DONE':
break
else:
stockNames.append(name)
stockPrices.append(price)
i += 1
Also you have to use == (comparison) instead of = (assignment) when you check your name = done. And dont forget done is a string, so it needs to be in quotations, and I used .upper() to make the input all caps to cover if its lower case or uppercase.
If you can clear up your question a little bit, I can update this answer to include everything put together. I'm not quite understanding why you want to input a list and then also take user input, unless you're appending to that list, at which point you'd want to put the whole thing in a while loop maybe.
Update:
Based on your comment, you could do something like this and enclose the whole thing in a while loop. This takes the incoming two lists (assuming you made a master list somewhere) and sends them both into the getStocks function, where someone can keep appending to the pre-existing list, and then when they type done or DONE or DoNe (doesn't matter since you use .upper() to make the input capitalized) you break out of your while loop and return the updated lists:
def getStocks(name, price):
stockNames = name
stockPrices = price
while 1:
inputName = str(input("What is the name of the stock?"))
inputPrice = int(input("what is the price of that stock?"))
if name.upper() != 'DONE':
stockNames.append(inputName)
stockPrices.append(inputPrice)
else:
break
return (stockNames, stockPrices)
But really, depending on the rest of the structure, you might want to make a dictionary instead of having 2 separate lists, that way everything stays in key:value pairs, so instead of having to check index 0 on both and hoping they didn't get shifted by some rogue function, you'd have the key:value pair of "stock_x":48 always together.

Resources