Related
So as the title states I'm simply looking for general feedback on the overall structure of the script, where I could do better (don't have to tell me how, where would be plenty) and things like that. Any feedback, advice, tips or help in general is always greatly appreciated as I'm real keen to learn deeper!
As for the errors...
Errors:
It doesn't seem to save any of the contacts after closing, if the only method of saving it, to save it to a file?
Updating claims to be out of range, which if I'm correct it shouldn't be, unless I'm just not seeing something?
Not exactly an issue but something I've been playing with, with no good result...is it possible to have a for loop w/if statement in a comprehension format without being in a print statement?
My code so far:
"""
This is project that lets the user pretty much create and edit a contact book by giving them options and using their
input to complete the data needed for the contact book.
"""
import sys
contacts = []
lst = []
def ContactBook():
rows, cols = int(input("Please enter the amount of people you want in the contact book: ")), 5
print(contacts)
for i in range(rows):
print(f"All mandatory fields will include *")
for a in range(cols):
if a == 0:
lst.append(input("Enter a name*: "))
if lst[a] == '' or lst[a] == "": sys.exit(f"Failed to provide a name...Exiting the contact book!")
if a == 1: lst.append(input("Enter a number*: "))
if a == 2:
lst.append(input("Enter an email: "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 3:
lst.append(input("Enter a D.O.B (mm/dd/yy): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 4:
lst.append(input("What category (Family/Friends/Work/Others): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
contacts.append(lst)
print(f"Your contacts are:\n{contacts}")
return contacts
def Menu():
print(f"\t\t\t{'Contact Book':*^70}", flush=False)
print(f"Your options are:\n1. Add a Contact\n2. Searching Contacts\n3. Edit Contacts\n4. Delete Contacts\n"
f"5. View Contacts\n6. Delete Everything\n7. Exit the book")
choice = int(input("Please select an option: "))
return choice
def AddingContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts.append(input("Enter a name: "))
elif i == 1: contacts.append(int(input("Enter a number: ")))
elif i == 2: contacts.append(input("Enter a email: "))
elif i == 3: contacts.append(input("Enter a d.o.b (mm/dd/yy): "))
elif i == 4: contacts.append(input("Enter a category: "))
cb.append(contacts)
return cb
def SearchContacts(cb):
s = int(input("Select an option:\n1. Name\n2. Number\n3. Email\n4. D.O.B\n5. Category"))
t, c = [], -1
if s == 1:
q = input("Enter who you want to search: ")
for i in range(len(cb)):
if q == cb[i][0]: c = i, t.append(cb[i])
elif s == 2:
q = int(input("Enter the number you want to find: "))
for i in range(len(cb)):
if q == cb[i][1]: c = i, t.append(cb[i])
elif s == 3:
q = input("Enter the email you want to search: ")
for i in range(len(cb)):
if q == cb[i][2]: c = i, t.append(cb[i])
elif s == 4:
q = input("Enter the date you want to search in mm/dd/yy format: ")
for i in range(len(cb)):
if q == cb[i][3]: c = i, t.append(cb[i])
elif s == 5:
q = input("Enter a category you want to search: ")
for i in range(len(cb)):
if q == cb[i][4]: c = i, t.append(cb[i])
else:
print(f"Invalid search inquiry...")
return -1
if c == -1: return -1
elif c != -1:
ShowContent(t)
return c
def ShowContent(cb):
if not cb: print(f"List has nothing in it...: []")
else: print(f"{[cb[i] for i in range(len(cb))]}")
return cb
def UpdateContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts[0] = (input("Enter a name: "))
elif i == 1: contacts[1] = (int(input("Enter a number: ")))
elif i == 2: contacts[2] = (input("Enter a email: "))
elif i == 3: contacts[3] = (input("Enter a d.o.b: "))
elif i == 4: contacts[4] = (input("Enter a category: "))
cb.append(contacts)
return cb
def RemovingContacts(cb):
q = input("Enter the person you want to remove: ")
x = 0
for i in range(len(cb)):
if q == cb[i][0]: x += 1, print(f"This contact has now been removed: {cb.pop(i)}")
return cb
if x == 0: print(f"Person doesn't exist. Please check the name and try again....")
return cb
def DeleteBook(cb):
return cb.clear()
if __name__ == "__main__":
print(f"Welcome to your new Contact Book! Hope you find it easy to navigate!")
ch = 1
cb = ContactBook()
while ch in (1, 2, 3, 4, 5, 6):
ch = Menu()
if ch == 1: cb = AddingContacts(cb)
elif ch == 2: cb = SearchContacts(cb)
elif ch == 3: cb = UpdateContacts(cb)
elif ch == 4: cb = RemovingContacts(cb)
elif ch == 5: cb = ShowContent(cb)
elif ch == 6: cb = DeleteBook(cb)
else: sys.exit(f"Thank you for using this contact book! Have a great day!")
I plan on using the Pandas module to display the data in table format, is it possible without mySQL?
I am trying to create a Tic-Tac-Toe AI that will never lose. My code works sometimes but it does not work other times. Sometimes it will find the best move and print it out correctly but other times it will just fail. For example, once the AI takes the center if you press nine and take the top right corner then the AI will take a top left corner. Then if you take the bottom right corner the AI takes the middle left tile and then if you take the middle right tile then you will win. I wanted the AI to take the middle right to stop you from winning. I am a beginner programmer so please excuse me if the code is not written in the most optimal way. Why is that? Also can you please elaborate your explanation so I can understand what is wrong? Here is the code:
the_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
def print_board(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
def check_for_win(current_state_of_the_board, player_sign):
if current_state_of_the_board["7"] == current_state_of_the_board["8"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["4"] == current_state_of_the_board["5"] == current_state_of_the_board["6"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["2"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["4"] == current_state_of_the_board["7"] == player_sign:
return "Victory"
elif current_state_of_the_board["2"] == current_state_of_the_board["5"] == current_state_of_the_board["8"] == player_sign:
return "Victory"
elif current_state_of_the_board["3"] == current_state_of_the_board["6"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["7"] == current_state_of_the_board["5"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["9"] == current_state_of_the_board["5"] == current_state_of_the_board["1"] == player_sign:
return "Victory"
else:
return "No Victory"
def get_copy_of_the_board(current_board, move, player_sign):
copy_of_the_board = current_board
if copy_of_the_board[str(move)] == " ":
copy_of_the_board[str(move)] = player_sign
return copy_of_the_board
else:
return copy_of_the_board
def check_for_computer_win():
for number in range(1, 10):
print( check_for_win(get_copy_of_the_board(the_board, number, "X"), "X"))
if check_for_win(get_copy_of_the_board(the_board, number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_win():
for number in range(1, 10):
print(check_for_win(get_copy_of_the_board(the_board, number, "O"), "O"))
if check_for_win(get_copy_of_the_board(the_board, number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_computer_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "X")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "O")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def get_computer_move():
if check_for_computer_win() != "Check next condition":
comp_move = check_for_computer_win()
return comp_move
else:
if check_for_player_win() != "Check next condition":
comp_move = check_for_player_win()
return comp_move
else:
if check_for_computer_forks() != "Check next condition":
comp_move = check_for_computer_forks()
return comp_move
else:
if check_for_player_forks() != "Check next condition":
comp_move = check_for_player_forks()
return comp_move
else:
for move in ["5"]:
if the_board[move] == " ":
comp_move = "5"
return comp_move
for move in ["7", "9", "1", "3"]:
if the_board[str(move)] == " ":
return move
for move in ["4", "8", "6", "2"]:
if the_board[str(move)] == " ":
return move
def game():
count = 0
turn = "computer"
while count < 9:
if turn == "computer":
print("The computer move is: ")
final_computer_move = get_computer_move()
if the_board["1"] == "O":
pass
else:
if final_computer_move == "1":
pass
else:
the_board["1"] = " "
the_board[final_computer_move] = "X"
print_board(the_board)
if check_for_win(the_board, "X") == "Victory":
print("The computer has won!")
exit()
else:
turn = "player"
count += 1
else:
player_move = input("Where would you like to move?")
the_board[player_move] = "O"
print_board(the_board)
if check_for_win(the_board, "O") == "Victory":
print("You have won!")
exit()
else:
turn = "computer"
count += 1
game()
Thanks in advance!!
import random
class Player:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
run = True
def __init__(self):
self.name = input("Enter your name : ")
self.Bet = inputs.bet(self)
self.Aceval = inputs.Aval(self)
class Dealer:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
class inputs:
def bet(self):
"""
takes in the bet from the user and stores it in the player class
:return: output
"""
self.bet = input("Enter the amount for your bet : ")
output = self.bet
if self.bet.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.bet(self)
else:
return int(output)
def Aval(self):
"""
Takes the value for ace and stores it in the player class
:return: output
"""
self.aval = input("Enter the value for ACE (1 or 10) : ")
output = self.aval
if self.aval.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.Aval(self)
elif self.aval.isnumeric() == True:
if self.aval in ["1", "10"]:
return int(output)
else:
print("I understand you suffer braincell deficiency but I need you to fire up those 2 braincells you have and enter the proper number")
return inputs.Aval(self)
def valcalc(card):
"""
takes the card for player.deck and returns the value of that card
:return: card value
"""
if card[0] in ("K", "Q", "J"):
return 10
elif card[0] == "A":
return p.Aceval
else:
if len(card) > 2:
return int(card[0:2])
else:
return int(card[0])
def hitorstop(todo):
if todo.lower() == ("hit" or "stop"):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
if todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
p = Player()
d = Dealer()
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
print("Dealer's card is :" + str(dcard) + "+")
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
hitorstop(input("Do you want to hit or stop : "))
Why does the code below todo == "stop" run when i put in stop as input , it just keeps looping asking for the input again and again if i put "stop" for hitorstop() function
.................................................................................................................................................................................................................................................................................................................................................
You need to replace the line todo.lower() == ("hit" or "stop"): with todo.lower() in ("hit", "stop"): to make it work.
However, this entire condition is redundant in the first place and you can remove it.
You don't need it since you compare the input with "hit" and "stop" later, so it is useless to compare twice.
Here is the replace:
def hitorstop(todo):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
elif todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")
I am trying to create a program that lets the user choose to play rock, paper or scissors. Once they choose what they want to play and the amount of games that they want to play, they will be told if they won or lost.
I want to tally up the amount of times they won or lost, but instead it just prints after each round. Is there a way that I can make it print after the game is completed? I want to show the user the outcome overall at the end
from random import randint
def main():
games = int(input("How many games would you like to play?"))
while games > 0:
games -= 1
comp = computer()
choice = user()
print("You played", choice, "and the computer played", comp)
winner(comp, choice)
def computer():
comp = randint in range (0,3)
if comp == 0:
comp = 'rock'
elif comp == 1:
comp = 'paper'
elif comp == 2:
comp = 'scissors'
return comp
def user():
choice = int(input("choose 0 for rock, 1 for paper, or 2 for scissors: "))
if choice == 0:
choice = 'rock'
elif choice == 1:
choice = 'paper'
elif choice == 2:
choice = 'scissors'
else:
print("invalid input")
return choice
def winner(comp, choice):
tie = 0
win = 0
lose = 0
while True:
if choice == "rock" and comp == "rock":
result = 'tie'
tie += 1
break
elif choice == 'rock'and comp == 'scissors':
result = "you win"
win += 1
break
elif choice == 'rock' and comp == 'paper':
result = "you lose"
lose += 1
break
elif choice == 'paper' and comp == 'paper':
result = 'tie'
tie += 1
break
elif choice == 'paper' and comp == 'scissors':
result = 'you lose'
lose += 1
break
elif choice == 'paper' and comp == 'rock':
result = 'you win'
win =+ 1
break
elif choice == 'scissors' and comp == 'scissors':
result = 'tie'
tie += 1
break
elif choice == 'scissors' and comp == 'paper':
result = 'you win'
win += 1
break
elif choice == 'scissors' and comp == 'rock':
result = 'you lose'
lose +=1
break
else:
print("error")
break
print(result)
print("you won", win,"times, and lost", lose,"times, and tied", tie,"times.")
main()
Declare globals for the win, lose and tie counters
randint(0, 2) is how you get random integer
It's += and not =+
There are couple of mistakes. I added a comment # CORRECTION at the respective lines.
from random import randint
tie = 0
win = 0
lose = 0
def main():
games = int(input("How many games would you like to play?"))
while games > 0:
games -= 1
comp = computer()
choice = user()
print("You played", choice, "and the computer played", comp)
winner(comp, choice)
def computer():
# CORRECTION: randint in range (0,3) always return FALSE. BELOW IS THE CORRECT WAY
comp = randint(0, 2)
if comp == 0:
comp = 'rock'
elif comp == 1:
comp = 'paper'
elif comp == 2:
comp = 'scissors'
return comp
def user():
choice = int(input("choose 0 for rock, 1 for paper, or 2 for scissors: "))
if choice == 0:
choice = 'rock'
elif choice == 1:
choice = 'paper'
elif choice == 2:
choice = 'scissors'
else:
print("invalid input")
return choice
def winner(comp, choice):
# CORRECTION: MAKE ALL THE COUNTERS GLOBAL
global tie
global win
global lose
while True:
if choice == "rock" and comp == "rock":
result = 'tie'
tie += 1
break
elif choice == 'rock'and comp == 'scissors':
result = "you win"
win += 1
break
elif choice == 'rock' and comp == 'paper':
result = "you lose"
lose += 1
break
elif choice == 'paper' and comp == 'paper':
result = 'tie'
tie += 1
break
elif choice == 'paper' and comp == 'scissors':
result = 'you lose'
lose += 1
break
elif choice == 'paper' and comp == 'rock':
result = 'you win'
# CORRECTION: ITS NOT =+ ITS +=
# win =+ 1
win += 1
break
elif choice == 'scissors' and comp == 'scissors':
result = 'tie'
tie += 1
break
elif choice == 'scissors' and comp == 'paper':
result = 'you win'
win += 1
break
elif choice == 'scissors' and comp == 'rock':
result = 'you lose'
lose +=1
break
else:
print("error")
break
print(result)
main()
print("you won", win,"times, and lost", lose,"times, and tied", tie,"times.")