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")
Related
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)
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.
I'm making a guessing game or computer science in school where the number to guess is seven. I have tried using while loops and if elif else statements but it doesn't seem to want to make a conditional loop My code is as follows:
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
else:
print("Well done")
Any help would be appreciated thanks. I need it in about a week and a half's time.
If you're trying to allow your player to continuously guess the input needs to be at the top of the while loop, before the conditional-branch
while(True):
guess = input("Make a guess: ")
if(guess == 7):
print(guess,"was correct!")
break
else:
print("Nope. Guess again.")
Of course, you could make it more interesting in a variety of ways.
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
guess=int(input("Guess a number!"))
else:
print("Well done")
var=0 #set var to 0, to exit the loop
Try this. You need to exit the loop, and to do that, var needs to be set to 0.
I am a beginner programmer. I want to create a game where user input affects the course of the game. I am kind of stuck on the very beginning.
def displayIntro():
print("You wake up in your bed and realize today is the day your are going to your friends house.")
print("You realize you can go back to sleep still and make it ontime.")
def wakeUp():
sleepLimit = 0
choice = input("Do you 1: Go back to sleep or 2: Get up ")
for i in range(3):
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
else:
print("Invalid")
def whichWay():
print("After your shower, you decide to plan your route.")
print("Do you take 1: The scenic route or 2: The quick route")
choice = input()
if choice == 1:
print("scenic route")
if choice == 2:
print("quick route")
displayIntro()
wakeUp()
i have a few bugs and I've tried to work them out on my own but I'm struggling.
1) I only want the player to be able to go back to sleep 3 times and on the third i want a message to appear and another function to run (havent made yet).
2) if the player decides to wake up i want whichWay() to run and it does but instead of exiting that for loop it goes right back to that loop and asks if the player wants to wake up again i have no idea how to fix this.
3) is there a better way i can go about making a game like this?
Thank you for your time and hopefully your answers.
The code below should work.
1. I moved the line 'choice = input("Do you 1: Go back to sleep or 2: Get up ")' into the for loop.
2. I added a break statement at the end of the elif block.
def wakeUp():
sleepLimit = 0
for i in range(3):
choice = input("Do you 1: Go back to sleep or 2: Get up ")
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
break
else:
print("Invalid")
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))