issues looping back to start of program - python

I am having troubles looping back to the start of the program. I am asked to ask the user if they would like to enter another file, if they say yes it will bring them back to the start of the program to input a file name. When I do this, it just restates the previous file entered. I was wondering how to make it so it would ask for another file input. Here is my code:
def main ( ):
file = input("Enter Name of input file: ")
inputfile = open(file, "r")
total = 0
count = 0
num_list = []
#Read and display the file's contents
for line in inputfile:
number = int(line)
total += number
count += 1
num_list.append(number) # append current number to the list
max_number = max(num_list) # get max value from the list of numbers
min_number = min(num_list) # get min value from the list of numbers
range_of_list = (max_number - min_number)
# close the file
inputfile.close()
while True:
print("File Name: ",inputfile.name)
print("Sum: ", total)
print("Count: ", count)
print("Average: ", total / count)
print("Maximum: ", max_number)
print("Minimum: ", min_number)
print("Range: ", range_of_list)
perform_again = input("Would you like to evaluate another file of numbers? (yes/no): ")
if (perform_again == "yes"):
continue
else:
break
main ( )

Your while loop is wrapped around the print statements, so it will just keep printing again and again.
Have it at the start, like the following:
def main():
while True:
file = input("Enter Name of input file: ")
inputfile = open(file, "r")
total = 0
count = 0
num_list = []
# Read and display the file's contents
for line in inputfile:
number = int(line)
total += number
count += 1
num_list.append(number) # append current number to the list
max_number = max(num_list) # get max value from the list of numbers
min_number = min(num_list) # get min value from the list of numbers
range_of_list = (max_number - min_number)
# close the file
inputfile.close()
print("File Name: ", inputfile.name)
print("Sum: ", total)
print("Count: ", count)
print("Average: ", total / count)
print("Maximum: ", max_number)
print("Minimum: ", min_number)
print("Range: ", range_of_list)
perform_again = input(
"Would you like to evaluate another file of numbers? (yes/no): ")
if (perform_again == "yes"):
continue
else:
break
main()

Related

Slot Machine generator in python , two functions are'nt working ( def get_slot_,machine_spin , def print_slot_machine )

import random
MIN_LINES = 1
MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1
ROW = 3
COL = 3
symbol_count = {
"A":2,
"B":4,
"C":6,
"D": 8,
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[],[],[]]
for _ in range(cols):
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
columns.append(value)
columns.append(columns)
return columns
def print_slot_machine(colmuns):
for row in range(len(colmuns[0])):
for i , colmun in enumerate(colmuns):
if i != len(colmun) - 1:
print(colmun[row], end="|")
else:
print(colmun[row], end="")
print()
def deposit():
amount = input("inter the amount of deposit you'd like to add ")
if amount.isdigit():
amount = int(amount)
while amount > 0:
break
else: print("amount must be more than 0")
else: print("Please enter a number ")
return amount
def get_number_of_lines():
lines = input("inter the amount of lines you'd like to add ")
if lines.isdigit():
lines = int(lines)
while MIN_LINES <= lines <= MAX_LINES:
break
else: print("amount must be between 1~3")
else: print("Please enter a number ")
return lines
def get_bet():
while True:
amount = input("Inter the amount of deposit you'd like to bet \n")
if amount.isdigit():
amount = int(amount)
while MIN_BET <= amount <= MAX_BET:
break
else:
print(f"The amount must be between ${MIN_BET}and ${MAX_BET}\n ")
else:
print("Please enter a number ")
return amount
def main():
balance = deposit()
lines = get_number_of_lines()
while True:
bet = get_bet()
total_bet = bet *lines
if total_bet> balance:
print(f"you dont have enough to bet on that amount , your current balance is {balance}")
else:
break
print(f"you're betting {bet},on {lines} lines . total bet is = ${total_bet}")
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
main()
I tried changing the two lines in many different ways but it didnt work plz help
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
i got this code from a utube video called (Learn Python With This ONE Project!) i wrote the same code as but when he excute the code it shows him the Slot machine results ( abcd ) while am not getting it , i hope my question was clear ,,, all i want is to make the functions work and show the results of the random choices
Your problems are all in the get_slot_machine_spin function. Did you ever do a basic debug print of what it returns? You would have immediately seen that it was wrong.
Look at what you're asking. You're creating columns with three empty lists. You then generate a random thing and add it to THAT list, So, after three runs, you'd have [[], [], [], 'A', 'C', 'D']. Then you append THAT list to ITSELF, and repeat. When you see something like columns.append(columns), that's an immediate indication that something is wrong.
You need to create a separate list to hold the individual column values, then you append that list to your master column list, which should start out empty. Like this:
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = []
for _ in range(cols):
row = []
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
row.append(value)
columns.append(row)
print(columns)
return columns

Why is my write to file function overriding my previous file text?

I'm trying to add user entered data to a tuple, then write that tuple on a line in my text file. I'm doing something wrong because only the last call is added to the txt file. Here's my functions:
def write_to_file(tuple1):
with open('student_info.txt', 'w') as f:
f.write(' '.join(x for x in tuple1))
f.write("\n")
def get_student_info(student_name):
tuple1 = ()
tuple1 = tuple1 + (student_name,)
print("\nScores for " + student_name)
print("Enter a test score (or enter Stop to stop):")
count = 2
test_score = input("Test score 1: ")
tuple1 = tuple1 + (test_score,)
while not test_score == "stop" and not test_score == "Stop":
test_score = input("Test score " + str(count) + ": ")
count = count + 1
tuple1 = tuple1 + (test_score,)
last_item = len(tuple1) - 1
tuple1 = tuple1[:last_item]
write_to_file(tuple1)
def read_from_file():
with open('student_info.txt', 'r') as f:
f_contents = f.read()
print(f_contents, end=" ")
And here's my calls in the main section:
open("student_info.txt", "w").close()
student_name = ""
get_student_info("Jenny: ")
get_student_info("Dave: ")
get_student_info("Sammy: ")
get_student_info("Brooke: ")
read_from_file()
My student_info.txt just ends up reading "Brooke:" and then the data added to the tuple on the last call.
If you want to append to a file you need to change the ‘w’ to an ‘a’ for append when you want to write to the file.

How to input 2 items in a record

I was wondering if there was a way to input 2 items into an array (2 dimensional) at least. One part of the array to hold the name of the person that was golfing, and the other part of the array to hold the score of the person that was playing.
scores = []
playerName = "Cynthia"
playerScore = "72"
scoreEntry = [playerName, playerScore]
The code above shows it being hard coded into it so the resulting would be [Cynthia, 72], but I am trying to figure out how to grab the input from the user and tried applying directly to the array, but it ends up coming out to this below.
How many players: 1
Enter a name: Cynthia
Enter a score: 72
Data written out is: C : y
Data written out is: 7 : 2
This is the output im currently getting
Code below for what I used to get this
def main():
golfFile = open ("golf.dat", 'w')
scores = []
SIZE = getSize()
playerName = getName(scores, SIZE)
playerScore = getScore(scores, SIZE)
scoreEntry = [playerName, playerScore]
scores.append(scoreEntry)
for scoreEntry in scores:
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
golfFile.write (fileLine)
print("Data written out is: ", fileLine)
golfFile.close()
def getSize():
SIZE = int(input("How many players: "))
return SIZE
def getName(scores, SIZE):
index = 0
while (index <= SIZE - 1):
nameInput = input("Enter a name: ")
scores.append(nameInput)
index = index + 1
return scores
def getScore(scores, SIZE):
index = 0
while(index <= SIZE - 1):
scoreInput = input("Enter a score: ")
scores.append(scoreInput)
index = index + 1
return scores
main()
Expected output is
[Cynthia, 72]
There is an error that comes up as well
Traceback (most recent call last):
File "d:\Programs\test.py", line 35, in <module>
main()
File "d:\Programs\test.py", line 11, in main
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
TypeError: can only concatenate list (not "str") to list
Also, I do not want to use any libraries at all for this
You're appending to scores in the getName() and getScore() functions, and each of them return the whole scores list. Then you're putting those two references to scores in the scoreEntry list, and then appending that list to scores again. So you've got the lists nested several levels deep, and you never have each name in the same list as the corresponding score.
Instead, you should just read one name and score each time through a single loop. Put those in a scoreEntry tuple, and append that to the scores list.
def main():
scores = []
SIZE = getSize()
for _ in range(SIZE):
playerName = getName()
playerScore = getScore()
scoreEntry = (playerName, playerScore)
scores.append(scoreEntry)
with open ("golf.dat", 'w') as golfFile:
for scoreEntry in scores:
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
golfFile.write (fileLine)
print("Data written out is: ", fileLine)
def getSize():
SIZE = int(input("How many players: "))
return SIZE
def getName():
nameInput = input("Enter a name: ")
return nameInput
def getScore():
scoreInput = int(input("Enter a score: "))
return scoreInput
main()

Python file appears to be empty after a function

Code:
import os, csv
def menu():
print("Welcome to da sporty ting" + "\n" + "Menu options: " + "\n")
print("1 - Run the code")
print("2 - Exit")
menu_choice = int(input("Enter choice: "))
while menu_choice not in (1, 2):
menu_choice = int(input("Error, try again: "))
if menu_choice == 1:
finding_file()
elif menu_choice == 2:
exit()
def finding_file():
print("\n")
print("Text file options" + "\n")
print("1 - testfile 1" + "\n" + "2 - testfile 2" + "\n" + "3 - Other")
txt_menu_option = int(input("Enter choice: "))
print("\n")
while txt_menu_option not in (1, 2, 3):
txt_menu_option = input(input("Error, try again: "))
if txt_menu_option == 1:
filename = "Test1_Votes.txt"
pass
elif txt_menu_option == 2:
filename = "Test2_Votes.txt"
pass
elif txt_menu_option == 3:
filename = str(input("Enter name of txt file (don't include .txt at he end) : "))
filename = filename + ".txt"
file_exists = os.path.exists(filename)
if file_exists == False:
print("File does not exist, returning to menu")
menu()
pass
file_validity(filename)
def file_validity(filename):
f = open(filename, 'r+') # opening file in read/write mode
inv_lines_cnt = 0
valid_list = [0, 0, 1, 2, 3] # sorted list of valid values
lines = f.read().splitlines()
f.seek(0)
f.truncate(0) # truncating the initial file
for l in lines:
if sorted(map(int, l.split(','))) == valid_list:
f.write(l + '\n')
else:
print(l + " is a invalid line")
inv_lines_cnt += 1
print("There were {} invalid line/lines.".format(inv_lines_cnt))
calculate_quota(filename)
def calculate_quota(filename):
f = open(filename, 'r+')
lines = f.readlines()
print("Calculate quota " + str(lines))
seats = 2
line_count = 0
for line in lines:
line_count += 1
quota = 0
quota == int((line_count / (seats + 1)) + 1)
print(quota)
quota_required(quota, lines)
def quota_required(quota, lines):
for line in lines:
lines.rstrip(',')
lines.rstrip('\n')
print(lines)
candidate_fp_votes = [0,0,0,0,0]
for line in lines:
for i in range(5):
if line[i] == 1:
print ("if working")
candidate_fp_votes[i] += 1
print (candidate_fp_votes)
print (candidate_fp_votes)
Text file sample:
1,2,3,0,0
0,0,3,2,1
1,0,0,3,2
1,0,0,2,3
0,1,2,3,0
Currently I have a problem where after file_validity(), the text file just appears to have loaded up as empty as when I re-open the file in the next function, it prints lines as empty. file_validity() just deletes the file, and rewrites the valid votes. As you can see I have tried to find out where the trouble lies. I believe the truncate and seek functions seem to be causing some trouble but I am not sure if this is true. And if it were to be the case, how to fix it.
Any help?
Thanks in advance.

How to repeat blocks of code in Python

I've created a code that allows a user to view the average score of the values that are in the file. In Example the Text File would look like the following:
Text File For Class 1: it is similar for each text file ; 2 and 3. just different names and values
Matt 2
Sid 4
Jhon 3
Harry 6
There are 3 classes altogether in which the user is prompted to choose which class they want to preview.
Code:
def main_menu():
print ("\n Main Menu ")
print ("1.Average Score of class = 'avg'")
main_menu()
option = input("option [avg]: ")
option_class = input("class: ")
one = "1.txt"
two = "2.txt"
three = "3.txt"
if option.lower() == 'avg' and option_class == '1':
with open(one) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '2':
with open(two) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '3':
with open(three) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
Question
If i wanted to Keep Repeating the code above so that the user can keep using it until they want to exit. so, is it possible to put the code into a while loop and only stop the code if the user wants to, i.e the user is prompted if they want to choose another option and class.
NB: there will be other options such as alphabetical order however right now i only want to know how to do it for the average section.
Best thing you can do is to make a loop for user input and write a function for listing the file.
def main_menu():
print ("\n Main Menu ")
print ("1.Average Score of class = 'avg'")
main_menu()
option = ""
options = ["1", "2", "3"]
one = "1.txt"
two = "2.txt"
three = "3.txt"
def read_text_file(file): # standalone function for viewing files to reduce duplicate code
file += ".txt"
with open(file) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
while True:
option = input("option [avg]: ").lower()
if option == "exit":
break # checks if user want to exit a program
else:
option_class = input("class: ")
if option == 'avg' and option_class in options:
read_text_file(option_class)
else:
print("nothing to show, asking again")
print("end of program")
As I mentioned in the comment section, you should leverage the power of functions here. By breaking down your components to manageable pieces, you actually afford yourself readability and flexibility. See code below, where I have two functions, one for averages and one for totals.
def get_class_average(class_number):
filename = "{0}.txt".format(class_number)
try:
with open(filename) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
return avg
except:
print "No file with that name found."
def get_class_total(class_number):
filename = "{0}.txt".format(class_number)
try:
with open(filename) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
return b
except:
print "No file with that name found."
def check_class_number(string_input):
try:
int(string_input)
return True
except ValueError:
return False
if __name__ == "__main__":
while True:
input_val = raw_input(
"Enter class number (enter 'exit' to quit program): ")
if input_val == 'exit':
break
if check_class_number(input_val): # If it's a valid class number.
method = raw_input("Enter method: ")
if method == 'avg':
avg = get_class_average(int(input_val))
print "The average of Class {0} is {1}".format(input_val, avg)
elif method == 'sum':
total = get_class_total(int(input_val))
print "The total of Class {0} is {1}".format(input_val, total)
else:
print "That is not a valid class number."
continue
Sample run:
The really fun part here is that you can even refactor get_class_average and get_class_total to be a single function that checks if the passed in method is avg or sum and returns the respective values from there (this is easily doable since you have practically the same lines of code for both functions, get_class_average just has an extra division involved).
Have fun.
Yes, you can just put your code within a while-loop and prompt the user for input:
def main_menu():
print ("\n Main Menu ")
print ("1.Average Score of class = 'avg'")
# End main_menu()
one = "1.txt"
two = "2.txt"
three = "3.txt"
keepGoing = True
while(keepGoing):
main_menu()
option = input("option [avg]: ")
option_class = input("class: ")
if option.lower() == 'avg' and option_class == '1':
with open(one) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '2':
with open(two) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
if option.lower() == 'avg' and option_class == '3':
with open(three) as f:
the_list = [int(l.strip().split()[-1]) for l in f]
b = sum(the_list)
length = len(the_list)
avg = float(b) / length if length else 0
print ("Average of Class is: ", avg)
# Prompt user for input on whether they want to continue or not:
while(True):
keepGoingStr = input("Would you like to continue? (Y/N)\n>>> ").lower()
if(keepGoingStr[0] == 'y'):
# Keep going
keepGoing = True
break
elif(keepGoingStr[0] == 'n')
# Stop
keepGoing = False
break
else:
print("Sorry, your input did not make sense.\nPlease enter either Y or N for yes or no.")
# end if
# end while - keep going input
# End While(keepGoing)
As mentioned in the comments, though, you should consider breaking up your code into functions.

Categories

Resources