I wrote a program that makes 3 things which user may choose:
def createLeague(): #creates a list with all teams
file = open('league1.txt', 'r')
teams = []
for line in file:
team = line.split()
teams.append(team)
file.close()
return teams
def getTeam(teams): #this function gets a team that user inputs
result = ' '
choice = input('Enter the team: ')
checkforteam = False
for line in teams:
team = line[0]
if choice == team: #check for input team in all lines
result = team
games = line[1]
wins = line[2] #assign all statistics to the variables with
draws = line[3] #appropriate names
loses = line[4]
checkforteam = True
if checkforteam: #if it is True, it will return the team. If False, returns an error message
print(result, games, wins, draws, loses)
else:
print('No such a team')
def getWinner(teams): #returns a leader
winner = ' '
result = 0
loses = 100
for team in teams:
points = int(team[2])*3 + int(team[3])
lose = int(team[4])#counting all points
if points > result: #find a team with maximum points
result = points
winner = team[0]
loses = lose
elif points == result:
if lose < loses:
winner = team[0]
print('Winner: ', winner)
print('Points: ', result)
def updateScore(teams): #update the table
firsteam = input('Home: ')
secondteam = input('Away: ')
goal1 = int(input('Goals scored by home: '))
goal2 = int(input('Goals scored by away: '))
f = open('nhl.txt', 'w')
for team in teams:
komanda = team[0]
matches = int(team[1])
wins = int(team[2])
draws = int(team[3])
loses = int(team[4])
if firsteam == komanda:
if goal1 > goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
elif secondteam == komanda:
if goal1 < goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
newline = komanda+ ' '+ str(matches) + ' ' +str(wins)+ ' '+ str(draws) + ' '+ str(loses)+ '\n'
f.write(newline)
f.close()
print('Saved')
teams = createLeague()
loop = 1 #variable that makes 'while' working until user wants to close the program
while loop == 1:
print('0. Exit')
print('1. Find a team')
print('2. Get a leader')
print('3. Update the results')
x = input('Choose: ')
if x == '1':
getTeam(teams)
elif x == '2':
getWinner(teams)
elif x == '3':
updateScore(teams)
elif x == '0':
print('Goodbye!')
loop = 0
else:
print('Wrong!')
Now I want that when I choose 1, 2 or 3 in IDLE, there will be a GUI window appeared where the function that called in while loop will work. I am stucked about it. How I can do it? Please, just show an example for one of the function.
Related
I'm getting the IndexError on line 50 (the sixth line of checkForDisallowedCharacters while j < len(resultSet[i]):)
I get this error when I input '***er', 't', and 'canpilru' into the console when prompted
Using my print statements I've found that this error occurs when the resultSet array has a length of 141, and when i is 0
resultSet[0] is 'paper' and it clearly exists
If anyone can explain why this is throwing an error I would be very grateful
import csv
import os
import sys
def buildDictionary():
dictionary = []
with open("./wordle-helper/wordle-dictionary.csv", newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
for row in spamreader:
dictionary.append(row)
for i in range(len(dictionary)):
dictionary[i] = dictionary[i][0].lower()
return dictionary
def buildTestWordComposition(testWord):
testWordComposition = []
for i in range(len(testWord)):
if testWord[i] == "*":
testWordComposition.append(i)
return testWordComposition
def buildThreshold(testWord):
threshold = 0
for character in testWord:
if character != "*":
threshold += 1
return threshold
def checkForSoftMatches(dictionary, testWord, threshold):
resultSet = []
for word in dictionary:
testThreshold = 0
for i in range(5):
if testWord[i] == "*":
continue
elif testWord[i] == word[i]:
testThreshold += 1
if testThreshold == threshold:
resultSet.append(word)
return resultSet
def checkForDisallowedCharacters(resultSet, disallowedCharacters):
i = 0
while i < len(resultSet):
print(len(resultSet), i, resultSet[i][0])
j = 0
while j < len(resultSet[i]):
for character in disallowedCharacters:
if resultSet[i][j] == character:
try:
resultSet.remove(resultSet[i])
finally:
i -= 1
j = -1
break
j += 1
i += 1
if i < 0:
i = 0
elif i >= len(resultSet):
break
return resultSet
def checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition):
resultSetChecked = []
threshold = len(requiredCharacters)
m = 0
resultSetCheckedLength = 0
while m < len(resultSetNoDisallowedCharacters):
compareToThreshold = 0
for aCharacter in requiredCharacters:
for number in testWordComposition:
if resultSetNoDisallowedCharacters[m][number] == aCharacter:
compareToThreshold += 1
break
if len(resultSetChecked) != resultSetCheckedLength:
break
if compareToThreshold == threshold:
resultSetChecked.append(resultSetNoDisallowedCharacters[m])
resultSetCheckedLength = len(resultSetChecked)
m += 1
return resultSetChecked
def wordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
dictionary = buildDictionary()
testWordComposition = buildTestWordComposition(testWord)
threshold = buildThreshold(testWord)
resultSet = checkForSoftMatches(dictionary, testWord, threshold)
resultSetNoDisallowedCharacters = checkForDisallowedCharacters(resultSet, disallowedCharacters)
resultSetChecked = checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition)
if not resultSetChecked:
return resultSetNoDisallowedCharacters
return resultSetChecked
def printWordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
print("All possible words are listed below\n\n-----------------------------------------------\n")
for word in wordleHelper(testWord, requiredCharacters, disallowedCharacters):
print(word)
def handlePersistentCharacters(disallowedCharactersComplete):
willDisallowedCharactersPersist = input("Would you like to continue using your previous list of grey letters? (y/n): ")
if willDisallowedCharactersPersist == "y":
return disallowedCharactersComplete
elif willDisallowedCharactersPersist == "n":
return []
else:
print("Please enter a valid character")
handlePersistentCharacters(disallowedCharactersComplete)
def clearConsole():
if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
os.system('clear')
elif sys.platform.startswith('win'):
os.system('cls')
def buildParsed(unparsed):
parsed = []
for letter in unparsed:
parsed.append(letter)
return parsed
def handleUserContinue(disallowedCharactersComplete):
willUserContinue = input("Would you like to use World Helper (tm) again? (y/n): ")
if willUserContinue == "n":
sys.exit()
persistentDisallowedCharacters = handlePersistentCharacters(disallowedCharactersComplete)
if willUserContinue == "y":
promptUser(persistentDisallowedCharacters)
def promptUser(persistentDisallowedCharacters=[]):
clearConsole()
testWord = input("Please enter your Wordle guess in the form of *la*t where 'l', 'a', and 't' are the green letters from your guess, and the '*'s are yellow or grey letters from your guess: ")
requiredCharacters = input("Please enter your letters in yellow here in the form of 'abcxyz' (do not enter letters which are already in your Wordle guess string): ")
disallowedCharacters = input("Please enter your letters in grey here (in the form of 'abcxyz'): ")
requiredCharactersParsed = buildParsed(requiredCharacters)
disallowedCharactersParsed = buildParsed(disallowedCharacters)
disallowedCharactersComplete = persistentDisallowedCharacters + disallowedCharactersParsed
printWordleHelper(testWord, requiredCharactersParsed, disallowedCharactersComplete)
handleUserContinue(disallowedCharactersComplete)
promptUser()
I am trying to improve this program. I am working with Linux. I want to add a menu function where the user can pick an option and based on the option call the respective function, but the program is not working, when I run it in the Terminal it doesn't do anything and doesn't show any errors. Please, I need help to solve the problem and make the program works. Thanks!
Here's what I have so far, still there are some functions that need to develop:
#! /usr/bin/python3
import sys
def menu(self):
print ("""
1. Add an Expense
2. Remove an Expense
3. Add revenue
4. Remove Revenue
5. Exit
""")
option = input ("What would you like to do [Number Only]?")
if option == "1":
self.add_expense()
elif option == "2":
self.remove_expense()
elif option == "3":
self.add_revenue()
elif option == "4":
self.remove_revenue()
else:
self.reset_program()
self.close_program()
return option
def add_expense(self):
def __init__(self):
self.month_balance = 0
self.expenses = 0
self.expense_list = []
self.expense_name = []
self.month_balance_name = []
self.month_balance_list = []
self.prompt_income()
def month_balance_ask(self):
add_month_balance = input('Add monthly balance? [y/n]: ')
return add_month_balance
def month_balance_sum(self):
self.month_balance = sum(self.month_balance_list)
def expense_ask(self):
add_expense = input('Add expense? [y/n]: ')
return add_expense
def expense_sum(self):
self.expenses = sum(self.expense_list)
def month_balance_check(self):
if not self.month_balance_list:
print('Please enter at least one monthly balance. ')
self.prompt_month_balance()
def expense_check(self):
if not self.expense_list:
print('Please enter at least one expense. ')
self.prompt_expense()
def prompt_month_balance(self):
x = False
while not x:
result = self.month_balance_ask()
if result == 'y':
month_balance_input = int(input('Enter monthly balance. [Numbers Only]: '))
self.month_balance_list.append(month_balance_input)
month_balance_name = input('Enter monthly balance name. [Name Only]: ')
self.month_balance_name.append(month_balance_name)
else:
self.month_balance_check()
x = True
self.month_balance_sum()
name = [name for name in self.month_balance_name]
month_balance = [month_balance for month_balance in self.month_balance_list]
month_balancedict = dict(zip(name, month_balance))
for k in incomedict:
print(k + ': ', '$' + str(month_balancedict[k]))
print('Total user monthly balance: ', '$' + str(self.month_balance))
self.prompt_expense()
def prompt_expense(self):
x = False
while not x:
result = self.expense_ask()
if result == 'y':
expense_input = int(input('Enter expense amount. [Numbers Only]: '))
self.expense_list.append(expense_input)
expense_name = input('Enter expense name. [Name Only]: ')
self.expense_name.append(expense_name)
else:
self.expense_check()
x = True
self.expense_sum()
name = [name for name in self.expense_name]
expense = [income for income in self.expense_list]
expensedict = dict(zip(name, expense))
for k in expensedict:
print(k + ': ', '$' + str(expensedict[k]))
print('Total user expenses: ', '$' + str(self.expenses))
self.added_expense()
def added_expense(self):
expenseadded = self.month_balance - self.expenses
if expenseadded < 0:
print('You are in the negative, you have a deficit of ' + '$' + str(expenseadded))
if expenseadded == 0:
print('You have broken even, you are spending exactly as much as you make.')
if expenseadded > 0:
print('You are in the positive, you have a surplus of ' + '$' + str(expenseadded))
another = input('Would you like to run another analysis? [y/n]: ')
if another == 'y':
self.menu()
else:
self.reset_program()
self.close_program()
def remove_expense(self):
print("code goes here")
def add_revenue(self):
print("code goes here")
def remove_revenue(self):
print("code goes here")
def reset_program(self):
self.month_balance = 0
self.expenses = 0
del self.expense_list[0:]
del self.expense_name[0:]
del self.month_balance_name[0:]
del self.month_balance_list[0:]
self.prompt_month_balance()
def close_program(self):
print('Exiting Program.')
sys.exit(0)
I am writing a car rental program on python.
In this function I am trying to modify car details which are added in the details.txt file but I am getting an error "if acc[0] == var[0]:TypeError:'NoneType' object is not subscriptable"
how do I fix this error ?
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
count += 1
mod_file.close()
if exist != True:
print("!!! Can NOT Find The Data !!!")
elif exist == True:
s_list = []
mod_file = open("details.txt", "r")
for s in mod_file:
s = s.strip()
s_list.append(s)
mod_file.close
choice = "Y"
while choice == "Y":
print("\n===============================")
print("---------- MODIFY Cars ----------")
print("---------------------------------")
print("Select the details you wish to modify")
print("1. Type")
print("2. Manufactured Year")
print("3. details of the car")
print("4. car code")
print("5. Daily price rate ( USD $ )")
print("6. back")
while True:
try:
c = int(input("please select a number (1 - 5): "))
modify = ["Type", "Manufactured Year", "details of the car", "car code", "Daily price rate ( USD $ )"]
if c > 0 and c < 6:
new = input("\nType the New " + modify[c - 1] + ":")
var[c - 1] = new
temp = ",".join(var)
s_list[count] = temp
mod_file = open("details.txt", "w")
mod_file.write("")
mod_file.close()
count_file = 0
for s in range(len(s_list)):
mod_file = open("details.txt", "r")
for counting in mod_file:
count_file += 1
mod_file.close()
mod_file = open("details.txt", "a")
if count_file == 0:
mod_file.write(s_list[s])
else:
mod_file.write("\n")
mod_file.write(s_list[s])
mod_file.close()
print("\nDetails UPDATED")
be_exit = input("\nDo you want to modify again? (Y/N): ").upper()
if be_exit == "y":
choice = "y"
else:
modifying(acc)
elif c == 6:
modifying(acc)
else:
print("\n!!! Incorrect Input !!!\n")
continue
except:
print("\n!! NOT a Number !!!\n")
continue
modifying()
You have to do
acc = some_value
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
In your example you haven't defined the variable acc. Using global just say that the variable is a global variable, but you're not assigning a value to it
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
So in my coding class we are required to make a "Dice Poker" game. We need to implement a scoring system, however, mine keeps returning a "None", therefore causing issues when I want to add the accumulated score to the base score of 100, since NoneTypes and integers can not be added. I'm aware that I need to fix whatever is causing the None, but I'm not sure how. I believe the problem could be in the "scoring" function, but perhaps it is more lurking in the later parts (After the #Choosing Last Roll or #Scoring output comments) of the function "diceGame". I'm very new to coding, and after hours of looking at this thing I'm not really sure what I'm looking at anymore. Thank you so much for your help!
Text-based dice game
from random import randint
def rollFiveDie():
allDie = []
for x in range(5):
allDie.append(randint(1,6))
return allDie
def outputUpdate(P, F):
print(P)
print(F)
def rollSelect():
rollSelected = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
selectList = rollSelected.split()
return selectList
def rollPicked(toRollList, diceList):
for i in toRollList:
diceList[int(i) - 1] = randint(1,6)
def scoring(dList):
counts = [0] * 7
for value in dList:
counts[value] = counts[value] + 1
if 5 in counts:
score = "Five of a Kind", 30
elif 4 in counts:
score = "Four of a Kind", 25
elif (3 in counts) and (2 in counts):
score = "Full House", 15
elif 3 in counts:
score = "Three of a Kind", 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
score = "Straight", 20
elif counts.count(2) == 2:
score = "Two Pair", 5
else:
score = "Lose", 0
return score
def numScore(diList):
counts = [0] * 7
for v in diList:
counts[v] = counts[v] + 1
if 5 in counts:
finScore = 30
elif 4 in counts:
finScore = 25
elif (3 in counts) and (2 in counts):
finScore = 15
elif 3 in counts:
finScore = 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
finScore = 20
elif counts.count(2) == 2:
finScore = 5
else:
finScore = 0
return finScore
def printScore(fscore):
print(fscore)
print(" ")
def diceGame():
contPlaying = True
while contPlaying:
playPoints = 30
if playPoints > 9:
playPoints -= 10
else:
print("No more points to spend. Game Over.")
contPlaying = False
playing = input("Would you like to play the Dice Game? (Answer 'y' or 'n'): ")
print(' ')
if playing == 'y':
#First Roll
fiveDie = rollFiveDie()
outputUpdate("Your roll is...", fiveDie)
#Choosing Second Roll/Second Roll execution
pickDie = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
pickDie = pickDie.split()
rollPicked(pickDie, fiveDie)
outputUpdate("Your next roll is...", fiveDie)
#Choosing Last Roll
pickDie = rollSelect()
rollPicked(pickDie, fiveDie)
outputUpdate("Your final roll is...", fiveDie)
#Scoring output
scoring(fiveDie)
finalScore = numScore(fiveDie)
playPoints += finalScore
print(playPoints)
else:
contPlaying = False
def main():
diceGame()
main()