python trouble getting code to work - python

update so it seems like no matter what i do or type it asks
what would you like to add?
instead of doing the other options it just keeps asking this
it should only be asking this if the user types a
this is a 2 issue thing im having and the main original post is here
How to debug errors in Python?
but the bigger issue im having is i cant get the bottom half of my code to work
it just ignores the inputs given to it and continues to add them to the list
#.....
elif user == "d" :
listdelete = input("what item do you want deleted")
list.remove (listdelete)
elif user == "p" : # prints the list
print (list)
elif user == "x" : # exits the program
print ("good bye")
print ("!!!!!!that is not a choice!!!!!!")
#right now everything is being called through a single procedure
print (option())
and on the bottom here is going to be the entire code sorry for pasting the entire code on the bottom here but i thought it would be easy to understand the whole issue if i showed the whole code and then the section thats not working since its all under one procedure
list = []
def option() :
print ("(a) -to add item ")
print ("(d) -to delete item")
print ("(p) -to see items on your list")
print ("(x) -to exit ")
#above just prints out user options with a input after
user = input("please select a choice")
if user == "a" :
item = input("what would you like to add? ")
list.append (item)
# next im going to ask if they would like to add another item
more = input(" would you like to add something else? yes or no")
while more == "yes":
if more == "yes" :
item = input("what else would you like to add? type b to back ")
if item == "b" :
print (option())
else :
list.append(item)
elif more == "no" :
print (option())
#.....
elif user == "d" :
listdelete = input("what item do you want deleted")
list.remove (listdelete)
elif user == "p" : # prints the list
print (list)
elif user == "x" : # exits the program
print ("good bye")
print ("!!!!!!that is not a choice!!!!!!")
#right now everything is being called through a single procedure
print (option())

I have updated your code which still has flaws and exploits the mutability of the list datatype but does work as you would expect it:
#!/usr/bin/env python
def AddElement(collection):
elementToAdd = input("What would you like to add: ")
collection.append(elementToAdd)
return collection
def DeleteElement(collection):
print("You have the following items:", collection)
elementToDelete = input("What item do you want deleted: ")
for elements in collection:
if elements == elementToDelete:
collection.remove(elements)
print("You have the following items left:", collection)
return collection
def WriteMenu():
print("(a) -to add item")
print("(d) -to delete item")
print("(p) -to see items on your lst1")
print("(x) -to exit")
return True
def option():
WriteMenu()
UserInput = input("Please select a choice: ")
while UserInput:
if UserInput == "a":
AddElement(collection)
elif UserInput == "d":
DeleteElement(collection)
elif UserInput == "p":
print(collection)
elif UserInput == "x":
print("Good bye!")
break
WriteMenu()
UserInput = input("Please select a choice: ")
else:
print(collection)
#right now everything is being called through a single procedure
collection = []
option()

Related

Part of my Python Code is not functioning, but all other parts are

I have a code in Python that I recently created for a Maths Assignment, but part of it is not working.
So it asks the user to select a choice, but when I tested it, all other options (which I took out) worked for me, but when I entered "4", it wouldn't work. Instead, it just reprinted everything and asked for my choice again.
FYI: I have taken out the other options, because they aren't needed here.
Does anybody have a solution though? Because whatever I do, it doesn't seem to function or work.
Here's the part of my code that has the problem:
#This part greets the user, and lets the user know that the application has started
print("Hello there!")
#This starts off the loop, but this variable may be changed later on
cont = "yes"
#This is the actual loop
while cont == "yes" or cont == "Yes" or cont == "YES":
print("Choose an option below:")
#This shows the options
print("1) Calculate the value of different product sizes")
print("2) Calculate the sale price")
print("3) Calculate the discount")
print("4) Create a shopping list")
print("5) Create a receipt that shows costs")
print("6) Exit")
#This part lets the user choose what they would like to do
option = float(input("Choose an option (1/2/3/4/5/6): "))
#This is what happens if the user chooses Option 4
#This is the "Shopping list" part of the application below
if option == 4:
sl = []
import os,sys,time
try:
f = open("Shopping_List.txt","r")
for line in f:
sl.append(line.strip())
f.close
except:
pass
def mainScreen():
os.system("cls")
print("Just a couple reminders:")
print("Your shopping list contains", len(sl), "items so far.")
print("If items aren't deleted from the list after use, they'll remain there.")
print("Choose an option below:")
print("1) Add an item to the list")
print("2) Delete an item from the list")
print("3) View the list")
print("4) Exit")
asdf = input("Enter your choice here: ")
if len(asdf) > 0:
if choice.lower()[0] == "1":
addScreen
elif choice.lower()[0] == "2":
deleteScreen()
elif choice.lower()[0] == "3":
viewScreen()
elif choice.lower()[0] == "4":
sys.exit()
else:
mainScreen()
else: mainScreen()
def addScreen():
global sl
os.system('cls')
print("Press ENTER if you would like to exit.")
print("Enter the name of the item you would like to add below.")
item = input("Name of item: ")
if len(item) > 0:
sl.append(item)
print("Item has been added.")
saveList()
time.sleep(1)
addScreen()
else:
mainScreen
def viewScreen():
os.system('cls')
for item in sl:
print(item)
print("Press ENTER to exit.")
input()
mainScreen()
def deleteScreen():
global sl
os.system('cls')
count = 0
for item in sl:
print(count, ") - ", item)
count = count + 1
print("Enter the number corresponding to the item you would like to delete.")
chce = ("Number: ")
if len(chce) > 0:
try:
del sl[int(chce)]
print("Item has been deleted.")
saveList()
time.sleep(1)
except:
print("Invalid number.")
time.sleep(1)
deleteScreen()
else:
mainScreen()
def saveList():
f = open("Shopping_List.txt", "w")
for item in sl:
f.write(item + "\n")
f.close()
mainScreen
Thanks in advance.
Here's the solution:
The line at the bottom of my code should be changed from mainScreen to mainScreen(), otherwise it wouldn't do anything. And also, if choice.lower()[0] == "1": addScreen should be if choice.lower()[0] == "1": addScreen(), or otherwise, that part of my code wouldn't function either, which would create further problems.
Credit goes to Keith John Hutchison and MaxiMouse for helping me figure out how to solve my problem, why it didn't work, and for also suggesting improvements to my code.

'while' loop not behaving as expected

Background:
I have made a program that takes a text input, applies encryption (a simple cipher) and saves the output to a list - if desired. Messages can also be decrypted.
The program is navigated through an options menu:
1. Encrypt a message
2. View encrypted messages
3. Decrypt a message
To allow all sections of the program to access the same list (variable) of saved messages, I have written it within a class. Within the class exist def's that call on this list.
Only the 'encrypt a message' bit has been written so far.
Problem:
The user decision flow is made with two Y/N choices.
However, the choices do not work - even if the user types in 'N' - my program thinks they have typed 'Y' in both cases.
def encrypt():
def save_cip():#This function allows the user to save the ciphered message to the ciphered_messages if they choose
choosing = True
while choosing:
save_choice = input("Would you like to save your Ciphered message? (Y/N)\n")
if save_choice == "Y" or "y":
print("You chose yes")
cct.ciphered_messages.append(' '.join(["Message", str(len(cct.ciphered_messages)), ":", cipher]))
choosing = False
elif save_choice == "N" or "n":
print("You chose no")
choosing = False
continue
else:
print("That was not a valid entry, please enter Y or N only")
continue
I think the problem lay within the scope, and that somehow the same variable is not being referenced when setting and reading Y or N. I have been going up and down the same code for about 3 hours and still nothing, declaring all variables in many different places with no luck, so any advice greatly appreciated.
Full executable code:
class cct:
print("Welcome to the CaeserCipher tool v1.0")
menu_state = "main" #This is used to record what state the program is in
unciphered_messages = [] #Decrypted messages are saved here
ciphered_messages = [] #Encrypted messages are saved here
def menu(): #This is the main menu interface
while cct.menu_state == "main": #This while
cct.menu_state = input("What would you like to do? \n 1: Encrypt a Message \n 2: View Encrypted Messages \n 3: Decrypt a message\n")
if cct.menu_state == "1":
cct.encrypt()
elif cct.menu_state == "2":
cct.view()
elif cct.menu_state == "3":
cct.decrypt()
elif cct.menu_state == "main":
print("\n\nWelcome back to the menu!\n\n")
else:
print("You did not enter a valid choice. Please enter a number between 1 and 3.\n")
cct.menu_state = "make_choice"
continue
def encrypt():
def save_cip():#This function allows the user to save the ciphered message to the ciphered_messages if they choose
choosing = True
while choosing:
save_choice = input("Would you like to save your Ciphered message? (Y/N)\n")
if save_choice == "Y" or "y":
print("You chose yes")
cct.ciphered_messages.append(' '.join(["Message", str(len(cct.ciphered_messages)), ":", cipher]))
choosing = False
elif save_choice == "N" or "n":
print("You chose no")
choosing = False
continue
else:
print("That was not a valid entry, please enter Y or N only")
continue
#This while loop continually takes messages, gives the option of saving, and asks if you want to cipher another
while cct.menu_state == "1":
text = input("Enter your message: ") #Enter the message you wish to cipher
cipher = '' #Create a string for the cipher
for char in text: #This for sub-loop will increment each character by 1. e.g. A -> B, T -> U, Z -> A
if not char.isalpha():
continue
char = char.upper()
code = ord(char) + 1
if code > ord('Z'):
code = ord('A')
cipher += chr(code)
print(' '.join(["Your ciphered message is:", cipher]))
save_cip()
print(cct.ciphered_messages)
#This sub-while loop is reponsible for checking if you want to cipher another message
#and making sure the user has made a valid choice
choosing_another = True
while choosing_another == True:
choice_variable = input(' '.join(["You have", str(len(cct.ciphered_messages)), "saved messages \n", "Would you like to Cipher another? (Y/N)\n"]))
if choice_variable == "Y" or "y":
print("You chose yes")
choosing_another = False
elif choice_variable == "N" or "n":
print("You chose no")
cct.menu_state = "main"
choosing_another = False
else:
choice_variable = input("That was not a valid entry, please enter Y or N only: \n")
continue
return
def view():
#TO BE CODED
return
def decrypt():
#TO BE CODED
return
cct.menu()
This is always true:
if save_choice == "Y" or "y":
bacause its interpreted as :
if (condition) or (condition):
the 1st condition is (save_choice == "Y")
the 2nd condition is just ( "y" ) which python interprets as 'True'
So the whole condition is always True.
U probably mean:
if save_choice == "Y" or save_choice == "y":
Or better :
if save_choice.lower() == "y":
Not a python programmer, but i don't think python allows a "implied" subject for the or operator
--> IF save_choice == "Y" OR save_choice == "y" :

Python while loop isn't doing as expected

I'm trying to complete my assignment and have been struggling. The idea is that you select report type, A or T. From there you enter keep entering integers until you quit. Once you quit, it should print out the total of integers added together for report 'T'; or for report 'A', it should print the total, plus a list of integers entered.
The problem I'm encountering at the moment is from report 'T', once I'm entering integers nothing will make it error or quit. It just keeps constantly asking me to enter another integer. Then from report 'A', every integer I enter it just comes up with 'invalid input'. I'm sure there are probably plenty more issues with my code but can't get past these ones at the moment. Any pointers would really be appreciated. Thanks
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an ingteger to add to the total or \"Q\" to quit: ")
if report.upper == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
while True:
if report.upper() in "A T":
adding_report(report)
else:
print ("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")
The in operator needs a collection of possible values. Use
if report.upper() in ("A", "T")
or (closer to what you have)
if report.upper() in "A T".split()
Your first problem is in this line:
if report.upper == "A":
This always evaluates to False, because report.upper is a function object, not a value. You need
if report.upper() == "A":
to return the value. You would also do well to rename the input variable and replace its value to the internal one you want:
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
report = report.upper()
This saves you the mess and time of calling upper every time you access that letter.
Please look through your code for repeated items and typos; you'll save headaches in the long run -- I know from personal experience.
Try this
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an integer to add to the total or \"Q\" to quit: ")
#You used "report.upper" instead of "report.upper()"
if report.upper() == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
#You forgot ot add this : "items.append(user_number)"
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
break
#Add this for loop termination: "or 0 to quit: "
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\" Or 0 to quit: ")
while True:
#it should be this ""if report.upper() in "A" or "T":"" not this ""if report.upper() in "A T":""
if report.upper() in "A" or "T":
adding_report(report)
#The condition below terminates the program
elif report == '0':
break
else:
print("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")

Allowing users to create multiple list in Python

I want to user to input information and print out the total list. However, when the user input another list it only prints out the first list. How can I make the program print the users total input. Here's my code.
listing = []
class Car:
def __init__(self, ownerName=None, model=None, make=None, price=None):
self.ownerName = ownerName
self.model = model
self.make = make
self.price = price
def input(self):
print "Please update car info \n"
while True:
i = 0
listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
print "Updated"
print listing[i].ownerName, listing[i].model, listing[i].make, listing[i].price
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() == "y":
i += 1
continue
else:
break
# search a car and print its information. Exit when user input is 'exit'
def menu():
x = Car()
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) search a car and print info\n" \
"\"exit\" Exit")
if choice == "1":
x.input()
elif choice == "2":
print "Price"
elif choice == "3":
print "Search and Print info"
menu()
#mhawke's answer should fix your problem. However, I do not like the idea of creating objects of a class from one of its functions. Check the edited code below.
listing = []
class Car:
def __init__(self, ownerName=None, model=None, make=None, price=None):
self.ownerName = ownerName
self.model = model
self.make = make
self.price = price
def input_car():
print "Please update car info \n"
i = 0
while True:
listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
print "Updated"
print listing[i].ownerName, listing[i].model, listing[i].make, listing[i].price
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() == "y":
i += 1
continue
else:
break
# search a car and print its information. Exit when user input is 'exit'
def menu():
#x = Car()
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) search a car and print info\n" \
"\"exit\" Exit")
if choice == "1":
input_car()
elif choice == "2":
print "Price"
elif choice == "3":
print "Search and Print info"
menu()
I cleaned up the code a little bit. I should work now. Option 3 gives you a complete listing of all cars so far, so youhave an example to build on.
listing = []
class Car:
def __init__(self, ownerName=None, model=None, make=None, price=None):
self.ownerName = ownerName
self.model = model
self.make = make
self.price = price
#to have a useful method for our example I overwrite the __str__ method from object
def __str__(self):
return ",".join([self.ownerName, self.model, self.make, self.price])
#input does not handle aspects of car, therefore it should be not a method of car
def input():
print "Please update car info \n"
while True:
# there is no need for 'i' so I removed it
car = Car(raw_input("Owner Name"),
raw_input("Model?"),
raw_input("Make?"),
raw_input("Price?"))
listing.append(car)
print "Updated"
print car #possible since __str__ is overwritten
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() == "n":
break
def menu():
keep_running = True
#added a while loop so the user stays in the program until he types 'exit'
#changed option '3' to have a working example to build on
while keep_running:
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) list all cars\n" \
"\"exit\" Exit")
if choice == "1":
input()
elif choice == "2":
print "Price"
elif choice == "3":
print "\n".join(map(str, listing))
elif choice == "exit":
keep_running = False
menu()
That's because you reset i on each iteration of your while loop.
Move the line:
i = 0
to the line before the while True:
That should fix the immediate problem, however, your code uses an unusual design. You should not create a Car object in order to create further instances of Cars which are then inserted into a global list.
At a minimum you could make input() a static method and have it return a list of Car instances to the caller. Then you can do away with the global listing variable. Also, you don't actually need to keep a counter in i you can just use -1 as the subscript to access the last item in the list:
#staticmethod
def input(listing=None):
if listing is None:
listing = []
print "Please update car info \n"
while True:
listing.append(Car(raw_input("Owner Name"), raw_input("Model?"), raw_input("Make?"), raw_input("Price?")))
print "Updated"
print('{0.ownerName} {0.model} {0.make} {0.price}'.format(listing[-1]))
addOn = raw_input("Continue? (Y/N)")
if addOn.lower() != "y":
break
return listing
Using a static method is good here because input() is related to Car objects so it makes sense to package that function with the class.
Now you can call input() without creating an instance of a Car. In your menu() function remove the x = Car() and change x.input() to listing = Car.input(). Or, if you want to append to an existing "listing" list, call Car.input(listing) which will append new input to listing. You can then print the returned list to see all user input:
def menu():
print "PLease choose an option (1-4):\n"
choice = raw_input("1) input\n" \
"2) change price and owner\n" \
"3) search a car and print info\n" \
"\"exit\" Exit")
if choice == "1":
listing = Car.input()
# print out all user entered cars
for car in listing:
print('{0.ownerName} {0.model} {0.make} {0.price}'.format(car))
elif choice == "2":
print "Price"
elif choice == "3":
print "Search and Print info"

My programme enteres a blank row before entering data to CSV file how to delete the row or stop it from adding the row?

This is my code and when I enter the programme and try to find the records and get them sorted it shows up list index out of range and when I take the quiz it shows up everything all right but when I enter the CSV file there is an empty row between the input and the beginning of the file I tried deleting the empty rows and the programme works sorts the data and prints it but with the empty rows it just shows up the error mentioned above.
a=True
b=True
c=True
import random #Here i imported a random module
import csv
import operator
score=0 #I made a variable called score and set it to 0
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
if menu1 == ("s"):
menu2=input("How do you want it sorted? alpabetically(a) acording to score highest to lowest(s) or according to average score highest to lowest(a) ")
if menu2 == ("a"):
menu3=input("Which class are you in a b or c ")
if menu3 == ("a"):
sample = open("ClassA.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
if menu3 == ("b"):
sample = open("ClassB.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
menu4=input("Do you want to take the quiz now? ")
if menu4 == ("no"):
print("Thank you for Looking At the scores!")
if menu4 == ("yes"):
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
elif menu1 == ("t"):
while a == True: #Opens a loop called a
name=input("What is your name? ") #I asked the user their name here if name == (""):
if name.isdigit() or name == (""): #If the user enters a number or nothing something will happen
print("Incorrect Name") #This is the message that appears when the the name is a number or is nothing is incorrect
else:
a=False #Here i closed a loop
print("Welcome To my quiz " +str(name))#This is the welcoming message
while b == True:
group=input("What Class Are you A,B,C ") #Asks The User their class
if group == ("a") or group == ("b") or group == ("c") or group == ("A") or group == ("B") or group == ("C"):
break
else:
print("No such class!")
def addition(): #Here i define a function called addition
score=0 #Here the score shows score
first_number_a=random.randint(1,10) #The program gets a random number
second_number_a=random.randint(1,10) #The program gets another random number
question1=int(input("What is " +str(first_number_a)+ "+" +str(second_number_a)+ " ")) #Here the program asks the user a question
total_a=(first_number_a+second_number_a) #The answer to the question above
if question1 == total_a: #If answer is equal to the new variable c which is the answer to the question
print("Correct!") #This tells the user they got it correct
score=score+1 #This adds a point to the score
else: # if answer is not the variable
print("Incorrect!") #Here the program will print that the user is incorrect
print(total_a) #Here the program prints the correct answer if they got the question wrong
return score #This keeps the score safe
def multiplication():
score=0
first_number_m=random.randint(1,10)
second_number_m=random.randint(1,10)
question2=int(input("What is " +str(first_number_m)+ "*" +str(second_number_m)+ " "))
total_m=(first_number_m*second_number_m)
if question2 == total_m:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_m)
return score
def subtraction():
score=0
first_number_s=random.randint(1,10)
second_number_s=random.randint(1,10)
question3=int(input("What is " +str(first_number_s)+ "-" +str(second_number_s)+ " "))
total_s=(first_number_s-second_number_s)
if question3 == total_s:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_s)
return score
qw=["a" , "b" , "c"] #List Of Letters that will be randomly selected to then start a function
for i in range(0,10): #Thsi willrepeat the process listed below however many times in this example 10 times
random_Letter=random.choice(qw) #Selets a random letter
if random_Letter == "a": #If the random letter is a
score += addition() #It will use the function addition
elif random_Letter == "b":
score += multiplication()
elif random_Letter == "c":
score += subtraction()
print("your score is " +str(score)+ " Out of 10")#Tells the user their final score
if group == ("a") or group == ("A"): # If users input is as specified
f=open("ClassA.csv","a")#This opens a file
c = csv.writer(f)
c.writerow([name,score]) #Writes To A file
f.close() #This closes the file saving anything the user wrote to it
elif group == ("b") or group == ("B"):
f=open("ClassB.csv","a")
c = csv.writer(f)
c.writerow([name,score])
f.close()
elif group == ("c") or group == ("C"):
f=open("ClassC.csv","a")
f.write(name)
f.write(str(score)+ "\n")
f.close()

Categories