Random/ Loop challenge - python-3.x

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))

Related

trying to get the "print("Which will you choose?")" to go to a new set of choices which will lead to other choices

The assignment is to create a text based game. The goal of this game is to open the locked door inner to access the rest of the house. When the door has been unlocked the player can return to the entrance room and open the door to the rest of the house.
in each room (the pantry and the kitchen) there are a set of locks of which you must turn to the corect postions to unlock the central door).
Now i think im on the right track however, as the question states, im stuck on trying to get teh final part of the ##if option == "1":## to get to a set of choices.
Here is what i got..im not looking for answers just help to be lead in the right direction.
do i define a new set of functions like #def choices():#, then list the available options?
import random
import time
def displayIntro():
print("Welcome to the")
time.sleep (1)
print("Dungeon of Doom")
print()
time.sleep (1.5)
displayIntro()
#need to defin the path choices and what they lead to# also need to make sure it validates the inputs so no errors is user inputs a false input#
def choosePaths():
path = ""
while path != "1" and path != "2" and path != "3":
path = input("Which path will you choose? (1,2 or 3): ")
return path
def checkPath():
print("You head down the hallway into the pantry.")
time.sleep(2)
print("")
time.sleep(2)
print("")
print()
time.sleep(2)
def menu():
print('Choose your option')
time.sleep (1)
print("[1] Enter The Dungeon")
print("[2] Run away.")
menu()
option = ""
while option != "1" and option != "2":
option = input("Enter The temple or run away? (1 or 2): ")
option
if option == "1":
print("You step inside the ominous and dank dungeon.")
time.sleep (3)
print("as you enter the dungeon you hear a mysterious whisper in your ear")
time.sleep (3)
print("the voice says that you may not leave until you find the treasure within the central hall of the dungeon.")
time.sleep (3)
print("You turn around as see that the door behind you has magically disappeared.")
time.sleep (3)
print("You begin to look around the room")
time.sleep (3)
print("you see three hallways, one to the left, one to the right and one down the center.")
time.sleep (3)
print("The one on the right looks like it leads you towards what may be the kitchen")
time.sleep (3)
print("the other on the left may lead to the pantry")
time.sleep (3)
print("the very center hallway leads to what looks like the central hall.")
time.sleep (3)
print("Which will you choose?")
if option == "2":
print("You have left the Dungeon of Doom")

Is there a way read the random printed?

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")

Writing an ATM script - how do I get it to loop back out to the user options? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Still a beginner with Python. 7 Weeks into an 8 week course. My assignment was to polish my previous assignment. What I'm trying to add is not required, but I think it would be good practice to always aim for the best UI possible. I currently have a functional ATM script that works fine, once, then it must be restarted to use one of the other functions. What I want to do is somehow call the user_options dictionary I created to prompt the user to see if they want to perform another task while the ATM program is still running.
To clarify, I would like the program to be able to start, prompt the user, run the function the user selects, then loop back out to the prompt for another input.
If I change the user_options dict to a function, I don't know how to do it. Sorry for rambling, anyway, here is my code:
import sys
account_balance = float(500.25)
# defines theprintbalance function
def balance():
print("Your current balance:\n" + str(account_balance))
#defines the deposit function
def deposit():
global account_balance
#input paramaters for deposit
deposit_amount = input("How much would you like to deposit today?\n")
#modifies account balance with deposit ammount
account_balance += float(deposit_amount)
#prints the deposit amount and current blanace
print("Deposit was $" + str('%.2f' % float(deposit_amount)) + ", current
balance is $" + str(account_balance))
#defines withdrawal function
def withdrawal():
global account_balance
#input paramaters for withdrawal
withdrawal_amount = input("How much would you like to withdraw today?\n")
#if statement for withdrawal amount that exceeds balance
if float(withdrawal_amount) > account_balance:
print("$" + str('%.2f' % float(withdrawal_amount)) + " is greater than
your account balance of $" + str('%.2f' % float(account_balance)))
#restarts the withdrawl
print('Please enter an amount less than or equal to your current balance
for withdrawal')
withdrawal()
#else statement for successful withdrawal
else:
account_balance -= float(withdrawal_amount)
print("Withdrawal amount was $" + str('%.2f' % float(withdrawal_amount))
+ ", current balance is $" + str('%.2f' % float(account_balance)))
#defines quit function
def quit():
#prints quit message
print("Thank you for banking with us.")
#creates user input dict and removes previously used if/else loop
user_options = input("What would you like to do? (B)alance, (W)ithdrawal,
(D)eposit, (Q)uit\n")
options = {'B': balance,
'b': balance,
'W': withdrawal,
'w': withdrawal,
'D': deposit,
'd': deposit,
'Q': quit,
'q': quit,
}
options[user_options]()
If anyone has ideas or suggestions, that'd be great. This is PURELY a cosmetic thing that I want to add to the program. I don't think I'll be graded any differently on it. I just want to learn.
Create a while loop which would include all the options they have. Once they have completed whatever option they chose to do, break out of the loop and have send the user back the the beginning of the program where they can choose to exit the ATM or run another option.

How to get Python 3 to register a random word from a external file as a variable

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.

text-based adventure help in python 3.x

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")

Resources