Yes I know that there is already a post covering this, but when I read it, it didn't help so please don't mark this as a duplicate.
I want to write a program that asks the user if they want advice and if they input "No" or "no" I want it to repeat the question and if they input "Yes" or "yes" I want it to print the advice. I want it to include a while loop
I have tried to write it myself but I can't get it to work correctly.
Anyone know?
Code from the comment for 3.4 -
def doQuestion(question, advice):
reply = ("no")
while reply == "no":
print (question)
reply = input("Do you need some advice? ").lower()
if (reply == "yes"):
print ("Always listen to your IT teachers")
doQuestion("Do you want some advice?","Always listen to your IT teachers")
The following will keep on checking up on the user to see whether or not they need advice regarding a question:
def doTheyNeedAdvice(advice):
while raw_input("Do you need advice? ").lower() == "no":
pass
print (advice)
print "How old am I?"
doTheyNeedAdvice("I am old enough")
Related
I'm coding a text adventure in python.
In general: I want people to be able to make mistakes for putting in the wrong answers. If they not write a valid answer like "1" or "2" they should get send back with a loop until they put in a viable answer without breaking the whole code and to start all over again.
As mentioned in the title: I have a problem with consecutive if-query-loops (with elif else etc.) I do found a nice while-function for just one query. (here on stack overflow. THX for that so far)
But trying to implement it for consecutive if-querys leading to the next one is not working.
The first if-query works fine, but after going to the second one, when writing gibberish for example, instead of looping back to the second question I get send to the first(!) one again...
I tried to put "else: -continue..." to every(!) if-query, even with multiple "while True:" after each query.. but that resulting in infinty loops...
I'm a beginner with python, but heard that maybe switch / case -functions might be working?
Still, is there maybe a more efficient way?
Thanks a lot for your time and effort! :-)
while True:
question1 = input("question1")
if question1 =="1":
print("Wrong")
break
elif question1 == "2":
print("Right, go on!!")
question2 = input("question2")
if question2 == "1":
print("Wrong")
break
elif question2 == "2":
print("Right, go on!!")
question3 = input("question3")
if question3 == "1":
print("wrong")
break
elif question3 == "2":
print("Right, go on!!")
quit()
else:
print("Use a valid answer!")
continue
Here's an idea of how I'd structure your program and what things you should look at and learn to properly implement what you want to do.
I'd recommend you use a state machine and putting all your logic into a dictionary (which later you could read from a json file, so you can create different adventures without having to modify the code at all)
The logic of your adventure is:
You are in question 1 and you have 3 possible answers:
1 -> Correct: Go to next question
2 -> Incorrect: Go back to first question
Anything else -> Repeat current question
Then you can mount each question with a nested dictionary structure, like this:
states = {
1: {
"Question": "The text of question 1",
"Answers": {
"1": 2, # Answer "1" will go to state 2
"2": 1, # Answer "2" will go to state 1
"Default": 1 # Anything else will stay in state 1
}
},
2: {
"Question": "The text of question 2",
"Answers": {
"2": 3, # Answer "2" will go to state 3
"1": 1, # Answer "1" will go to state 1
"Default": 2 # Anything else will stay in state 2
}
}
}
You can add more options to your dictionary, maybe you want the user to allow more answer for each question, and you can then put to which state each answer goes (maybe you don't want sequential questions, but more a graph with complex paths)
Now your main code will have a variable state that you can initialize to 1
state = 1
You can then access the information of this state by doing
states[state]
For example the question of the current state is
states[state]["Question"]
And the answers dictionary are in
states[state]["Answers"]
So if the user inputs an answer answer, you can get the appropriate response doing
states[state]["Answers"][answer]
This might look a bit complicated now for you, but try understanding dictionaries and how to structure your question and answers in them and you will see that your code then simplifies a lot, you just need to print the Question for the current state, read the answer and update the state according to the dictionary.
so you want something like
state = 1
while True:
# print current question
print(states[state]["Question"])
# ask the user an answer
answer = input("What is your answer? ")
# check if answer exist for the current state
if answer in states[state]["Answers"].keys():
# if it exist go to the state pointed by that answer
state = states[state]["Answers"][answer]
else:
# if it doesn't exist, go to the state pointed by default
state = states[state]["Answers"]["Default"]
You maybe want a final state that gives you a victory, so you can get a special state that when reached will print "You won" and exit the game
Try to understand the logic of this program and you will find that a combination of state machines and dictionaries will make your code very flexible and very easy to understand.
So basically, what I'm trying to do is to create a menu that allows me to modify the contents of a text file. It's supposed to look like this:
Question 1
I think I already know how to create the menu, as shown here:
print("User Management")
print("1.Add new record")
print("2.View all record")
print("3.Search record")
print("4.Exit")
option = int(input("Enter your choice: "))
if option == 1 :
The problem I have I have no idea how to correlate the options to the commands. For example, if I wanted to correlate this:
name = input("Please enter your name:")
email = input("Please enter your email address:")
f = open("user.txt","a")
f.write("\n"+name+","+email)
f.close()
print("Record added."))
to 1 so whenever I input 1 in the "Enter your choice" it allows me to add a name and email address to the text file, etc. Here's an example I can find:
Example
I have been told that using the if and elseif functions allows me to do that, but I have no idea how. I'm quite new to Python, so forgive me if I seem ignorant. Any help will be appreciated.
You're right in that using a conditional (the fancy technical term for if/elseif/else) is the way to do that. Assuming that the text you have included in your question is accurate, it's likely that you haven't indented the code that is meant to be in the if block.
Python uses indentation (that is, spaces or tabs) to indicate what code is within each control structure. So in your example, if you want to only execute the second block of text if option == 1 you would want:
print("User Management")
print("1.Add new record")
print("2.View all record")
print("3.Search record")
print("4.Exit")
option = int(input("Enter your choice: "))
if option == 1 :
name = input("Please enter your name:")
email = input("Please enter your email address:")
f = open("user.txt","a")
f.write("\n"+name+","+email)
f.close()
print("Record added."))
For more on using if and other control flow, see the tutorial here.
firmware = input("which image would you like to upload?")
if firmware == 1:
net_connect.send_config_set("wr")
net_connect.send_config_set(" copy tftp://cisco#10.36.50.60/s2t54-ipservicesk9-mz.SPA.152-1.SY6.bin bootdisk:")
print ("Press enter to confirm ")
# How can I send a enter command to the shell
Sorry I have adjusted the post but I have commented where I need to send the enter key I have already tried print("\n") and I have tried print(" "). Both do not work. Can someone please advise :)
You can do something like this:
input("Press the enter key to continue.. ")
Put this wherever you want to confirm or pause.
Am trying to create a quiz program in Python where the questions are stored in one txt file with the answers in another. The questions are set out in the text file as follows:
Which one of these is a percussion instrument?
A. Trumpet
B. Euphonium
C. Viola
D. Glockenspiel
The program pulls the questions out in random order and keeps score of the number of right answers.
I know how to open files, read from them and display the contents of the file on the screen, I even know now how to randomise the info in the file. However, as there are multiple lines involved AND another file to get the answer from, I have no idea where to start.
I would really appreciate any help you could offer me.
Feel free to ask questions if you need to clarify anything.
EDIT:
Ok, I have decided to change my idea a little, which might make it easier. Using a CSV file might be the better option. Here is what I have so far.
def Trivia():
score=0
myFile = open("farming.csv","r") # opens the CSV file and stores it in the array myFile
players = myFile.readlines() # reads the lines of the CSV file into the variable players
questionno=1
while questionno < 6:
for p in players:
data = p.split(",") #splits each cell of the CSV file into its parts
questions = data[0]
answera = data[1]
answerb = data[2]
answerc = data[3]
CorrectAnswer = data[4]
print("Question #",questionno)
print(questions) #prints the question and the 3 answers
time.sleep(0.5)
print(answera)
time.sleep(0.5)
print(answerb)
time.sleep(0.5)
print(answerc)
time.sleep(0.5)
answer = input("Answer? ") #asks the user for their answer
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
if answer == CorrectAnswer: #checks if the answer is correct and prints approptiate responses
print("That is the correct answer")
score=score+1
time.sleep(1)
else:
print("That is not the correct answer")
time.sleep(1)
print("Your current score is", score)
print("")
questionno = questionno+1
myFile.close()
My problem now is that I don't know how to get to the next question in the quiz. Using this format it keeps asking the same question. Any idea?
Thanks.
This question is two-fold: what to save, and how to save. Let's answer "how" first.
Seems like what you need is serialization, which is a fancy way of saying "saving data in a particular format". I would learn about pickle or json. This will allow you to save and load objects, so you could for instance save a class that represents a question.
And about what you save and not how you save it, I guess each answer should be saved along with a number of a question, then you can link between them - sort of like foreign keys in a DB.
Good luck!
I am not exactly 100 percent sure as yet I haven't run the program myself to check. But I think it could be the "While" module. It says while questionno is under six, do that question, and so when you add 1 to questionno it is still under 6 running the program over again. Change it too this
If questionno == 1:
.....
.....
.....
for next question in the quiz you'll need to just start it with
If questionno == 2:
.....
.....
.....
now write the 2nd quiz
I apologize for my earlier questions as they were vague and difficult to answer. I am still fairly new to programming and am still learning the ins and outs of it all. So please bear with me. Now to the background information. I am using python 3.3.0. I have it loaded onto the Eclipse IDE and that is what I am using to write the code and test it in.
Now to the question: I am trying to learn how to create and use dictionaries. As such my assignment is to create a price matching code that through user interface will not only be able to search through a dictionary for the items (which are the keys and the locations and prices which are the values associated with the keys.) So far I have created a user interface that will run through well enough without any errors however (at least within the IDE) When I run through and input all of the prompts the empty dictionary is not updated and as such I cannot then make a call into the dictionary for the earlier input.
I have the code I have written so far below, and would like if someone could tell me if I am doing things correctly. And if there are any better ways of going about this. I am still learning so more detailed explanations around code jargon would be useful.
print("let's Price match")
decition = input("Are you adding to the price match list?")
if decition == "yes":
pricematchlist = {"Snapple":["Tops",99]}
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = input("Now how much was the item")
int(price)
pricematchlist[item]=location,price
print(pricematchlist)
else:
pricematchlist = {"Snapple":["Tops",99]}
reply = input("Ok so you want to search up a previous price?")
if reply == "yes":
search = input("What was the item?")
pricematchlist.item(search)
These are a few minor changes. For dictionaries: you are using them correctly.
print("let's Price match")
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes":
# pricematchlist = {"Snapple":["Tops",99]}
# If this whole code block is called repeatedly, you don't want to reassign it
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = int(input("Now how much was the item"))
# int(price) does nothing with reassigning price
pricematchlist[item]=location,price
print(pricematchlist)
else:
reply = input("Ok so you want to search up a previous price?").lower()
if reply == "yes":
search = input("What was the item?")
print pricematchlist[search] # easier way of accessing a value