Python write to file maths generator - python

hello i have my code for a random maths quiz and i want it to save the name and there score next to the file and i want it to keep the data and not write over it every time could someone please help me and add this in i would like it so it could reocrd it like this let say i played it i would like the file to be like this then if someone else took the quiz it just adds there name to the list not erase the list first
name score
def quiz():
import random
import time
name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
for question in range (1,11):
ops=['*','+','-']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation=random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Question",question)
time.sleep(0.5)
print (rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
print ("Correct")
score=score+1
else:
print ("Incorrect. The actual answer is",maths)
if score >=7:
print ("Well done you got",score,"out of 10")
else:
print ("Unlucky you got",score,"out of 10")
percentage=score/10*100
print ("You got",percentage,"%")
f = open('results.txt','w')
f.write('%d' % score)
f.close()
playagain = 'yes'
while playagain == 'yes':
quiz()
print('Do you want to play again? (yes or no)')
playagain = input()

Change
f = open('results.txt','w')
to
f = open('results.txt','a')
Read the python docs for File I/O. 'w' overwrites an existing file
if you want the name with the score
f.write('{} : {}\n'.format(name, score) )

Related

I'm making a text based adventuere game in python and trying to add a third option but it's not working

I'm trying to make a simple text adventure game with three choices. But I can't seem to figure out why this isn't working.
This is the code I have been working on:
#Text based medieval adventure game
#Imported libraries are required
import random
import time
def displayWelcome():
print ("\nText adventure game\n")
print ("Welcome to the medieval adventure game!")
print ("You will have many choices through out this game")
print ("Be sure to pick the right one")
print (" Good Luck! ")
answer = askYesNo("Would you like help with this program? (Y/N): ")
if answer == "Y":
helpForUser()
time.sleep(3)
def askYesNo (question):
# This function will ask you a yes or no question and will keep asking until one is chosen.
# The following function is used to erase the variable response of any values
response = None
while response not in ("Y", "N"):
response = input (question).upper()
return response
def helpForUser():
#This function will show the user some helpful advice if they desire it
print ("\n+++++++++++++++++++++++++++++++++++++++ Help +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print ("This game is a adventure text based game set in the medieval times")
print ("You will be asked multiple questions with a yes or no response")
print ("you must answer the questions with the answers supplied to you suches as yes or no")
print ("If you don't answer the q uestion with the given answers it will be repeated untill a valid response occurs")
print ("The program can end when you choose")
print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def displayIntro():
#Displays intro to game
print ("\n It's been a rough day in the wild and you despratly need shelter")
print ("There is currently a war going on and nowhere is safe")
print ("But you intend to find somwhere with food and a bed but it wont be easy...")
print ()
def choosePath(lower,middle,upper):
#This functions allows you to choose between multiple options
path = 0
while path < lower or path > upper:
number = input("What path will you take(" + str(lower) + " - " + str(upper) + ")?: ")
if number.isdigit():
path = int (number)
else:
path = 0
return path
def followPath(chosenPath):
print ("you head down a long road\n")
time.sleep(3)
print ("You come across an abandoned campsite and decide to stay there for the night")
time.sleep(3)
print("You wake up to a sudden sound of voices and begin to realise that this campsite wasn't abandoned...")
time.sleep(3)
print("You start to freak out")
time.sleep(3)
if chosenPath == 1:
print("You grab your sword out and decide to go out the tent")
print ("Four well trained knights surround you")
print ("They strike without any hesitation, you counter two knights trying to hit you from the front as two from behind stab you in the back")
print ("The knights decide to burn your body and leave nothing left of you.\n")
elif chosenPath == 2:
print("You dart out of the tent and head for the exit")
print("All the guards try and get you whilst shooting arrows")
print("Several arrows hit you leaving you injured unable to run")
print ("Suddenly a man with a giant axe appears before you and slices you head off in a clean swoop\n")
else chosenPath == 3:
print("You keep calm and decide to sneak past all the guards")
print ("You're close to the exit when suddenly a guard notices you")
print("He's about to call for back up when you dash right into his chest with your sword, leaving it in him and running out the campsite")
print("You make it to a safe forest and decide to rest\n")
displayWelcome()
playAgain = "Y"
while playAgain == "Y":
displayIntro()
choice = choosePath()
followPath(choice)
playAgain = askYesNo ("Would you like to play again?")
print ("\nBye")
Error Number one: line 63, else should be elif or get rid of the condition "chosenPath == 3:
Current state
else chosenPath == 3:
What it should look like
elif chosenPath == 3:
or
else:
The other error is that nothing ever happens on initialization of choice because you forgot to input the "lower, middle, upper" values.

Nest IF needed? in Python

This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.
You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()

Python joke or chat error

when i run this, if i type chat it runs the punchline from the joke above how do i fix this?
enter image description here
print ("whats your name?")
firstname = input()
print ("hello,", firstname)
print ("what's your surname?")
surname = input()
fullname = (firstname +" "+ surname)
print ("hello,", fullname)
print ("what shall i call you on a daily basis?")
name = input()
print ("Glad to meet you,", name)
print ("is there anything you would like to do?")
print (" you can 'hear a joke' or 'have a chat'")
question = input("joke or chat?")
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
if question == "chat":
print("what games do you like?")
game = input()
print ("NO way i love,", game)
In the absence of proper indentation, Python is assuming that the lines
idk = input()
print ("Dead!!! LOL!!!!")
are outside the if statement. Indent them like you did for the print statement for the punchline.
Your spacing / indentation is off:
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
In your code should be:
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
PS: You should use more than 1 space for indenting to make it easier to read. Such as:
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")

How to detect own files name

I have some code, which I will rather not share but this a portion
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + "maze_game.exe"
exit()
else:
exit()
I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
so how might I get the file name?
EDIT: here is my whole code:
import os
import time
clear = lambda: os.system('cls')
name = input ("What is your name? ")
friend = "Charels"
if name == "Charels" or name == "charels" or name == "Charles" or name == "charles":
friend = "Chuck"
print ("Welcome to the Maze Game Dr. " + name)
time.sleep(1.5)
clear()
print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend)
time.sleep(1.5)
clear()
print ("Are you sure you want to continue?")
answer = input ("Y or N? ")
if answer == "Y" or answer == "y":
("")
else:
friend = friend + " for dead. R.I.P."
print ("Shame on you, you left " + friend)
time.sleep(1.5)
clear()
print ("YOU LOSE")
time.sleep(1.5)
clear()
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
input ("...")
no, the program is not completed and ignore the last line
Maybe I am misunderstanding what you want, but I think os.path.basename(__file__) will do the trick.
This will give you just the file part of your path, so if you have a filefoo/bar/baz.py and pass that path like os.path.basename('foo/bar/baz.py'), it will return the string 'baz.py'.
So try:
file_name = os.path.basename(__file__)
That being said, your approach seems a little atypical as #Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for.

Python, I have a guessing game and want to add the number of guesses

In the guessing game, I want the count to be the number of guesses variable and it to print the value when you win the game. Whenever I try to add the count = count + 1 line of code under the else part I keep getting loads of errors.
import random
from random import randint
secret = randint(0,11)
count = 1
def guessing():
print ("Guessing easy: The secret number will stay the same every turn")
guess = int(input("Guess a number from 1 to 10 "))
if secret == guess:
print ("Your guess was", guess)
print ("Well done, you win")
print ("It took you", count, "guessing to win")
startgame()
else:
print ("Your guess was",guess)
print ("Sorry, your guess was wrong. Please try again""\n")
guessing()
def guessinghard():
print ("Guessing hard: The secret number will change every turn")
secret = randint(0,11)
guess = int(input("Guess a number from 1 to 10 "))
if secret == guess:
print ("Your guess was", guess)
print ("Well done, you win")
print ("It took you ", count, " guessing to win")
startgame()
else:
print ("Your guess was", guess)
print ("Sorry, your guess was wrong. Please try again")
guessinghard()
def startgame():
game = input("Would you like to play easy or hard ")
if game == "easy":
guessing()
elif game == "hard":
guessinghard()
else:
print("Please choose easy or hard")
startgame()
startgame()
The errors I get are:
Traceback (most recent call last):
File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise - Secret Number.py", line 52, in <module>
startgame()
File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise - Secret Number.py", line 45, in startgame
guessing()
File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise - Secret Number.py", line 21, in guessing
count = count + 1
UnboundLocalError: local variable 'count' referenced before assignment
The count variable was declared outside the function that's using it. You could either declare that it's global, inside the function:
global count
Or pass it around as a parameter each time you call guessing(), as it's a recursive function:
def guessing(count):
Also, the code posted in the question doesn't show where the actual count variable is being incremented.

Categories

Resources