Thanks for reading my post. I'd be really grateful if someone can help me with my problem. I'm trying to add a rather simple thing to my code but keep getting issues.
Before the user is presented with the questions of the quiz I would like to to great them e.g. Welcome to the Quiz and then ask them their name and save it has a variable to use later in the code e.g. Well done Gary you score 5 out of 5.
Please if you can help I would be so happy. Thanks in advance.
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompts = [
"Which of these will help keep you safe when using a chat room or an internet forum?\n(A)Always tell your friends your password.\n(B)Use the same password for everything.\n(C)Change your password regularly.\n(D)Make your passwords easy to guess.\n\n",
"Who should you tell if something or someone on the internet upsets you?\n(A)Only your friends.\n(B)Only your bother or sister.\n(C)Nobody.\n(D)Your parents or a member of staff.\n\n",
"When is it safe to use a webcam?\n(A)You should never use a webcam.\n(B)When talking to people you know in the real world.\n(C)When talking to people you only know through the internet.\n(D)When talking to anyone.\n\n",
"What is cyber bullying?\n(A)When anyone uses the internet, a mobile, or other technology to deliberately upset someone.\n(B)When someone sends you an e-mail giving you the answers to your homework.\n(C)When someone disagrees with your opinion on an internet forum\n(D)When someone is nasty to a robot\n\n",
"How can you protect your computer from viruses?\n(A)Never click e-mail links or open attachments from people you don't know.\n(B)Always remember to log off when you are finished using the computer.\n(C)Do nothing - your computer will protect itself\n(D)Give it antibiotics.\n\n",
]
questions = [
Question(question_prompts[0], "C"),
Question(question_prompts[1], "D"),
Question(question_prompts[2], "B"),
Question(question_prompts[3], "A"),
Question(question_prompts[4], "A"),
]
def run_quiz(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("you got", score, "out of", len(questions))
if score == 5:
print("Well done you answered all the questions correctly")
if score == 4:
print("Well done you got most of the questions correctly")
if score == 3:
print("Not bad going. You answered most of the questions correctly")
if score <= 2:
print("Let's try doing the quiz again.")
run_quiz(questions)
Read the name from the user before calling run_quiz(questions) and pass the name as argument to the function. Inside the function, display the username along with score.
Here is the updated code.
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompts = [
"Which of these will help keep you safe when using a chat room or an internet forum?\n(A)Always tell your friends your password.\n(B)Use the same password for everything.\n(C)Change your password regularly.\n(D)Make your passwords easy to guess.\n\n",
"Who should you tell if something or someone on the internet upsets you?\n(A)Only your friends.\n(B)Only your bother or sister.\n(C)Nobody.\n(D)Your parents or a member of staff.\n\n",
"When is it safe to use a webcam?\n(A)You should never use a webcam.\n(B)When talking to people you know in the real world.\n(C)When talking to people you only know through the internet.\n(D)When talking to anyone.\n\n",
"What is cyber bullying?\n(A)When anyone uses the internet, a mobile, or other technology to deliberately upset someone.\n(B)When someone sends you an e-mail giving you the answers to your homework.\n(C)When someone disagrees with your opinion on an internet forum\n(D)When someone is nasty to a robot\n\n",
"How can you protect your computer from viruses?\n(A)Never click e-mail links or open attachments from people you don't know.\n(B)Always remember to log off when you are finished using the computer.\n(C)Do nothing - your computer will protect itself\n(D)Give it antibiotics.\n\n",
]
questions = [
Question(question_prompts[0], "C"),
Question(question_prompts[1], "D"),
Question(question_prompts[2], "B"),
Question(question_prompts[3], "A"),
Question(question_prompts[4], "A"),
]
def run_quiz(questions, user_name):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("Hey ", user_name, " you got", score, "out of", len(questions))
if score == 5:
print("Well done you answered all the questions correctly")
if score == 4:
print("Well done you got most of the questions correctly")
if score == 3:
print("Not bad going. You answered most of the questions correctly")
if score <= 2:
print("Let's try doing the quiz again.")
if __name__ == "__main__":
user_name = input("Welcome to the quiz.\nEnter your name:")
run_quiz(questions, user_name)
Related
Basic Python Chatbot
An Objective of the task is to create a Basic Python chatbot where any questions asked if the chatbot does not know the answer, it shows request the user to provide the answers. Once the answer is received, it should write that question and its answer it into the pandas dataframe. In the future, a similar question is asked, the chatbot should look into the pandas data frame and give the answer.
Purpose of creating the pandas data frame is that currently, I don't have any ready question and answer, so as time progress I will be adding the question and answer to pandas data frame one by one.
Blockquote
username = "User"
chatbotname = "<>"
chatbotnameknown = False
active = True
def saychatbot(text):
global username
global chatbotname
global chatbotnameknown
global active
if chatbotnameknown:
print(chatbotname + ": " + text)
else:
print("*: " + text)
def speak(user_entry):
global username
global chatbotname
global chatbotnameknown
global active
if user_entry == "Hello!" or user_entry == "hello":
saychatbot("Hi, " + username)
elif user_entry == "How are you?":
saychatbot("I'm fine. And you?")
reply = input("Your answer: ")
if reply == "Great":
saychatbot("I'm glad to hear that.")
else:
saychatbot("I didn't understand you.")
elif user_entry == "Bye":
active = False
else:
saychatbot("I didn't understand you.")
saychatbot("I am still learning, let me learn your language")
if input("Would you like to teach me your language, Say y/n ? ") == "y":
saychatbot("You know i am still infancy, so please teach me your language one question and its answer at a time so i will load it in my database!!")
print("Here I would like to record the question and its answer in Pandas data frame and use that data frame as input to answer the same question in future")
print("Is there any way to achieve it")
def OpenDiscussion():
global username
global chatbotname
global chatbotnameknown
global active
print("********Python - Do you know system can speak****************")
while active:
if chatbotnameknown:
speak(str(input(username + ": " + chatbotname + ", ")))
else:
speak(str(input(username + ": ")))
saychatbot("Bye.")
OpenDiscussion()
First, you can set up a data structure to store the <question, answer> data. In this case, a dictionary would be fine.
If you need use dataframe and add data, pandas.DataFrame.append method would help.
I am trying to set up a fighting game where it prints a question and you have to answer the question correctly to win the fight. But I a finding that I can't find a way to get the code t read the random question to be read thus meaning I can't get it to read the answer as correct.
I've tried making the random be separated into multiple variables but that didn't work. I haven't had much time to try anything else either.
import random
fights=("I run but never walk, I have a bed but never sleep", "What time
of day is the same fowards as it is backwards?", "3+2")
FIGHTS=random.choice(fights)
print(FIGHTS)
ans1="river"
ans2="noon"
ans3="5"
que1=input("What shall you say?\n")
if ans1=="I run but never walk, I have a bed but never sleep":
print("You won!")
elif ans2=="What time of day is the same fowards as it is backwards?":
print("You won!")
elif ans3=="3+2":
print("You won!")
else:
print("You lost...")
If you answer correctly it displays "You won!" and if you answer wrongly it displays "You lost..." but it can't read what is printed so it always displays "You lost..."
A good approach would be to store the questions and answers in a dictionary and use good variable names.
import random
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question = random.choice(tuple(fights.keys()))
print(question )
answer = input("What shall you say?\n")
if answer == fights[question]:
print("correct")
else:
print("wrong")
If you are not going to use this dictionary again, you can use fights.popitem() instead. Keep in mind that if using Python >= 3.7 popitem will always return the same key-value pair:
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question, correct_answer = fights.popitem()
print(question)
user_answer = input("What shall you say?\n")
if user_answer == correct_answer:
print("correct")
else:
print("wrong")
I'm a computer science student at secondary school currently struggling with a certain aspect of my NEA, we are permitted to get help with the code. The aim of the NEA is to create a game which can choose a random song and artist from an external file and then get the user to guess which song it is. The issue I have run into is when I run the program the random aspect of the code (The Song name and artist chosen from the external file) does not seem to be registered by the if statement. I cannot think of a better way to explain my issue, but if you run the code I believe you will see the issue I'm having. I have taken out most of the excess code that is not part of the problem to make it easier to understand because like I said before I am still a novice at this. I have looked around for a while now and cannot seem to find an answer. Any sort of help would be very much appreciated.
username = 'Player1'
password = 'Password'
userInput = input("What is your username? (Case Sensitive)\n")
if userInput == username:
userInput = input("What Is Your Password? (Case Sensitive)\n")
if userInput == password:
print(
"Welcome! In this game you need to guess each songs name after being given its first letter and its artist. Good luck!"
)
else:
print("That is the wrong password. Goodbye ;)")
exit()
else:
print("That is the wrong username. Goodbye ;)")
exit()
startgame = 'Start' 'start'
userInput1 = input("Click Any Button And Click Enter To Begin Game:")
if userInput1 == startgame: 'Start'
print("Welcome To The Game")
import random
Song = [line.strip() for line in open("Songnames.txt")] #Currently in the external file I have removed all of the other songs apart from H______ By Ed Sherran.
print(random.choice(Song))
userguess = input("Whats Your Answer?\n")
if userguess == ("Happier") and (random.choice(Song)) == "H______ By Ed Sherran": #The program will continue to return 'Incorrect'.
print("Nice One")
else:
print ("Incorrect")
Any sort of help would be very much appreciated , I have looked for a while on this site and others for an answer however if it seems I have missed an obvious answer I do apologise.
When I run the code it seems to work. (My Songnames.txt contains one line, H______ By Ed Sherran.)
Is it possible that your Songnames.txt contains at least one empty line? If so, filtering the empty lines might fix the problem:
Song = [line.strip() for line in open("Songnames.txt") if line.strip()]
A few other suggestions for your code:
startgame = 'Start' 'start'
userInput1 = input("Click Any Button And Click Enter To Begin Game:")
if userInput1 == startgame: 'Start'
print("Welcome To The Game")
This doesn't make sense. Besides the misleading prompt about buttons and clicks, the if userInput1 == startgame: 'Start' doesn't do anything, not even print start. And the game starts regardless of what the user enters.
The actual game has a few issues as well, most importantly for when you actually have multiple songs is the fact that you choose a random song twice. Given enough songs, these will almost always be two different songs, so the print will be utterly misleading. Better choose one song and assign it to a variable:
import random
songs = [line.strip() for line in open("Songnames.txt") if line.strip()]
computer_choice = random.choice(songs)
print(computer_choice)
userguess = input("Whats Your Answer?\n")
if userguess.lower() == computer_choice.lower():
print("Nice One")
else:
print("Incorrect")
I took the liberty to make the comparison case insensitive by comparing the lowercase versions of the user guess and the computer's choice.
First of all, I'm not a native speaker, so please excuse me if there are grammatical errors. :)
I'm a real greenhorn and just started to learn programming - i choose Python 3 as my first language. So please be lenient :)
I already tried to find an answer by myself, but i wasn't successful.
What is the better or more correct "style". Is there maybe a difference on runtime. Thank You!
Version 1:
def newUsername(db):
isUser = True
while isUser:
username = input('Set an username:...')
if not username:
pass
elif username in db:
print("This user already exists!")
else:
isUser = False
return username
Version 2:
def newUsername(db):
while True:
username = input('Set an username:...')
if not username:
pass
elif username in db:
print("This user already exists!")
else:
return username
The second version would be better.
This is better since you are not using an additional variable & also reducing an expression where you assign that variable with a value.
Thanks in advance for your answer(s). So, I just started learning Python, and was faced with a challenge that now is mind bugging. Here is the challenge:
Objective was to write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it's runs.
My solution:
# Program simulates fortune cookie.
# Displays one of five unique fortunes at random
"""
Fortunes:
* You will meet someone that will change your life today.
* Invest in lottery this week because you will win big.
* You will get a call from someone with great influence this week.
* Purchase chinese food as you will read a fortune that will come to pass.
* Good news about an inheritance will come shortly.
"""
# Steps:
# Display a Welcome message explaining what the Fortune cookie program is about, and how users can use it.
# Import random module to randomize the messages.
# Employ loop to repeat.
#Welcome
print("\t\t\n<<<Welcome to Your Fortune Cookie.>>>")
print("\t*To see what the Fortune Cookie Ginie has in store for you.")
print("\t*Ok, here we go...\n")
print(input("Press Enter to Reveal your Fortune: "))
#random module
import random
fortune1 = random.randint(1, 6)
#loop body
fortune1 < 1
while True:
print("You will meet someone that will change your life today.")
print(input(">>Press Enter again to Reveal another Fortune: "))
if fortune1 == 2:
print("Fortune: Invest in lottery this week because you will win big.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 3:
print("Fortune: You will get a call from someone of great influence this week.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 4:
print("Fortune: Purchase chinese food as you will read a fortune that will come to pass.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 4:
print("Fortune: Good news! An inheritance will come shortly.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 5:
print("Fortune: Aha! You will win something this weekend")
print(input(">>Press Enter again to Reveal another Fortune: "))
else:
print("Let's check again...")
fortune1 += 1
print("That's all your fortune")
Although I want to run it differently, but the program sort of ran. I guess my question is: is there another way i could've done this? Thanks again for your responses.
Another way to do it is have a list of the outputs, then randomly choose one output from the list with random.choice(list). Example:
import random
fortunes = ['fortune1', 'fortune2', 'fortune3']
while True:
input("Press enter to receive a fortune. ")
print(random.choice(fortunes))