How would you create a option to retry in Python? - python-2.7

I'm a little confused on how to allow the user to retry entering something in Python. I created an example code bellow. I want it so if the user types a invalid answer other than 1 or 2 it allows them to try again.
import sys
def start():
print "Hello whats your name?"
username = raw_input("> ")
print "Okay, welcome to the game %s" % username
print "Do you want to hear the background of the game?"
print "1. Yes"
print "2. No"
background = raw_input("> ")
if background == "1":
print "Background goes here."
elif background == "2":
print "Background skipped"
start()
How would I incorporate a try again option into this example? Thanks!

Use a while loop:
def start():
print "Hello whats your name?"
username = raw_input("> ")
print "Okay, welcome to the game %s" % username
print "Do you want to hear the background of the game?"
print "1. Yes"
print "2. No"
while True: # Repeat the following block of code infinitely
background = raw_input("> ")
if background == "1":
print "Background goes here."
break # Break out of loop if we get valid input
elif background == "2":
print "Background skipped"
break # Break out of loop if we get valid input
else:
print "Invalid input. Please enter either '1' or '2'" # From here, program jumps back to the beginning of the loop
start()

Related

Trying to Create a basic Text Based Game in Python. How can I implement an if loop around "Spear" without nesting

I am trying to implement a loop around the option of having the spear or not.
With the spear, the hero should kill the bear. Without the spear, he should be eaten.
Originally, I set spear to False, and then changed it to TRUE when the hero picked up the spear. However, when looping back to bear_room(), the value of spear is reset to FALSE.
Is there any way to get around this without having to nest 2 if functions?
if not is there a cleaner implementation of the second if loop?
I attempted using if "true" and "true" and "if true and false" to determine whether the spear is held by the hero or not. Right now this does not work. However, the code still runs as is.
Here is the code:
from sys import exit
def dead(why):
print why, "good Job!"
exit(0)
def bear_room():
print """In front of you is a big bear. It stares at you. You notice a door behind the bear. To the side of the bear you see a spear propped up against the wall. What do you do?"""
print"1. Fight the bear"
print"2. Pick up the spear"
print"3. try to run away"
bear = raw_input(">")
spear = False
if (bear == "1" and spear == True) :
print "You fight and kill the bear"
elif (bear == "1" and spear == False):
dead("the bear claws your face off")
elif (bear == "2" and spear == True):
print "You already have the spear"
bear_room()
elif (bear == "2" and spear == False):
print "you picked up the spear"
spear = True
print "Now do you want to fight the bear?"
print "1. Fight the bear with the spear"
print "2. Try to run away from the bear"
choice = raw_input(">")
if choice == "1":
print """You fought and killed the bear, you can now
go through the door"""
elif choice == "2":
dead("The bear eats you from behind")
else:
"""You drop the spear, and retreat back to the entrance of the room. """
bear_room()
elif (bear == "3"):
dead("The Bear catches you and rips your head off")
else:
print "Please choose what to do!"
bear_room()
bear_room()
declare bear_room with a parameter:
def bear_room(spear = False):
take out the initial spear = False and whenever you call recursively bear_room make sure you pass in bear_room(spear) to reflect if spear has been change.
Note that if you just call bear_room() with no parameters to pass in, spear will be reset to False
Change the signature of the function bear_room() to bear_room(spear_status=False)
initialize your spear variable with spear_status
and where ever you calling bear_room() call it as bear_room(spear)
You can also make use of objects. Here is an example.
from sys import exit
class Person:
def __init__(self, name):
self.name = name
self.items = []
def die(self,why):
print why, "good Job", self.name
exit(0)
def bear_room(person):
print """In front of you is a big bear. It stares at you. You notice a door behind the bear. To the side of the bear you see a spear propped up against the wall. What do you do?"""
print"1. Fight the bear"
has_spear = "Spear" in person.items
if not has_spear: print"2. Pick up the spear"
print "3. try to run away"
bear = raw_input(">")
if (bear == "1" and has_spear) :
print "You fight and kill the bear"
return True
elif (bear == "1" and not has_spear):
person.die("the bear claws your face off")
elif (bear == "2" and not has_spear):
print "you picked up the spear"
person.items.append("Spear")
return False
elif (bear == "3" and has_spear):
person.die("The Bear catches you and rips your head off")
elif (bear == "3" and not has_spear):
person.die("The Bear eats you from behind")
elif has_spear:
print "You drop the spear retreat back to the entrance of the room. "
return True
else:
print "Please choose what to do!"
return False
warrior = Person("Soldat")
while True:
if bear_room(warrior): break

simple notepad data input program needs fixing

Hi I recently had this program running fine but after fiddling round with it now it doesn't work because when i run it in the shell when the program asks "do you want to enter a user" and I type "yes" it doesn't ask for the user to input he/shes name, DOB in form 00/00/0000, run time, postcode. It just prints "do you want to see your records?" If anyone could help quick it would be much appreciated p.s im really new so I dont 100% understand some things at the moment.
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
Try this

Why won't my program work in python?

Hi I am 11 yrs old and I am teaching myself how to code. I set myself a task to make a times table quiz that asks 10 questions and inputs random numbers. However, my code is not working and I do not know why. I am using python 2.7.5. This is my code:
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
import random
print random.randint(1,10)
print ("times")
import random
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"
I can not spot why it is not working but I have not put a for loop in yet so it only asks 1 question. When I run it else is highlighted in red but I do not know why.
Python works without brackets. It is replaced by "spaces or tabs". And we import ONCE, the beginning.
This should work
import random
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
print random.randint(1,10)
print ("times")
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"

TypeError: expected a character buffer object (trying to write to a text file)

I am trying to code a simple program that writes the output of a function to a text file, and I had it working, but today I tried to run it and it gives me this error at line 54: TypeError: expected a character buffer object.
Here is that line:
f.write(spotify.getCurrentTrack())
Also, here is the rest of the code:
from pytify import Spotify
spotify = Spotify()
import time
var2exit = 1
print "This program was created by Drew Halverson. Do not claim as your own work."
time.sleep(2)
print "This program could not have been created without the help of pytify."
time.sleep(2)
print "Also, this program is not affiliated with Spotify at all and is not an official app."
time.sleep(2)
print "For information on how to use this program and what its use is, check readme.txt"
yes = set(["yes", "y", "YES"])
no = set(["no", "n", "NO"])
r = open("readme.txt", "r")
print "Would you like to read the readme now (type yes or no)?"
choice = raw_input()
if choice in yes: print r.read()
print " "
time.sleep(2)
if choice in no: print "Hi! I will now be checking what song is playing on spotify."
time.sleep(2)
print "Make sure spotify is playing (Only the downloaded application will work. The program is not compatible with the web player version of Spotify."
time.sleep(2)
print " "
time.sleep(1)
print "Have you downloaded Spotify on this computer already? Type yes or no..."
choice2 = raw_input()
if choice2 in yes: print "Alright! Let's go!"
if choice2 in no: var2exit = 2
if var2exit == 2:
print "Go install Spotify first, then try again."
time.sleep(5)
print "Goodbye!"
time.sleep(2)
sys.exit()
var = 1
while var == 1 :
spotify.getCurrentTrack()
spotify.getCurrentArtist()
f = open("current_track.txt", "w")
g = open("current_artist.txt", "w")
f.write(spotify.getCurrentTrack())
g.write(spotify.getCurrentArtist())
print "The current Track is:"
print spotify.getCurrentTrack()
print "The current Artist is:"
print spotify.getCurrentArtist()
time.sleep(10)
print" "
print "Checking again..."
I know there are similar questions to this but none that I found exactly answered my problem. Thanks.

How can i make it so the program progresses while a 'while loop' is running a timer (python)

I need to know how i can enter user input while this while loop counting time is running. I know my program is not efficient nor organized as I am new to python. A simple but longer fix is better than a short fix that I would not understand.
import time
print 'Welcome To the Speedy Type Game!'
time.sleep(1)
print "You're objective is to win the game by typing the specific word before the time runs out"
print "Don't forget to press 'enter' after typing the word!!!!"
print "For round 1 you will have 5 seconds"
null = raw_input('Press enter when you are ready to start')
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'GO'
C = 'poop'
x = 5
while C in ['poop']:
x = x - 1
time.sleep(1) #This is where my program comes to a halt.
C = raw_input("Print the word 'Calfornia': ") #I dont know how to make the program progress to here without stopping the timer above.
if x < 0:
print 'You have failed, game over!'
else:
print 'Good Job! let us move to the next round!'
There is no easy way to do this in Python - a single process is running at a time, so without e.g. threading (see https://stackoverflow.com/a/2933423/3001761) you can't overlap user input with counting. An easier approach might be:
def test(word, limit=5):
started = time.time()
while True:
result = raw_input("Type {0!r}: ".format(word))
finished = time.time()
if result == word and finished <= started + limit:
print 'Good Job! let us move to the next round!'
return True
elif finished > started + limit:
break
print 'Wrong, try again.'
print 'You have failed, game over!'
return False
Then call e.g.:
>>> test("California")
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly but quickly
Wrong, try again.
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly and slowly
You have failed, game over!
False
>>> test("California")
Type 'California': California # typed slowly
You have failed, game over!
False