Looking for general feedback + a few small errors - python-3.x

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?

Related

I've tried running the code but it says list index is out of range

from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends

Why the "stop" input doesnt stop the hitorstop() and run the code for the condition elif todo == "stop"

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 : "))

Code Not Compiling- Unable to figure out Issue

I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)

not getting output but they do not show error

import random
dict = {0:'rock',1:'Spock',2:'paper',3:'lizard',4:'scissors'}
def name_to_number(name):
if name == "rock":
return 0
elif name == "spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "csissors":
return 4
else:
print("error:wrong name!")
return
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print("error: wrong number!")
return
def rpsls(palyer_choice):
print(" ")
print("players chooses %s",'player_choice')
player_number = name_to_number(player_choice)
comp_number = random.randrange(0, 5)
print ("Computer chooses %s",' comp_number')
difference = player_number - comp_number
if difference == 0:
print("Player and computer tie!")
elif difference == 3 or difference ==3 or difference == -1 or difference == -2:
print ("computer wins!")
else:
print("Players wins!")
you have to call rpsls function
so add this code in the last of your code
rpsls()

Need some insight on following python 3 code

I was trying to build this basic code for fun but I ran into some weird error. The following code asks for an answer of a basic printed out equation. When the answer is 10 or greater, it is behaving weirdly. I tried to implement some error handling methods (the failure is at int(ansr_raw) I guess). I think a better method will help me out. You don't need to spell out the code for me but pointing me at the right direction will be helpful. The code and output are given below.
code -
import random
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
while True:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
else:
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
break
elif choice in 'no':
continue
else:
print("Wrong choice. continuing game.")
continue
print('answer format invalid')
continue
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")
Here is the output (arrow marks added)-
9 + 3 = ?
Enter the answer: 12
answer format invalid <----
2 - 9 = ?
Enter the answer: 5
wrong answer.
1 - 3 = ?
Enter the answer: 2
Right Answer.
8 + 3 = ?
Enter the answer: 11
answer format invalid <----
1 + 2 = ?
Enter the answer: 3
Right Answer.
6 + 2 = ?
Enter the answer:
The problem is where you say
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
For a single digit number like 9, yes there is a 9 in that string, but there is only a few two digits(01,23,34,45,56,67,78,89), to what you're trying to do, check if the string can become an integer; do this.
try:
ansr = int(ansr_raw)
except ValueError:
Full Code:
import random
import sys
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
running = True
while running:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
try:
ansr = int(ansr_raw)
except ValueError:
answerInv = True
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
sys.exit(0)
elif choice in 'no':
continue
answerInv = False
else:
print("Wrong choice. continuing game.")
answerInv = False
continue
if answerInv:
print('answer format invalid')
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")

Resources