How do I clear positional arguments in my function(s) in Python? - python

There was a looping error with add, but now that I can add data to my txt file, there is this error using 'see' to list my data. Below is the erro:
TypeError:list_champs() takes 0 positional arguments but 1 was given.
I cannot see where I added a parameter unknowingly that doesn't need one in my current code.
# file = open("champs.txt", "w+")
FILENAME = "champs.txt"
def write_champs(champs):
with open(FILENAME, "w") as file:
for champ in champs:
file.write(champ + "\n")
def read_champs():
champs = []
with open(FILENAME) as file:
for line in file:
line = line.replace("\n", "")
champs.append(line)
return champs
def list_champs():
for i in range(len(champs)):
champ = champs[i]
print(str(i+1) + " - " + champs)
print()
def add_champ(champs):
champ = input("Champion: ")
#year = input("Season: ")
#champ = []
champs.append(champ)
#champ.append(year)
write_champs(champs)
print(champ + " was added.\n")
def display_menu():
print("Premier League Champions")
print("++++++++++++++++++++++++")
print("COMMANDS")
print("see - See the list of Champions")
print("add - Add a Champion to the list")
print("exit - Exit program")
print()
def main():
display_menu()
champs = read_champs()
while True:
command = input("Enter command: ")
if command == "see":
list_champs(champs)
elif command == "add":
add_champ(champs)
elif command == "exit":
print("Later!")
break
else:
print("Input not valid. Try again.")
if __name__ == "__main__":
main()
As always help is much appreciated!

You need to change your def list_champs to support arguments:
def list_champs(champs):
for i in range(len(champs)):
champ = champs[i]
print(str(i+1) + " - " + champs)
print()

function definition
def list_champs():
function call
list_champs(champs)
Do you want the function to take an argument, or not?
Fix one or the other, depending on your intended design.

Related

How do I write input to files in one line and store multiple inputs to the file and be able to read them?

I'm a self taught programmer and im trying to make a ticketing system in Python where it accepts multiple inputs and reads from the file depending on the number of tickets. However, the previous inputs get overwritten by the newer inputs and I can't seem to fix it.
The output I get is like this:
J
a
k
e
25
M
a
l
e
But I'd like for the output to look like this:
Jake;25;Male
I've attached the code of this program below. Any help would be greatly appreciated. Thank you.
import sys, select, os
from os import system
def option_1():
with open(input("Input file name with extension: "), 'w+') as f:
people = int(input("\nHow many tickets: "))
name_l = []
age_l = []
sex_l = []
for p in range(people):
name = str(input("\nName: "))
name_l.append(name)
age = int(input("\nAge: "))
age_l.append(age)
sex = str(input("\nGender: "))
sex_l.append(sex)
f.flush()
for item in name:
f.write("%s\n" %item)
for item in [age]:
f.write("%s\n" %item)
for item in sex:
f.write("%s\n" %item)
x=0
print("\nTotal Ticket: ", people, '\n')
for p in range(1, people + 1):
print("Ticket No: ", p)
print("Name: ", name)
print("Age: ", age)
print("Sex: ", sex)
x += 1
def option_2():
with open(input('Input file name with extension: '), 'r') as f:
fileDir = os.path.dirname(os.path.realpath('__file__'))
f.flush()
f_contents = f.read()
print("\n")
print(f_contents, end = '')
def main():
system('cls')
print("\nTicket Booking System\n")
print("\n1. Ticket Reservation")
print("\n2. Read")
print("\n0. Exit Menu")
print('\n')
while True:
option = int(input("Choose an option: "))
if option < 0 or option > 2:
print("Please choose a number according to the menu!")
else:
while True:
if option == 1:
system('cls')
option_1()
user_input=input("Press ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
elif option == 2:
system('cls')
option_2()
user_input=input("Press ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
else:
exit()
if __name__ == "__main__":
main()
If you have a recent version of python you can use an f-string to compose the format you require.
You need a loop to iterate over the information you have collected.
You may just need this:
...
f.flush()
for name,age,sex in zip(name_l, age_l, sex_l):
f.write(f"{name};{age};{sex}\n")
...
Also, the printout to the console needs a similar loop:
print("\nTotal Ticket: ", people, '\n')
for p,(name,age,sex) in enumerate(zip(name_l, age_l, sex_l), start = 1):
print("Ticket No: ", p)
print("Name: ", name)
print("Age: ", age)
print("Sex: ", sex)

How to import content from a text file and add them to variables

I have a settings file for a monopoly like game I'm making, the settings file has parameters like the number of people playing and whatnot, I would like to know how to import the settings from that text file and bring it into different variables, for example, having number of players in the settings file go to a numPlayers variable in the actual code so I can use it for other games and also usee the settings in the code
This is my code:
def inputs(line, typeinp=None, start=None, end=None):
while True:
string = input(line)
if typeinp != None:
try:
if typeinp == "string":
string = str(string)
elif typeinp == "integer":
string = int(string)
if start != None and end != None:
while not (string >= start and string <= end):
print("Please input a number between", str(start) + "-" + str(end))
string = int(input(line))
break
except:
print("Plese input a", typeinp)
else:
break
return string
# Settings file, if user chooses to run setup this is all the setup questions
def gameSettingsSetup():
settingsCheck = open("settings.txt", "r")
print("Lets setup")
# Int Setup questions
numPlayers = str(inputs('How many real players are playing: ', "integer"))
numAIplayers = str(inputs('How many AI players will be playing?: ', "integer"))
AILevel = str(inputs("What AI difficulty level would you like? (Easy, Normal, Hard): "))
while True:
if AILevel == "Easy" or AILevel == "Normal" or AILevel == "Hard":
startingMoney = str(inputs("How much money does everyone start with? Max: 10 000 (Keep in mind "
"this does not affect the property prices) ", "integer", 100, 10000))
break
else:
print("Please enter a valid input (make sure to capitalize the first letter)")
AILevel = str(inputs("What AI difficulty level would you like? (Easy, Normal, Hard): "))
# sends over the settings into the text file as well as monoset check
if "MonoSet1-1" in settingsCheck.read():
with open("settings.txt", "w") as file:
file.write("MonoSet1-1: true" + "\n")
file.write("numPlayer: " + numPlayers + "\n")
file.write("numAIplayer: " + numAIplayers + "\n")
file.write("AI Level: " + AILevel + "\n")
file.write("startingMoney: " + startingMoney + "\n")
file.close()
# Allows for access to the settings file and drops values into a list
settings = []
with open("settings.txt") as file:
for line in file:
line = line.split(":")
line = line[1]
line = line.rstrip("\n")
line = line[1:]
line = line.split(" ")
try:
for x in range(len(line)):
line[x] = int(line[x])
line = (line[0], line[1])
except:
line = line[0]
settings.append(line)
file.close()
print("Alright the setup is complete, Your game will start now....")
time.sleep(1)
return settingsCheck, settings

How can I write an array to a .txt file, and then fill an array with the same.txt file?

So I'm doing a ToDo app, and I need to save an array of sentences and words to a .txt file. I have done some research but haven't found any tutorials that explain it well enough so I could understand it. As I said I'm using Python 3. Code below:
# Command line TO-DO list
userInput = None
userInput2 = None
userInput3 = None
todo = []
programIsRunning = True
print("Welcome to the TODO list made by Alex Chadwick. Have in mind
that closing the program will result in your TODO"
" list to DISAPPEAR. We are working on correcting that.")
print("Available commands: add (will add item to your list); remove
(will remove item from your list); viewTODO (will"
" show you your TODO list); close (will close the app")
with open('TODOList.txt', 'r+') as f:
while programIsRunning == True:
print("Type in your command: ")
userInput = input("")
if userInput == "add":
print("Enter your item")
userInput2 = input("")
todo.append(userInput2)
continue
elif userInput == "viewTODO":
print(todo)
continue
elif userInput == "remove":
print(todo)
userInput3 = input("")
userInput3 = int(userInput3)
userInput3 -= 1
del todo[userInput3]
continue
elif userInput == "close":
print("Closing TODO list")
programIsRunning = False
continue
else:
print("That is not a valid command")
This sounds like a job for pickle!
Pickle is a built-in module for saving objects and data in Python. To use it, you will need to put import pickle at the top of your program.
To save to a file:
file_Name = "testfile.save" #can be whatever you want
# open the file for writing
fileObject = open(file_Name,'wb')
# this writes the object to the file
pickle.dump(THING_TO_SAVE,fileObject)
# here we close the fileObject
fileObject.close()
To load from a file:
# we open the file for reading
fileObject = open(file_Name,'r')
# load the object from the file
LOADED_THING= pickle.load(fileObject)
fileObject.close()
The code in this answer was taken from here.
I hope that helps!
You use a simple text file to store your TODO - items and retrieve them from it:
import sys
fn = "todo.txt"
def fileExists():
"""https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-fi
answer: https://stackoverflow.com/a/82852/7505395
"""
import os
return os.path.isfile(fn)
def saveFile(todos):
"""Saves your file to disk. One line per todo"""
with open(fn,"w") as f: # will overwrite existent file
for t in todos:
f.write(t)
f.write("\n")
def loadFile():
"""Loads file from disk. yields each line."""
if not fileExists():
raise StopIteration
with open(fn,"r") as f:
for t in f.readlines():
yield t.strip()
def printTodos(todos):
"""Prints todos with numbers before them (1-based)"""
for i,t in enumerate(todos):
print(i + 1, t)
def addTodo(todos):
"""Adds a todo to your list"""
todos.append(input("New todo:"))
return todos
def deleteTodos(todos):
"""Prints the todos, allows removal by todo-number (as printed)."""
printTodos(todos)
i = input("Which number to delete?")
if i.isdigit() and 0 < int(i) <= len(todos): # 1 based
r = todos.pop(int(i) - 1)
print("Deleted: ", r)
else:
print("Invalid input")
return todos
def quit():
i = input("Quitting without saving [Yes] ?").lower()
if i == "yes":
exit(0) # this exits the while True: from menu()
def menu():
"""Main loop for program. Prints menu and calls subroutines based on user input."""
# sets up all available commands and the functions they call, used
# for printing commands and deciding what to do
commands = {"quit": quit, "save" : saveFile, "load" : loadFile,
"print" : printTodos,
"add": addTodo, "delete" : deleteTodos}
# holds the loaded/added todos
todos = []
inp = ""
while True:
print("Commands:", ', '.join(commands))
inp = input().lower().strip()
if inp not in commands:
print("Invalid command.")
continue
# some commands need params or return smth, they are handled below
if inp == "load":
try:
todos = [x for x in commands[inp]() if x] # create list, no ""
except StopIteration:
# file does not exist...
todos = []
elif inp in [ "save","print"]:
if todos:
commands[inp](todos) # call function and pass todos to it
else:
print("No todos to",inp) # print noting to do message
elif inp in ["add", "delete"]:
todos = commands[inp](todos) # functions with return values get
# todos passed and result overwrites
# it
else: # quit and print are handled here
commands[inp]()
def main():
menu()
if __name__ == "__main__":
sys.exit(int(main() or 0))

Python says: "expected an indented block"

I've been playing around with Python a bit recently and have come across this error when creating functions. I can't seem to fix it :(. CODE:
Python
#Python
choice = input('Append Or Write?')
if choice == "write":
def write():
pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
if choice == "append":
def append():
# Making a txt file
#Append
pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
You forgot to call your functions that you defined. pass may also be causing the statements in your function to get ignored, remove pass.
Reformatting your code:
#Python
def append():
# Making a txt file
#Append
# pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
def write():
# pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
choice = input('Append Or Write?')
if choice == "write":
write()
if choice == "append":
append()

Function is not getting called

I have below code where I have two functions print_menu() and pStockName()
def print_menu():
print ("\t\t\t\t 1. Get Stock Series ")
print ("\t\t\t\t 2. Invoke Stocks.")
print ("\t\t\t\t 3. Generate DC Stock List . ")
print ("\t\t\t\t 4. QUIT")
def pStockName():
global StockList, fStockList
pStockList = []
fStockList = []
StockList = str(raw_input('Enter pipe separated list of StockS : ')).upper().strip()
items = StockList.split("|")
count = len(items)
print 'Total Distint Stock Count : ', count
items = list(set(StockList.split("|")))
# pipelst = StockList.split('|')
# pipelst = [i.split('-mc')[0] for i in StockList.split('|')]
# pipelst = [i.replace('-mc','').replace('-MC','').replace('$','').replace('^','') for i in StockList.split('|')]
pipelst = [i.replace('-mc', '').replace('-MC', '').replace('$', '').replace('^', '') for i in items]
# pipelst = [Stock.rsplit('-mc',1)[0] for Stock in pipelst]
filepath = '/location/Stock_data.txt'
f = open(filepath, 'r')
for lns in f:
split_pipe = lns.split(':', 1)
if split_pipe[0] in pipelst:
index = pipelst.index(split_pipe[0])
pStockList = split_pipe[0] + "|"
fStockList.append(pStockList)
del pipelst[index]
# f.close()
for lns in pipelst:
print bcolors.red + lns, ' is wrong Stock Name' + bcolors.ENDC
if lns:
uResp = str(raw_input('Do You Want To Continue with option 0 [YES|Y|NO|N] : ')).upper().strip()
if uResp == "NO" or uResp == "N":
os.system("tput clear")
print bcolors.FAIL + "\n PLEASE USE OPTION 0 TO ENTER THE Stock NAMES BEFORE PROCEEDING." + bcolors.ENDC
# StockList = None
print_menu()
else:
pStockName()
f.close()
In above code you must be seeing in 4th last line I am calling print_menu() function. But it is just printing the content of print_menu() function not doing any operation and going to pStockName() function. Follow operation I want to execute from print_menu() function when I am calling it:
while choice >= 1 and choice < 4:
if choice == 4:
os.system("tput clear")
if StockList:
uResp = str(raw_input(
bcolors.FAIL + 'Do you need to move : ' + StockList + ' ? Press Y To Go Back to Main Menu and N to Quit [YES|Y|NO|N] : ')).upper()
if uResp == "NO" or uResp == "N":
print bcolors.HEADER + "GoodBye." + bcolors.ENDC
break
I mean to say when I am calling print_menu() function in pStockName() function in 4th last line from pStockName() function it should print the content of print_menu() function and when I press 4 it should perform the operation quit. But when I pressing any of the option from 1 to 4 it going to pStockName() function only.
Please help me what I am doing wrong here.
I'm a bit new here, but I do not see where you assign the keyboard input into variable "choice". Therefore, the program will not recognize what the end user input is. My suggestion is to assign "choice" into raw_input Like so:
choice = raw_input()
if choice == "4": # alternatively, perform int(choice) == 4
print ("yes")
I hope this helps!

Categories