I'm trying to get this problem fixed. I'm creating a program which stores the score in a spreadsheet but when it does, it does not write the score and name in different cell. I have tried adding the column string/row string but always getting error, some guide and help will be appreciated.
So far this is what I have done:
!(http://postimg.org/image/6zn9l43bj/)!
I tried to get a heading saying name and the users name below in each cell and same with score and need some starting point/help
ClassA = open('classa.csv', 'w')
ClassB = open('classb.csv', 'w')
ClassC = open('classc.csv', 'w')
start = True
while start:
user =(input("What is your name?"))
form =(input("Which Group are you in A/B or C ")).lower()
import re
import random
from random import randint
score = 0
for i in range(3):
first_num = random.randint(1,10)
second_num = random.randint(1,10)
choice = (first_num+second_num)
if choice == first_num+second_num:
print ("Question (%d)" % (i+1))
print (first_num)
print("Add (+)")
print(second_num)
check = True
while check:
answer = (input('enter the answer: '))
if not (re.match('-?[0-9]\d*(\.\d+)?$', answer)):
print("Only input numbers")
else:
check = False
answer = int(answer)
if answer == (choice):
print("It's correct!")
score +=1
else:
print("It's wrong!")
print ("The correct answer is: ", choice)
print('')
print(user)
if form == 'a':
ClassA.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'b':
ClassB.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'c':
ClassC.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
yesorno = input("Restart?, Y or N ").lower()
if yesorno == 'y':
start = True
elif yesorno == 'n':
start = False
ClassA.close()
ClassB.close()
ClassC.close()
Thanks
A bit of background: CSV stands for Comma Separated Values, oddly enough Values are quite often separated by semicolons in CSV files and, in fact, (I think) Excel won't recognise columns if you use commas, but it will if you use semicolons. Edit: As pointed out in the comments, this probably depends on regional settings, if in your country the decimal point is usually a comma (e.g. most of Europe) use ;, if it's usually a point use , as separator.
So, back to your question: you are not separating your values, use this instead (notice the semicolon):
ClassA.write("Name: "+str(user) + '; ' + "Score: "+str(score)+"/10" + '\n')
I wouldn't recommend writing the Name: and Score: prefixes either, I would go with a header row (Name; Score; Max Score) and something like this:
ClassA.write("{0}; {1}; {2}\n".format(user, score, max_score))
See also: str.format
Related
I'm making a quiz in Python where a user can add himself the questions and answers and specify the correct one.
I already did this
# Do you want to add another question version
from Question import Question
question_prompt = []
answer_list = []
def add_Question():
question = input('Add your question: ')
print(question)
test = int(input('If your question is correct. Enter 1 else enter 2: '))
if test == 1:
print('Type the answers propositions: ')
a = input('(a): ')
b = input('(b): ')
c = input('(c): ')
d = input('(d): ')
# print(a + '\n' + b + '\n' + c + '\n' + d )
answer = input('Which one is the correct answer? (a) (b) (c) or (d). Just type the letter ie. a: ').lower()
question_insert = f"{question} \n {a} \n {b} \n {c} \n {d}\n\n"
question_prompt.append(question_insert)
answer_list.append(answer)
listing = tuple(zip(question_prompt, answer_list))
questions = [Question(question_prompt[i],answer_list[i]) for i in range(0, len(listing))]
else :
question = input('add your question: ')
print(question)
test = int(input('if your question is correct. Enter 1 else enter 2: '))
return question, a,b,c,d,answer
def insert_question_prompt() :
again = int(input("Do you want to add another question. 1 = 'yes' and 2 = 'no' "))
while again == 1:
add_Question()
again = int(input("Do you want to add another question. 1 = 'yes' and 2 = 'no' "))
print(question_prompt)
def run_test(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("Hey You got " + str(score) + "out of " + str(len(questions)) + "questions correct")
# questions = [Question(question_prompt[i],answer_list[i]) for i in range(0, len(listing))]
add_Question()
insert_question_prompt()
print(question_prompt)
print(answer_list)
In the function def insert_question_prompt() : I ask the user if he wants to insert another question and repeat the add_Question function.
The run_test function is to test the quiz. Play and access it
But I am unable to access question_prompt and answer_list in the run_test function even though they are not empty.
Basically, I'm blocked at level where the user can test the quiz ie Play and have the score.
Thanks for your help
I am trying to print an output but I just can't figure out method.
keepAsking = True
author = ""
booktitle = ""
purchaseprice = float()
sellprice = float()
stockcount = int()
margin = float()
bookList = []
priceList = []
while keepAsking == True :
print("Enter Book Data: -")
author = input("Author: ")
if author == "" :
print("Blank Entry")
else :
booktitle = input("Title: ")
if booktitle == "" :
print("Blank Entry")
else :
purchaseprice = input("Purchase Price: ")
if purchaseprice == "" :
print("Incorrect Value")
else :
sellprice = input("Sell Price: ")
if sellprice == "" :
print("Incorrect Value")
else :
bookList.append(author)
bookList.append(booktitle)
if purchaseprice > sellprice :
bookList.remove(author)
bookList.remove(booktitle)
else :
priceList.append(purchaseprice)
priceList.append(sellprice)
stockcount = input("In Stock: ")
if stockcount == "" :
print("Incorrect Value")
else :
priceList.append(stockcount)
margin = ((float(sellprice)-float(purchaseprice))/float(purchaseprice))*100
marginround = round(margin,2)
priceList.append(marginround)
checkContinue = True
while checkContinue == True :
continues = input("Continue? [y/n]")
continuesLower = continues.lower()
if continues == "y" :
checkContinue = False
if continues == "n" :
checkContinue = False
keepAsking = False
and I am trying to get an output like this:
output
I don't really understand array and I have tried a few methods but failed to output it as the image shows. If possible, I would need some explanation too because I want to learn rather than get the answer straight out. So, if you have a solution, I might ask for more information on it too. (you don't have to explain it if you are not comfortable, but I just wish to learn more)
Thank you for attempting to help me. I am sorry if this is just a simple task but I am less than a beginner and trying to improve myself.
I am currently not outputting anything enter image description here
my print code is
for a in bookList :
counter = 0
while counter == len(bookList) :
print(bookList[0] + bookList[1])
print("Purchase Price: " + priceList[0] + "Sell Price: " + priceList[1] + "In Stock: " + priceList [2] + "Margin: " + priceList [3])
If you want to print multiple Book names and prices, etc you should put each one of them into a separate list in this case. (with append)
If you want to print them out you can do like this:
for i in range(0, len(booklist)):
print(author[i] + ' Purchase:' + purchase[i] + ' Sell:' + sell[0]))
... etc to the right format in wich purchase and sell are all lists. Don't forget to add spaces.
To check if the person actually input numbers you can use the method .isdigit()
if purchaseprice.isdigit() != true :
print("Incorrect Value, input numbers")
I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.
I have this code as part of a larger dice game program to save the high score in a separate file (as well as the normal winning score file) but it always saves the highscore regardless whether it's higher or lower and also doesn't save it in the Winning_scores file either
It also saves it in the form of ('Name: ', 'John', 'Score: ', '10', '\n') instead of the variables separately because of the str because otherwise I get 'write() argument must be str, not tuple' which I'm also not quite sure how to fix
tot1 = 5
tot2 = 1
name1 = ('John')
while True: #Code to find & print the winner
if tot1 > tot2:
print("Player 1 is the winner!")
#Opens file & appends the winning score at the end of it
tot1 = str(tot1)#Turns the score into a str
win_score = open("Winning_scores.txt", "a")
winner = ("Name: "+name1+" Score: "+tot1)
win_score.write(winner)
win_score.write("\n")
win_score.close()
print("Score saved.")
hisc = open("Winning_scores.txt", "w+")
highscore = hisc.read()
highscore_in_no = (highscore)
highscore_in_no = highscore_in_no
if tot1 > highscore_in_no:
print("Exceeded high score.")
highscore_in_no = tot1
hiscore = open("High_scores.txt", "a")
winner = ("Name: ",name1,"Score: ",tot1,"\n")
hiscore.write(winner)
hiscore.close()
print("High score saved.")
break
your winner variable is a tuple, not a string.
in order to use hiscore.write(winner), winner should be a string as follows:
winner = "Name: " + name1 + "Score: " + tot1 + "\n"
or nicer readable:
winner = "Name: {name1} Score: {tot1}\n".format(**locals())
you can also join your existing winner tuple to a string:
hiscore.write(' '.join(winner))
This is your problem:
winner = ("Name: "+name1+" Score: "+tot1)
win_score.write(winner)
When you wrap a value in parenthesis in Python, you're saying it's a tuple, something sort of similar to a list. Here's a hopefully more clear example
one = "foo"
two = "bar"
this_is_a_tuple = (one, two)
this_is_also_a_tuple = (one)
this_is_not_a_tuple = one + two
this_is_a_tuple = (one + two)
So I am trying to run a program on python3 that asks basic addition questions using random numbers. I have got the program running however, I wanted to know if there was a way I could count the occurrences of "Correct" and "Wrong" so I can give the person taking the quiz some feedback on how they did.
import random
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
else:
print ('Wrong.')
You could use a dict to store counts for each type, increment them when you come across each type, and then access it after to print the counts out.
Something like this:
import random
stats = {'correct': 0, 'wrong': 0}
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
stats['correct'] += 1
else:
print ('Wrong.')
stats['wrong'] += 1
print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])
import operator
import random
def ask_float(prompt):
while True:
try: return float(input(prompt))
except: print("Invalid Input please enter a number")
def ask_question(*args):
a = random.randint(1,100)
b = random.randint(1,100)
op = random.choice("+-/*")
answ = {"+":operator.add,"-":operator.sub,"*":operator.mul,"/":operator.div}[op](a,b)
return abs(answ - ask_float("%s %s %s = ?"%(a,op,b)))<0.01
num_questions = 5
answers_correct = sum(map(ask_question,range(num_questions)))
print("You got %d/%d Correct!"%(answers_correct,num_questions))