Pickle in python, writing to files - python

if group == 10G2:
file_name='10G2 Scores.txt'
fileObject = open(file_Name,'wb')
pickle.dump(+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
This is part of a maths quiz and I am trying to write scores to a text file. It says there is a syntax error on the 10G2?
All of the variables have been defined and I have imported pickle
Thanks in advance. BTW, I'm doing GCSE computing.
This is my whole code:
#Maths Quiz
noq=0
score=0
import math
import pickle
import random
import time
import pickle
def write(name, finalscore, totalquestions, score, file_Object):
pickle.dump ((str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,file_Object)
return
group=input("What mentor group are you in?: ")
name=input("What is your name?: ")
print ("Hello " + name + ". How many questions would you like to do?:")
totalquestions=int(input(" "))
for i in range (0,(totalquestions)):
noq=noq+1
print ("Question " +str(noq))
numberone=random.randint(1, 10)
numbertwo=random.randint(1, 10)
answer=int(numberone) + int(numbertwo)
print ("What is " +str(numberone) + "+" + str(numbertwo) + "?:")
uanswer=int(input(""))
if answer==uanswer:
print("That is correct!!!")
score=score +1
print ("Your score is.....")
time.sleep(0.5)
print("" +str(score) + " out of " + str(i+1))
time.sleep(1)
else:
print ("Sorry, that is wrong!!!")
score=score
print ("Your score is.....")
time.sleep(0.5)
print ("" +str(score) + " out of " + str(i+1))
time.sleep(1)
time.sleep(0.5)
print ("Your final score is.....")
finalscore=score/totalquestions
finalscore=finalscore*100
time.sleep(3)
print ("" +str(finalscore)+ " percent")
#file write###############################################################################
if group == 10G2:
file_name='10G2 Scores.txt'
fileObject= open(file_Name,'w')
pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
elif group == 10G1:
file_name='10G1 Scores.txt'
fileObject = open(file_Name,'w')
pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
elif group == 10G3:
file_name='10G3 Scores.txt'
fileObject = open(file_Name,'w')
pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
elif group == 10G4:
file_name='10G4 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
elif group == 10G5:
file_name='10G5 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
elif group == 10G6:
file_name='10G6 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
elif group == 10G7:
file-name='10G7 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()

Try changing this line
if group == 10G2:
to:
if group == '10G2':

Related

Hello, I'm trying to convert from YYYY/MM/DD to dd/mm/yyyy by using .strptime but it comes up with AttributeError: object has no attribute 'strptime'

from datetime import datetime
from datetime import date
import datetime
import time
import math
seconds_Yearly = 3656060*24
seconds_Daily = 606024
seconds_Hourly = 60*60
minute = 60
eventName1 = input("What is the name of the first event?")
print(" ")
eventName2 = input("What is the name of the second event?")
print(" ")
event_Year1 = input("Which year is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Month1 = input("Which month [1-12] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Day1 = input("Which day [1-31] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Year2 = input("Which year is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Month2 = input("Which month [1-12] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Day2 = input("Which day [1-31] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Year1 = int(event_Year1)
event_Month1 = int(event_Month1)
event_Day1 = int(event_Day1)
event_Year2 = int(event_Year2)
event_Month2 = int(event_Month2)
event_Day2 = int(event_Day2)
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
event1_date = event1_dates.strptime((event_Year1), (event_Month1), (event_Day1), "d/m/Y")
print(str(event1_date))
print(" ")
event2_date = date((event_Year2), (event_Month2), event_Day2)
print(event2_date)
print(" ")
seconds_event1 = time.mktime(event1_date.timetuple())
print(seconds_event1)
print(" ")
seconds_event2 = time.mktime(event2_date.timetuple())
print(seconds_event2)
print(" ")
seconds_difference_rough = seconds_event2 - seconds_event1
seconds_difference = abs(seconds_difference_rough)
print(seconds_difference)
print(" ")
minutes_difference = seconds_difference/60
print(minutes_difference)
print(" ")
hours_difference = minutes_difference/60
print(hours_difference)
print(" ")
days_difference_rough = hours_difference/24
days_difference = abs(days_difference_rough)
print(days_difference)
print(" ")
years_difference_roughs = seconds_difference/seconds_Yearly
years_difference_rough = seconds_difference//seconds_Yearly
years_difference = abs(years_difference_rough)
years_difference_remainer = seconds_difference%seconds_Yearly
print(years_difference)
print(years_difference_roughs)
weeks_difference_parta = (days_difference/7)/52
weeks_difference_partb = weeks_difference_parta/years_difference_roughs
weeks_difference = abs(weeks_difference_partb)
print(weeks_difference)
months_difference_part1a = hours_difference/24/30.435
months_difference_part1aa = months_difference_part1a//1
months_difference_part1b = abs(months_difference_part1aa)
print(months_difference_part1b)
months_difference_part2a = (years_difference * 12) - months_difference_part1b
month_difference_roughs = (years_difference * 12) - months_difference_part1a
months_difference_part2b = abs(months_difference_part2a)
days_decimal, whole = math.modf(months_difference_part1a)
print(" ")
print(months_difference_part2b)
print(" ")
print(months_difference_part1a)
print(" ")
days_difference1a = days_difference/28
days_difference1ab = days_difference/30.45
days_difference1b = days_difference1ab//1
days_difference1c = (days_difference1a - days_difference1ab)
days_difference_total = abs(days_difference1b)
print(days_difference_total)
print(" ")
print(days_difference1ab)
week_difference = days_difference_total/7
week_difference_total = abs(week_difference)
print(week_difference_total)
print(" ")
#hours_one = hours_difference
def days ():
global days, days_remaing_negative, days_remaing_positve, days_remaing
if event_Year2 > event_Year1:
months_difference_rough = days_difference/(hours_difference/24/30.435)
months_difference = abs(days_difference_rough)
months_difference_remainer = seconds_difference%seconds_Daily
print(months_difference)
print(days_decimal)
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
days_remaing = abs(days_remaing)
print(days_remaing)
else:
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
print(days_remaing)
def weeks():
global days_remaing, days, new_week, new_days2
if days_remaing >= 7:
new_weeks = days_remaing/7
abs_new_week = abs(new_weeks)
new_week = new_weeks//1
new_week_decimal, whole = math.modf(abs_new_week)
new_days1 = new_week_decimal * 7
new_days2 = new_days1//1
print(new_week)
print(new_days2)
else:
new_week = 0
new_days2 = days_remaing
print(new_days2)
def difference():
global new_days2, new_week, months_difference_part1b, years_difference, eventName1, eventName2, days_remaing, days, new_week, months_difference_part2b
if event_Year2 > event_Year1 or event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("a")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("b")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 == event_Month1 and event_Day2 > event_Day1:
print("C")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
else:
print("D")
print(str(eventName1) + " " + "is" + " " + "on" + " " + str(event1_date) + " " + " " + "which is" + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "After" + " " + " " + str(eventName2))
days ()
weeks()
difference()
Are you trying to convert event1_dates?
from datetime import date
event_Year1=2020
event_Month1=1
event_Day1=30
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
print(event1_dates)
event1_date = event1_dates.strftime("%d/%m/%Y")
print(event1_date)
Output:
2020-01-30
30/01/2020

Correct usage of __str__ method for a dictionary (kwargs)

I have a task to print correctly kwargs arguments of a class.
Here is my code:
class Contact:
def __init__(self, name, surname, number, selected=None, **kwargs):
self.name=name
self.surname=surname
self.number=number
self.selected=selected
self.additional=kwargs
def __str__(self):
if self.selected==None:
selected='No'
else:
selected='Yes'
return 'Name: ' + self.name+'\n' + \
'Surname: ' + self.surname+ '\n' + \
'Phone: ' + self.number + '\n' + \
'In selected: ' + selected + '\n' + \
'Additional information: ' + '\n' + \
str(self.additional.keys()) + '\n' + \
str(self.additional.values())
if __name__=='__main__':
jhon = Contact('Jhon', 'Smith', '+71234567809', telegram='#jhony', email='jhony#smith.com')
print (jhon)
I need to have in the end:
Additional information:
telegram : #jhony
email : jhony#smith.com
But all I've got is :
I've really tried to iterate over it, create lists, and I've got nothing, because the ___str___ method could only use str objects. How can I go through the kwargs arguments and take it in format of key : value?
You need to iterate over the dict referenced by self.additional.
def __str__(self):
return ('Name: ' + self.name + '\n'
+ 'Surname: ' + self.surname+ '\n' +
+ 'Phone: ' + self.number + '\n' +
+ 'In selected: ' + selected + '\n' +
+ 'Additional information: ' + '\n' +
+ '\n'.join([f' {k}: {v}' for k, v in self.additional.items()]))

How to implement a grid using arrays with a given size?

I am trying to create a simple board in a draw_board definition that will use size and several coordinates where I will place 1 character length characters in specified coordinates. I am in the beginning stages and want to just simply create the board itself using a 2d array.
This method below works when I change individual elements :
board = [['','','',''], ['','','',''], ['', '', '', ''], ['','','','']]
board[0][0] = 'a'
print(' 0 1 2 3')
print('0 ' + board[0][0] + ' ' + board[0][1] + ' ' + board[0][2] + ' ' + board[0][3])
print('1 ' + board[1][0] + ' ' + board[1][1] + ' ' + board[1][2] + ' ' + board[1][3])
print('2 ' + board[2][0] + ' ' + board[2][1] + ' ' + board[2][2] + ' ' + board[2][3])
print('3 ' + board[3][0] + ' ' + board[3][1] + ' ' + board[3][2] + ' ' + board[3][3])
However, I would not be able to change the size by just a variable and would need to edit the initialization of the board myself.
This method below is better and would work because I could easily change the size variable and get any size board I want...
size = 4
board = [['']*size]*size
board[0][0] = 'a'
print(' 0 1 2 3')
print('0 ' + board[0][0] + ' ' + board[0][1] + ' ' + board[0][2] + ' ' + board[0][3])
print('1 ' + board[1][0] + ' ' + board[1][1] + ' ' + board[1][2] + ' ' + board[1][3])
print('2 ' + board[2][0] + ' ' + board[2][1] + ' ' + board[2][2] + ' ' + board[2][3])
print('3 ' + board[3][0] + ' ' + board[3][1] + ' ' + board[3][2] + ' ' + board[3][3])
However, when I implement board[0][0] = 'a', it changes the entire column to 'a', which is not what I want. Any suggestions of how I could change this second method to make it work for just the desired coordinate?
Use
board = [['' for i in range(size)] for j in range(size)]
this is because when you use the * operator, you're creating more references to the same object, not more copies.
Here's more in depth information about the strategy used above, called list comprehensions

Python skipping elif statement

I'm trying to write a program that prints the values and keys in a dictionary depending of the input the user types. The problem appears when the elif statement on line 11 gets skipped. It doesn't matter if the if statement is false, the elif statement gets skipped. I'm learning so I don't really know where my error is. Thanks for the help!
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
print("Enter a conversion")
if input() == "Area Meassure":
displayConversion(areaM)
elif input() == "Linear Meassure":
displayConversion(linearM)
else:
print("Conversion not available")
Maybe this as the full code (too much inputss):
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
a=input("Enter a conversion\n")
if a == "Area Meassure":
displayConversion(areaM)
break
elif a == "Linear Meassure":
displayConversion(linearM)
break
else:
print("Conversion not available")

Generating combinations between a range of numbers. How?

I had the following code that was working just fine and then I've updated to a new version of Python. What I don't understand is why it will only work up to 10 combinations. If you set variables combination_cap and range_to to higher than 10 the program just hangs. No error. Nothing.
Here's my code:
import itertools
import subprocess
import os
if os.name == 'nt':
def clear_console():
subprocess.call("cls", shell=True)
return
else:
def clear_console():
subprocess.call("clear", shell=True)
return
def generateCombinationRange():
combination_cap = 10
range_from = 1
range_to = 10
combination_list = list(itertools.combinations(range(1, int(combination_cap)+1), 6))
combination_list_lenght = len(combination_list)
output_file = open('F' + str(range_from) + 'T' + str(range_to) + 'OF' + str(combination_list_lenght) + '_comibnations.csv', 'w')
index = 0
for each_combination in combination_list:
index += 1
#print(''.join(str(each_combination)) + '\n')
if index >= range_from:
output_file.write(str(index) + ', '
+ str(each_combination[0]) + ', '
+ str(each_combination[1]) + ', '
+ str(each_combination[2]) + ', '
+ str(each_combination[3]) + ', '
+ str(each_combination[4]) + ', '
+ str(each_combination[5]) + '\n'
)
if index >= range_to:
output_file.close()
break
output_file.close()
generateCombinationRange()
The issue is the line list(itertools.combinations(range(1, int(combination_cap)+1), 6)). If the numbers are high, you're generating an enormous list that's going to chew through all of your RAM. What you should do is use it as a generator, so it only generates the numbers you actually use. This version will work with any set of values for combination_cap and range_to because it only stores one combination in memory at a time.
def generate_combination_range():
combination_cap = 100
range_from = 1
range_to = 100
output_file = open(
'F' + str(range_from) + 'T' + str(range_to) + 'OF' + '_comibnations.csv', 'w')
index = 0
for each_combination in itertools.combinations(range(1, int(combination_cap) + 1), 6):
index += 1
# print(''.join(str(each_combination)) + '\n')
if index >= range_from:
output_file.write(str(index) + ', '
+ str(each_combination[0]) + ', '
+ str(each_combination[1]) + ', '
+ str(each_combination[2]) + ', '
+ str(each_combination[3]) + ', '
+ str(each_combination[4]) + ', '
+ str(each_combination[5]) + '\n'
)
if index >= range_to:
output_file.close()
break
output_file.close()
Also, style note, it's generally prefered to use enumerate instead of manually managing an index. for index, each_combination in enumerate(itertools.combinations(range(1, int(combination_cap) + 1), 6)):
You are getting a Memory error:
Traceback (most recent call last):
File "C:\zila\zilawww\t.py", line 54, in <module>
generateCombinationRange()
File "C:\zila\zilawww\t.py", line 25, in generateCombinationRange
combination_list = list(itertools.combinations((range(1, int(combination_cap)+1)), 6))
MemoryError
Remove the "list"
combination_list = list(itertools.combinations(range(1, int(combination_cap)+1), 6))
To make it a generator and save the memory (you won't be able to use it on len though)
combination_gen = (itertools.combinations(range(1, int(combination_cap)+1), 6))
I took the time to incorporate your answer into my code and now I have the finished product. I would like to share the complete code with everyone who may be interested.
import subprocess
import os
import itertools
import math
if os.name == 'nt':
def clear_console():
subprocess.call("cls", shell=True)
return
else:
def clear_console():
subprocess.call("clear", shell=True)
return
#----------------------------------------------------------------------
def main_menu():
while True:
main_menu_selected_option = 0
# MAIN MENU - PARENT
while main_menu_selected_option not in range(1, 4):
try:
clear_console()
print ('')
print (' Combination Generator v1.0 - Menu')
main_menu_selected_option = int(input('''
1. All indexed combinations for combination cap.
2. All Prime indexed combinations for combination cap.
3. Extract range of indexed combinations for combination cap.
4. Extract Prime range of indexed combinations for combination cap.
Enter Option: '''))
except ValueError:
#print ('Not an integer!')
#clear_console()
#print ('')
#print (' Lotery Systems - Menu')
continue
else:
if main_menu_selected_option == 1:
menu_1()
else:
if main_menu_selected_option == 2:
menu_2()
else:
if main_menu_selected_option == 3:
menu_3()
else:
if main_menu_selected_option == 4:
menu_4()
else:
clear_console()
main_menu()
#----------------------------------------------------------------------
def menu_1():
combination_cap = 0
# 1ST MENU = CHILD.
while int(combination_cap) not in range(1, 42+1):
combination_cap = int(input('''
Enter combination Cap: '''))
print ('')
print (' Generating combinations for combination cap.')
print (' Please wait...')
menu_1_execute(combination_cap)
#----------------------------------------------------------------------
def menu_2():
combination_cap = 0
# 2ND MENU = CHILD.
while int(combination_cap) not in range(1, 42+1):
combination_cap = int(input('''
Enter combination Cap: '''))
print ('')
print (' Generating combinations for combination cap.')
print (' Please wait...')
menu_2_execute(combination_cap)
#----------------------------------------------------------------------
def menu_3():
combination_cap = 0
range_from = 0
range_to = 0
# 3RD MENU = CHILD.
while int(combination_cap) not in range(1, 42+1):
try:
combination_cap = int(input('''
Enter combination Cap: '''))
range_from = int(input('''
Enter from: '''))
range_to = int(input('''
Enter to: '''))
except ValueError:
#print ('Not an integer!')
#clear_console()
#print ('')
#print (' Lotery Systems - Menu')
continue
else:
if range_from < range_to:
print ('')
print (' Generating range of combinations for combination cap.')
print (' Please wait...')
menu_3_execute(combination_cap, range_from, range_to)
else:
continue
#----------------------------------------------------------------------
def menu_4():
combination_cap = 0
range_from = 0
range_to = 0
# 3RD MENU = CHILD.
while int(combination_cap) not in range(1, 42+1):
try:
combination_cap = int(input('''
Enter combination Cap: '''))
range_from = int(input('''
Enter from: '''))
range_to = int(input('''
Enter to: '''))
except ValueError:
#print ('Not an integer!')
#clear_console()
#print ('')
#print (' Lotery Systems - Menu')
continue
else:
if range_from < range_to:
print ('')
print (' Generating Prime range of combinations for combination cap.')
print (' Please wait...')
menu_4_execute(combination_cap, range_from, range_to)
else:
continue
#----------------------------------------------------------------------
def menu_1_execute(combination_cap):
index = 0
output_file = open('all_indexed_combinations.csv', 'w')
combination_generator = (itertools.combinations(range(1, int(combination_cap) + 1), 6))
for each_combination in combination_generator:
index += 1
output_file.write(str(index) + ', '
+ str(each_combination[0]) + ', '
+ str(each_combination[1]) + ', '
+ str(each_combination[2]) + ', '
+ str(each_combination[3]) + ', '
+ str(each_combination[4]) + ', '
+ str(each_combination[5]) + '\n'
)
#Stamp Combination Cap
output_file.write('Cap: ' + ', ' + str(combination_cap) + '\n')
#Stamp Combinations Total
output_file.write('Total: ' + ', ' + str(index) + '\n')
output_file.close()
os.rename('all_indexed_combinations.csv',str(index) + '_combinations.csv')
#----------------------------------------------------------------------
def menu_2_execute(combination_cap):
index = 0
prime_index = 0
output_file = open('all_prime_indexed_combinations.csv', 'w')
combination_generator = (itertools.combinations(range(1, int(combination_cap) + 1), 6))
for each_combination in combination_generator:
index += 1
if isPrime(index):
prime_index += 1
output_file.write(str(index) + ', '
+ str(each_combination[0]) + ', '
+ str(each_combination[1]) + ', '
+ str(each_combination[2]) + ', '
+ str(each_combination[3]) + ', '
+ str(each_combination[4]) + ', '
+ str(each_combination[5]) + '\n'
)
#Stamp Combination Cap
output_file.write('Cap: ' + ', ' + str(combination_cap) + '\n')
#Stamp Prime Combinations Total
output_file.write('Total: ' + ', ' + str(prime_index) + '\n')
output_file.close()
os.rename('all_prime_indexed_combinations.csv',str(prime_index) + '_prime_combinations.csv')
#----------------------------------------------------------------------
def menu_3_execute(combination_cap, range_from, range_to):
index = 0
output_file = open('Range_F' + str(range_from) + 'T' + str(range_to) + '_combinations.csv', 'w')
combination_generator = (itertools.combinations(range(1, int(combination_cap) + 1), 6))
for each_combination in combination_generator:
index += 1
if index >= range_from:
output_file.write(str(index) + ', '
+ str(each_combination[0]) + ', '
+ str(each_combination[1]) + ', '
+ str(each_combination[2]) + ', '
+ str(each_combination[3]) + ', '
+ str(each_combination[4]) + ', '
+ str(each_combination[5]) + '\n'
)
if index >= range_to:
output_file.close()
break
output_file.close()
#----------------------------------------------------------------------
def menu_4_execute(combination_cap, range_from, range_to):
index = 0
output_file = open('Prime_Range_F' + str(range_from) + 'T' + str(range_to) + '_combinations.csv', 'w')
combination_generator = (itertools.combinations(range(1, int(combination_cap) + 1), 6))
for each_combination in combination_generator:
index += 1
if index >= range_from:
if isPrime(index):
output_file.write(str(index) + ', '
+ str(each_combination[0]) + ', '
+ str(each_combination[1]) + ', '
+ str(each_combination[2]) + ', '
+ str(each_combination[3]) + ', '
+ str(each_combination[4]) + ', '
+ str(each_combination[5]) + '\n'
)
if index >= range_to:
output_file.close()
break
output_file.close()
#----------------------------------------------------------------------
def isPrime(n):
if n < 2:
return False
i = 2
for i in range(2, int(math.sqrt(n) + 1)):
if (n % i == 0):
return False
return True
#----------------------------------------------------------------------
#Initialize Application
main_menu()

Categories