Related
I have a little piece of code in Python where I'm trying to compare a user input to a specific element in an array. Here is the code:
movies = ["movie 1", "movie2", "movie3"];
answer = raw_input("What is your guess: ")
if answer == movies[1]
then print ("yes that is correct")
else:
print ("no that is incorrect")
I know the indentation above looks wrong becasue I typed it out in the text box and I'm new to this site as well as python.
I also know that I probably need to use some sort of conditional loop, maybe a while loop, but I'm having trouble finding where I can compare user input string value to a string value in my array. Any ideas how I might accomplish this?
Have fun with Python! I guess you are trying to make a loop which keeps receiving inputs from user to compare with the desired input until user types the correct input. If so, one way, it can be implemented as following (but think of adding a break condition, like input == "Bored" , to avoid infinite loop and hard stopping your code):
movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
answer = raw_input("What is your guess: ")
if answer == correctAnswer:
print("Yes, that is correct")
is_notCorrect = False
else:
print("No, that is incorrect")
In the code above, when is_notCorrect turns into False. At next condition checking, it will break condition, and done with the loop.
Your code has some issues
movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python
answer = raw_input("What is your guess: ")
# Need a colon here after if condition, new line, and indent.
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B>
if answer == movies[1]
then print ("yes that is correct") # No then in if-else statement in Python
else:
print ("no that is incorrect")
I'm working on a HW assignment where I create a fake club with entry questions. If any of the questions are answered with "no", then the person isn't allowed to join.
I've tried going back to the og lessons about lists and loops, but I can't find what I'm trying to do on there.
Here's my code so far.
# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
display = input('Hi! This is your application to The Aqua Project...')
display2 = input('Read the following questions and just type y or n')
# Weird list format...
user = [input('Are you at least 18 yrs old? '),
input('Can you work with other people? '),
input('Do you like animals? '),
input('Are you okay with getting dirty sometimes? ')]
# Here's the problem, I want to print 'sorry you cant join' once...
for i in range(4):
if user[i] != 'y':
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
i += 1
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
main()
When you put a 'n' for some questions it says you can join, but for others it says you can't join. I don't know why sometimes it says you can when you placed a no in the interview, it shouldn't.
The usual ways to do this are a for loop with a break and an else clause:
for answer in user:
if answer != 'y':
print('Sorry')
break
else:
print('Congratulations')
Or the any() function:
if any(answer != 'y' for answer in user):
print('Sorry')
else:
print('Congratulations')
If one "no" means decline, you can add break to exit the loop after print decline info. Just like:
for i in range(4):
if user[i] != 'y':
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
# i += 1 # <<<<<<<<<<<<<<<<<< this code may be not needed here
break # <<<<<<<<<<<<<<<<<< where to add break
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
or you can use a variable to indicate whether to decline, just like:
toDecline = False
for i in range(4):
if user[i] != 'y':
toDecline = True
if toDecline:
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
There are a few ways to do this:
Use a flag variable and just output at the end. (Slightly inefficient if the first response is a no)
Use a flag variable and a while loop to exit as soon as the user responds with no. (Can be slightly confusing)
Use the builtin any method. (Can be confusing, not recommended)
flag = True
for i in range(4):
if user[i] != 'y':
flag = False # User has answered no to something, set the flag to false
if flag: # User has answered yes to everything
# <do your `yes` output>
else: # User has answered no to something
# <do your `no` output>
there are some small points in your code that need to be changed:
# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
display = input('Hi! This is your application to The Aqua Project...')
display2 = input('Read the following questions and just type y or n')
# Weird list format...
user = [input('Are you at least 18 yrs old? '),
input('Can you work with other people? '),
input('Do you like animals? '),
input('Are you okay with getting dirty sometimes? ')]
# you define a variable inside function main
# and assign a list to it
# this variable will not be visible outside
# you should just return it
return user
# Here's the problem, I want to print 'sorry you cant join' once...
# call your function before you test the answer
# and assign the the result of the function to a
# variable you can use in your check
user= main()
# define a flag variabe to
# see if the answers are ok according your check
ok= True
for i in range(4):
if user[i].lower()[:1] != 'y':
# you could also use your original code
# in the check. The code above is an example
# how you could make sure the user can enter
# upper/lower case letters and also "yes"
# and "y" [:1] cuts off 1 character
# if the string is non-empty, otherwise it
# returns an empty string
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
i += 1
# memorize that some question wasn't ok
ok= False
# I guess here you might want to exit the loop?
# so use a break, otherwise the other answers
# would be checked as well and the message
# output several times per user in some cases
break
if ok:
# this code here doesn't belong in the loop body
# I guess. It should be executed after all questions
# have been checked positive (which is only known
# after the loop has been executed)
# So here we are sure the answers were yes, because
# otherwise we would have set ok to False
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at TheAquaProject.com')
justToShowInCMD = input('')
# if you call your function here, you can't check
# the result of the input() calls because
# by the time you check it it has not been entered
I would suggest storing your questions in a list and using a for loop to ask them. Store the user's response to another list and check if there is any "n" in this list. See code below:
questions = ["Are you at least 18 yrs old?", "Can you work with other people?", "Do you like animals?", "Are you okay with getting dirty sometimes?"]
answers = list()
for question in questions:
user_answer = input(f"[y/n] {question}: ").lower()
answers.append(user_answer)
if "n" in answers:
print("Sorry, you can't join our club.")
else:
print("Congrats! You are in!!")
# you can print your desired messages as well.
Assuming you are iterating 4 times (using range(4))based on the length of user, what you can simple do is the following:
if 'n' or 'no' in user:
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
You can modify the if condition to cater to other forms of negative answers like 'N' or 'No'. You don't need to iterate over user.
Comments on OP main():
A key point of programming, is code use efficiency.
Don't repeatedly call functions (e.g. input and print) when not necessary.
There are several ways your problem can be solved.
The other answers focus on your original user list, complete with repeatedly calling input
Once user executes, it essentially becomes a list of y and or n values, which you then unpack with a loop to check the values.
Another problem with the user list method, is it requires all of the questions to be answered, prior to disqualification. What if there were 40 questions? I'd be annoyed.
Incidentally, a list can be unpacked as follows: for value in user:. There is no need to address the list by index with python.
Updated main() implementation:
def print_list(values: list):
"""Print the values of a list"""
for value in values:
print(value)
def main():
"""Iterate through a questionnaire"""
# Variables at the top
intro = ['Hi! This is your application to The Aqua Project...',
'Read the following questions and just type y or n']
questions = ['Are you at least 18 yrs old? ',
'Can you work with other people? ',
'Do you like animals? ',
'Are you okay with getting dirty sometimes? ']
final = ['\nCongratulations, you have met all of our requirements!',
'We will send an email soon to discuss when our team',
'will meet up to help save some animals!',
'In the meantime, visit our website at www.TheAquaProject.com']
print_list(intro)
for i, question in enumerate(questions, start=1):
response = input(question)
if response == 'n': # can be replaced with != 'y'
print("Sorry, you can't join the club!")
break
if i == len(questions):
print_list(final)
Comments on updated main():
Instead of calling print a lot, store the text in a list and then call the print_list function to do the printing.
Keep custom functions separate
Custom functions should perform one function
values: list this is a type hint, which tells what data type the values parameter of print_list should be.
Annotations
"""""": use docstrings
Documenting Python Code: A Complete Guide
Double space between functions: How to Write Beautiful Python Code With PEP 8
main(): Defining Main Functions in Python
questions is obvious, it's just the questions from user, as a list without calling input
unpack questions with a for-loop and use the built-in function: enumerate.
There are many Built-in Functions
i goes with enumerate to count.
Other languages create a dummy variable, like count = 0, then use count+=1 to track loop iteration; this is considered not pythonic. Python uses enumerate, but only if you need a count for implementing something else.
if condition checks if response is n
If the if condition evaluates as True (e.g. when response = n, n == n is True), the user gets the sorry message, break, ends the loop, and the questionnaire is complete.
There are no nicities here, the function does not check to make certain a user enters y, it only checks for n. That wasn't in the scope of the question.
The start parameter of enumerate is set to 1. If all the questions are answered, i=4 and len(questions)=4 so i == len(questions) evaluates as True and the user gets the congratulations message.
len(questions) is used instead of 4, because it's a bad idea to hardcode in values like that, because then you have to remember you've done so. What if the number of questions changes? Then your if condition is broken.
Resources:
I'm not affiliated with RealPython, but they are a great source of incredibly in depth tutorials.
Lists and Tuples in Python
Basic Data Types in Python
Im using a dictionary in my code and comparing the user's input to it, but when the user input nothing and just hits enter the program falls over and gives me a key error. I tried to use 'Try and Except' but that way the the program loops to the beginning which i dont want, i want to keep the program in the sub loop until the user inputs something that is within the boundary.
ftablet=open("tablet.txt").readlines() devicelist=["phone","tablet"]
dtablet = {}
for line in ftablet:
(key,val) = line.split(":")
dtablet[str(key)] = val.strip(",")
while True:
counter=0
device=""
while device not in (devicelist):
device=input(What is your device?: ").lower().replace(" ","")
print()
if device == "tablet":
usermodel=""
while usermodel != (dtablet["phonemodels"]):
print(dtablet["modelquestion"])
usermodel=input("Enter MODEL Here: ").lower().replace(" ","")
if usermodel in (dtablet["phonemodels"]):
name=""
while name != (dtablet[usermodel]):
print(dtablet["namequestion"])
print("Enter any of these : ",(dtablet[model]))
name=input("Enter NAME Here: ").upper().replace(" ","")
if name in (dtablet[usermodel]):
storage=""
while storage != (dtablet[name]):
print(dtablet["storagequestion"])
print("Enter any of these : ",(dtablet[name]))
storage=input("Enter STORAGE Here: ").upper().replace(" ","")
if storage in (dtablet[name]):
problem=input("What is the PROBLEM with your tablet?\nEnter Here: ").upper()
print()
for word in problem.split():
if word in (dtablet[storage]):
print(dtablet[word])
print("Thanks for using my troubleshooting program")
counter=1
if counter==0:
print("We dont have your keyword in out database")
else:
print("Sorry! We do not have that device in out database please choose from the ones listed above.")
This is My Text file that i converted into a dictionary which is called 'dtablet'.
modelquestion:What is the Model of your Tablet?
namequestion:What is the Name of your Tablet?
storagequestion:What is the STORAGE of your Tablet?
problemquestion:What is the PROBLEM with your Tablet?
phonemodels:apple,samsung,sony
apple:IPAD1,IPAD2,IPAD3
samsung:TAB1,TAB2,TAB3
sony:XPERIAZ2,XPERIAZ3,XPERIAZ4
IPAD1:16GB,32GB,64GB
IPAD2:16GB,32GB,64GB
IPAD3:16GB,32GB,64GB
TAB1:16GB,32GB,64GB
TAB2:16GB,32GB,64GB
TAB3:16GB,32GB,64GB
XPERIAZ1:16GB,32GB,64GB
XPERIAZ2:16GB,32GB,64GB
XPERIAZ3:16GB,32GB,64GB
16GB:cracked,broken
32GB:cracked,broken
64GB:cracked,broken
CRACKED:Problem = Cracked Solution = Take your phone to the repair
shop
BROKEN:Problem = Broken Solution = Take your phone to the repair shop
You have both
dtablet[model] # the key is the model variable
and
dtablet["model"] # the key is the "model" string
in your code, is this intentional?
If a user presses 'enter' then model will be an empty string, and this expression:
model in dtablet[model]
will always be true if dtablet[model] is a string.
Your issue is that you haven't included quotation marks around the key "model". This means that it wouldn't locate it anyway.
Also, why don't you just keep it to one loop? It'd be far more efficient.
First, you don't have a "model" key in your dictionary. You can print out dtablet.keys() and find if there is "model" in there. If not, then dtablet["model"] will 100% returns a KeyError.
Second, when you type while model != (dtablet["model"]):, since model is an empty string and if dtablet["model"] is a string then it will not go inside the while loop because an empty string is always a substring of any string.
You do realise that the while loop has both a break option and a continue option?
If you "want to keep the program in the sub loop until the user inputs something that is within the boundary" test and continue if the input was not what you were looking for.
Just to start off, I'm very much just a beginner. Much of what I know, I've learned over the past two days from the internet. Now on to the problem.
I'm working on a project where the goal is to develop a text based trivia game in python. I'm using an sqlite3 database to store the information for the questions. The database layout consists of three columns with the first containing an ID number, the second containing a text string with the question and answer choices, and the third column containing the answer for it's respective question.
I can get the list to be created and pull blocks of information off of it easily, but the problem comes when I need to pull one row at a time. For maximum clarity, here's my code in full:
#imports necessary SQL connection files
import sqlite3
import sys
#Data to form the Question table
info = (
("Who invented the Golden Meme? A:Copericus B:John Cena C:Aristotle D:Shie Lebeouf", "C"),
("What is the best chip flavor? A:Sour Cream & Onion B:Salt & Vinegar C:Barbecue D:Moldy", "B"),
("Who will be prisident in 2017? A:Donald Trump B:Bernie Sanders C:Hillary Clinton D:Ben Carson", "D"),
("Why? A:Becase he's smart and well educated B:Because he's a doctor C:Because once you go black you never go back D:Because my IQ is less than 30", "C")
)
#Connects to the SQL database
con = sqlite3.connect('Questions.db')
cur = con.cursor()
#Deletes the Questions table if it already exists, then creates a new one containing all the data
with con:
cur.execute('''DROP TABLE IF EXISTS Questions''')
cur.execute('''CREATE TABLE Questions(ID INTEGER PRIMARY KEY, question TEXT, answer TEXT)''')
cur.executemany('''INSERT INTO Questions(question, answer) VALUES(?, ?)''', info)
con.commit()
#Prints instructions
def instructions():
print()
print("INSTRUCTIONS: When a question is displayed, type the letter that corresponds to the desired answer choice. Type using capital letters only. If you answer a question wrong, you will recieve a Failure message and the game will end. If you answer all questions correctly, you win.")
print()
print()
#Displays which question the player is on
def counter():
global n
print("Question#", n)
n = n+1
nextQuestion()
#Displays the next question and recieves the players answer choice
def nextQuestion():
cur.execute('''SELECT question FROM Questions''')
Q = cur.fetchone()
if Q == None:
print()
print("Victory!")
print()
return False;
else:
print (Q)
playerAnswer = str(input("Your Answer: "))
answerValidation(playerAnswer)
#Determines is the answer is correct and, if so, restarts the process
def answerValidation(playerAnswer):
cur.execute('''SELECT answer FROM Questions''')
B = cur.fetchone()
if playerAnswer == B:
print()
print("Correct!")
print()
counter()
else:
print()
print ("You Failed!")
print(B)
return False
n = 1
instructions()
counter()
The problem is that I can print the 1st question, but not any question after that. I was under the impression that cur.fetchone() was suppose to fetch the current line row and then move on to the next one, but when the code runs through for a second pass it just reprints the first question.
This is the section specifically pertaining to that problem.
def nextQuestion():
cur.execute('''SELECT question FROM Questions''')
Q = cur.fetchone()
if Q == None:
print()
print("Victory!")
print()
return False;
else:
print (Q)
There is also a second problem. I'm also using the cur.fetchone() system to pull up the corresponding answer. It does fetch the correct answer, although probably just the first one as well, but the answer it fetches is still in the same format it was in the table. I put in a print B line to see what answer it was giving me and the result was ('C',). I think this is the reason whatever answer I put in always ends up false. Even if I put in C, the correct answer, it still counts it incorrect, most likely because the answer it pulled from the table has those apostrophes, parentheses, and comas in it.
If I change the code so that playerAnswer in ['C','c']: it will count the answer C correct and run back through the program pulling up the first question again.
Code pertaining to answer problem:
playerAnswer = str(input("Your Answer: "))
answerValidation(playerAnswer)
#Determines is the answer is correct and, if so, restarts the process
def answerValidation(playerAnswer):
cur.execute('''SELECT answer FROM Questions''')
B = cur.fetchone()
if playerAnswer in ['C','c']:
print()
print("Correct!")
print()
counter()
else:
print()
print ("You Failed!")
print(B)
return False
To sum it up, three main problems:
I can't get the program to print one question at a time and proceed to the next question only if the correct answer is given.
I can't get the program to accept the correct answer that corresponds to it's respective question.
I can't get the program to print the question and answer text outside of its stored format of ('X',)
Any solutions, ideas, or help would be much appreciated.
It should also be noted that I designed the program to go through the questions in order (mostly because I thought it would be easier), but it does not have to work this way. If anyone can offer a solution that would fix the above problems, but chooses questions at random, I would very much appreciate that as well. It just has to be scalable and not display a question more than once.
About your questions:
1./2. fetchone() returns the next row of the current query.
For each question, you start a new query. Therefore your one fetchone()
call returns always the first question.
You should also get the question and the corresponding answer in one query:
SELECT question, answer FROM questions. The way of two independent
queries works only if you query/use the question ID.
3.
fetchone() returns the whole row as a tuple. To access the first field use an
index:
cur.execute('''SELECT answer FROM Questions''')
Q = cur.fetchone()
answer = Q[0]
Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.