my code wont save the file
#ask for name
name=input("what is your name?")
print("start your quiz " + name + "!")
user=input
class123=('1','2','3')
class123=input("what class are you in 1,2 or 3")
#get random number
import random
#ask number of questions you want
score=0
count=10
#start while loop
while count != 0:
num1=random.randint(1,8)
num2=random.randint(1,8)
symbol=random.choice(['*','+','-'])
if symbol=="*":
user=int(input(str(num1) + "*" + str(num2)))
count=count-1
answer=num1 * num2
if user==answer:
print("well done your score goes up by 1")
score=score+1
else:
print("this is wrong next question")
elif symbol=="+":
user=int(input(str(num1) + "+" + str(num2)))`enter code here`
count=count-1
answer=num1 + num2
if user==answer:
print("well done your score goes up by 1")
score=score+1
else:
print("this is wrong next question")
elif symbol=="-":
user=int(input(str(num1) + "-" + str(num2)))
count=count-1
answer=num1 - num2
if user==answer:
print("well done your score goes up by 1")
score=score+1
else:
print("this is wrong next question")
#get final score
print(" your score was " + str(score) + " well done ")
#save data into 3 classes
while score == 10 and score >= 0:
if class123 == '1':
inFile = open("Class1.txt", 'a')
inFile.write("\n" + name + ":" + str(score))
inFile.close()
score = -1
elif class123 == '2':
inFile = open("Class2.txt", 'a')
inFile.write("\n" + name + ":" + str(score))
inFile.close()
score = -1
elif class123 == '3':
inFile = open("Class3.txt", 'a')
inFile.write("\n" + name + ":" + str(score))
inFile.close()
score = -1
If you want your code to work, first off remove or comment out the 'enter code here' part on line 26. It can be done with '#'. The reason is '' is a string and will be interpreted as a string in a place where it shouldn't be.
user=int(input(str(num1) + "+" + str(num2))) #enter code here
2nd, it's not saved because while never runs, as while score == 10 is not true, so the loop where you write the score never runs.
You can just change it to something like:
while score <= 10 and score >= 0:
I tested the 2 adjustments I made and, well, your code would run and create the Class?.txt file
Yet as others mention, it's not quite the right structure. Not quite the right usage of stuff. So you may want to improve your code, but here I just gave you a few fixes how to actually get it to run, if you don't mind.
Related
I'm currently working on a project where I have to code a simple number guessing game with a high score system. Where if your score is higher than one of the top 10 scores it will replace said score and tell you, you got a new high score. At the moment I'm a bit stuck on the retrieving the value from the file and comparing it to the score when you complete the game. I am a beginner at programming the code will be below.
Number guessing game with high scores:
import pygame
from random import randint
a = True
n = randint(1,10)
guesses = 0
#If scores ever need to be reset just run function
def overwritefile():
f = open("Numbergame.txt", "w")
f.close()
#overwritefile()
#Guessing Game Code
while a == True:
guess = int(input("What is your guess? \nEnter a number!"))
if guess > n:
print("Guess is too high! \nTry Again!")
guesses += 1
elif guess < n:
print("Guess is too low! \nTry Again!")
guesses += 1
else:
guesses += 1
a = False
print("You guessed the number! \nIt was " + str(n) + "\nIt took you: " + str(guesses) + " guesses")
#Adding Score to the file
f = open("Numbergame.txt", "a")
f.write(str(guesses) + '\n')
f.close()
#Compare values and figure out if it is a new highscore
#Maybe I will use the TRY thing got taught recently might help iron out some errors
##
##last_high_score = 0
##
##try:
## f = open("Numbergame.txt", "r")
## user = str(guesses)
##
## for line in f.readline():
## line_parts = line.split(" has a score of ")
##
## if len(line_parts) > 1:
## line_parts = line_parts[-1].split("\n")
## score = line_parts[0]
## if score.isdigit() and int(score) > last_high_score:
## last_hight_score = int(score)
##except Exception and e:
## pass
##
##if int(guesses) > last_high_score:
## f = open("Numbergame.txt", "a")
## f.write(str(guesses) + "\n")
##
##print("\n")
##f = open("Numbergame.txt", "r")
##whole_thing = f.read()
##f.close()
##for i in len("Numbergame.txt"):
## file.readline(i)
## if guesses < file.readline(i):
## print("Not a highscore")
## elif guesses > readline(i):
## print("Is a highscore")
## else:
## print("Not a highscore")
The two bits that are commented out are my attempts, the first one is one I copied from another question and the second one is my attempt
Hey I'm trying to add a variable for "won" or "loss", I already have a variable for players name and guesses allowed.
Any help would be kind thanks. This is the code I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?: ")
number_of_guesses = 0
print("Okay! "+ player_name+ " I am guessing a number between 1 and 100:")
max_guesses = random.randint(1, 6)
print("You have " + str(max_guesses) + " guesses. ")
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
f = open("statistics.txt", "a")
f.write =(player_name) (max_guesses)
f.close()
f = open("statistics.txt", "r")
print(f.read())
Maybe add befor you loop the variable won = False
And in the loop
if guess == number:
won = True
break
After the loop if the player don't find the nulber won will be false.
In the oter case it will be True
For saving
f.write( str(won) ) # convert to string
So I've built a simple calculator in Python where the user inputs two numbers and an operator and the answer is given. They also have the option to run the calculator again. I want to number the answers so each answer reads "Answer 1 equals x", "Answer 2 equals x", etc. depending on how many times the calculator is run. Everytime I try to format the counter to count iterations, it won't work and is stuck just labeling them "Answer 1" over and over. Any help would be greatly appreciated. I'm super new to Python.
answer = "y"
while ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
numones = input ("Give me a number: ")
numtwos = input ("Give me another number: ")
numone = float(numones)
numtwo = float(numtwos)
operation = input ("Give me an operation (+,-,*,/): ")
counter = 0
for y in answer:
counter += 1
if (operation == "+"):
calc = numone + numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "-"):
calc = numone - numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "*"):
calc = numone * numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "/"):
calc = numone / numtwo
if (numtwo != 0):
print ("Answer " + str(counter) + " is " + str(calc))
else:
print ("You can't divide by zero.")
else:
print ("Operator not recognized.")
answer = input ("Do you want to keep going? ")
if ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
print ()
else:
print ("Goodbye.")
break
Remove assigning counter = 0 in your while loop. And move this declaration above your while loop.
also lines:
for y in answer:
counter += 1
are really confusing and sure are wrong, because if you got 'yes' as an answer you would get +3 increase. Just increment(counter += 1) counter without any for-loop.
I am having a problem with getting an 'undefined' error in my code or, my variable being incorrectly redefined. I am trying to redefine a variable that is inside a loop each time the loop is executed. But the problem is that either (when my variable is defined outside the loop) i get a 'variable is undefined' error, or the variable does not change and/or is reset to zero when the loop is reinitialized.
def game():
scorePlayer = 0
scoreAI = 0 #If I define it here I get the latter of the two errors explained.
number = random.randint(1, 6)
print ("Your score is ", scorePlayer, ". Your opponent's score is ", scoreAI, ".") #This is where it tells me it is referenced before defined if I define outside the loop.
print (" ")
print ("Rolling...")
print (" ")
time.sleep(2)
print ("You have rolled a ", number, ".")
print (" ")
print ("Player, would you like to hold (enter 'hold') or roll (enter 'roll')?")
print (" ")
decide = raw_input(" ")
if decide == 'hold':
print (" ")
scorePlayer = tempScorePlayer + scorePlayer
gameAI()
elif decide == 'roll': #changed to elif
print (" ")
if number == 1:
print ("You have rolled a 1. You will not gain points from this turn.")
print (" ")
tempScorePlayer = 0
gameAI()
elif number >= 2: #changed to elif
print (" ")
tempScorePlayer = number + tempScorePlayer
game()
if scorePlayer >= 100:
winPlayer()
I have tried defining the variables everywhere else so that they wouldn't interfere with the loop and still couldn't get it to work.
Any help would be much appreciated, thanks.
Try this one:
def game():
scorePlayer = 0
scoreAI = 0 #If I define it here I get the latter of the two errors explained.
number = random.randint(1, 6)
print ("Your score is %d. Your opponent's score is %d."%(scorePlayer, scoreAI)) #This is where it tells me it is referenced before defined if I define outside the loop.
print (" ")
print ("Rolling...")
print (" ")
time.sleep(2)
print ("You have rolled a %d.", number)
print (" ")
print ("Player, would you like to hold (enter 'hold') or roll (enter 'roll')?")
print (" ")
decide = raw_input(" ")
if decide == 'hold':
print (" ")
scorePlayer += tempScorePlayer
gameAI()
if decide == 'roll':
tempScorePlayer = 0
print (" ")
if number == 1:
print ("You have rolled a 1. You will not gain points from this turn.")
print (" ")
gameAI()
if number >= 2:
print (" ")
tempScorePlayer += number
game()
if scorePlayer >= 100:
winPlayer()
I changed the tempScorePlayer variable, setting 0 at it by default.
Note: tempScorePlayer += number it's equals to tempScorePlayer = tempScorePlayer + number
I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())