I want a small program to count each part numbers enter by user.
here is so far I can do.
Is there a way I can export part numbers and their frequency to .csv file?
from collections import Counter
thislist = []
frequency = []
partnumber = ""
def mainmanu():
print ("1. Create List")
print ("2. Print list")
print ("3. Exit")
while True:
try:
selection = int (input("Enter Choice: ")
if selection ==1:
creatlist(thislist)
elif selection ==2:
counteach(thislist)
elif selection ==3:
break
except ValueError:
print ("invalid Choice. Enter 1-3")
def creatlist(thislist)
# while True:
partnumber = input ("Enter Part number: ")
if partnumber =="end":
print(thislist)
mainmanu()
break
thislist.append(partnumber)
def counteach(thislist)
Counter(thislist)
mainmanu()
mainmanu()
Welcome to the StackOverflow.
You are calling the mainmanu function inside another function which is called by mainmanu function. Instead what you should be doing is letting mainmanu calling all the other helper functions. Antoher thing, you can't call break in another function and expect where it is called to break.
The execution goes like this:
mainmanu is called, it calls creatlist, after it finishes execution it continues to execute the instructions where it is left from.
from collections import Counter
thislist = []
frequency = []
partnumber = ""
def mainmanu():
print ("1. Create List")
print ("2. Print list")
print ("3. Exit")
while True:
try:
selection = int (input("Enter Choice: ")
if selection ==1:
if creatlist(thislist): # line x
break
elif selection ==2:
counteach(thislist)
elif selection ==3:
break
except ValueError:
print ("invalid Choice. Enter 1-3")
def creatlist(thislist)
# while True:
partnumber = input ("Enter Part number: ")
if partnumber =="end":
print(thislist)
return True #this value will make the the condition to be true see line x
thislist.append(partnumber)
return false
def counteach(thislist)
Counter(thislist)
mainmanu()
Related
# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)
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.
I'm trying to call the "name" under 'create():' in 'show():', but it says it's not defined. How can I save my input in 'create():', so I can use it in the other subroutines (in 'show():' for this example).
Thank you
I have tried to ask the user input after the choice part, but it doesn't solve it. I keep getting the same error.
import sys
class data:
name = ""
average = ""
def menu():
print("1) Data input")
print("2) Print data")
print("3) Give file name")
print("4) Save")
print("5) Read file")
print("0) Stop")
choice = int(input("Give your choice: "))
print()
return choice
def save(datalist, namea):
f = open(namea, "w")
for data in datalist:
row = str("{};{}").format(data.name, data.average)
f.write(row)
f.write("\n")
f.close()
def read(datalist, namea):
f = open(namea, "r")
for row in f:
row = row.split(";")
dataa = data()
dataa.name = str(row[0])
dataa.average = float(row[1])
datalist.append(dataa)
return datalist
def printt(datalist):
for data in datalist:
print(data.name, data.average)
def name():
namea = str(input("Give a name: "))
return namea
def inputt(datalist):
dataa = data()
dataa.name = str(input("Give a name: "))
dataa.average = float(input("Give the average (float): "))
datalist.append(dataa)
print()
return(datalist)
def main():
try:
datalist = []
while True:
choice = menu()
if (choice == 1):
datalist = inputt(datalist)
elif (choice == 2):
printt(datalist)
elif (choice == 3):
namea = name()
elif (choice == 4):
save(datalist, namea)
elif (choice == 5):
datalist = read(datalist, namea)
elif (choice == 0):
print("The program was closed {} at {}".format(datetime.datetime.now().strftime('%d.%m.%Y'), datetime.datetime.now().strftime('%H:%M:%S')))
return False
except Exception:
sys.exit(0)
main()
I excpect it to print the name I input in 1), when I call 2).
For example:
choice 1)
1) Give name: Daniel
choice 2)
2) Prints: Hello Daniel
you got a problem with your Scope.
The name variable is only local.
See https://www.programiz.com/python-programming/global-local-nonlocal-variables for more Information.
a hotfix would be using global-variables instead, or as Aaron D. Rodriguez suggested passing the name as parameter to the show-function.
def lista():
print("1) Write name.")
print("2) Print written name.")
print("0) Stop.")
choice = int(input("Give your choice: "))
return choice
def create():
global name
name = input("Give name: ")
return(name)
def show():
global name
print(name)
return
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
create()
elif (choice == 2):
show()
else:
print("Input not detected.\nStopping.")
break
main()
You would have to have show() include a parameter in it. For example:
def show(n):
print(n)
So that when you call show(n), it prints whatever you include as n.
So if you called show(name). It would print out name.
def show(n):
print(n)
show(name) #This would print out name.
You also don't need return unless you are returning a value. Return doesn't make the code go back, it just makes the function return a value. So you do need return for list() and create(), but not for show(n).
Edit
You also would want to set the user input as a variable when you call create.
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
name = create() #Here is where you should change it
elif (choice == 2):
show(name)
else:
print("Input not detected.\nStopping.")
break
I need help with a one or two things on my coursework. firstly when I input an incorrect username/password it will output more than one error message at a time. Secondly, when the men function ends the program will go back to the login loop( that allows the user to re-enter their username/password), I have fixed this by using the B variable but this feels extremely janky and I know there is a better way of doing it. Any Modifications or Tips are greatly appreciated (even if they're not related to my above problems). also the way i code is a bit weird so it's probs best you read from bottom to top :)
def quiz():
print ("quiz")# place holder for real code (let's me know the function has been run)
def report():
print ("report") # place holder for real code (let's me know the function has been run)
def a_menu():# Admin menu
print ("Welcome to the student quiz!")
print ("Please choose a option")
while True:
print ("1: Computer science")
print ("2: Histroy")
print ("3: Reports")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
elif menu_in == 3:
report()
break
else:
print ("Invalid input! Please try again..")
def menu():
print ("Welcome to the student quiz!")
print ("Please choose a quiz")
while True:
print ("1: Computer science")
print ("2: Histroy")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
def login():
b = False
print ("Please enter your username and password")
while True:
if b == True:
break
log_user = input("Username:")
log_pass = input ("Password:")
with open("D:\\Computer science\\Computing test\\logindata.txt","r") as log_read:
num_lines = sum(1 for line in open('D:\\Computer science\\Computing test\\logindata.txt'))
num_lines = num_lines-1
for line in log_read:
log_line = log_read.readline()
log_splt = log_line.split(",")
if log_user == log_splt[0] and log_pass == log_splt[2]:
if log_splt[5] == "a": # Admin will have to mannually change the admin status of other user's through .txt file.
b = True
a_menu()
else:
b = True
log_read.close()
menu()
break
else:
print ("Incorrect username or password, please try again!")
def register():
print ("enter your name, age, and year group and password")
while True:
reg_name = input("Name:")
reg_pass = input ("Password:")
reg_age = input ("age:")
reg_group = input ("Year Group:")
print ("Is this infomation correct?")
print ("Name:",reg_name)
print ("password:",reg_pass)
print ("Age:",reg_age)
print ("Year Group:", reg_group)
reg_correct = input ("[Y/N]").lower()
if reg_correct == "y":
reg_user = reg_name[0:3]+reg_age
reg_write = open("D:\\Computer science\\Computing test\\logindata.txt","a")
reg_write.write (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group+","+"u"+"\n")
print ("Your username is:",reg_user)
reg_write.close()
login()
break
elif reg_correct == "n":
print ("Please Re-enter your infomation")
else:
Print ("Invalid input! Please try again...!")
def login_ask():
print ("Do you already have an account?")
while True:
ask_in = input("[Y/N]").lower()
if ask_in == "y":
login()
break
elif ask_in == "n":
register()
break
login_ask()
For menu-driven programming, how is the best way to write the Quit function, so that the Quit terminates the program only in one response.
Here is my code, please edit if possible:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
while choice!="q":
if choice=="v":
highScore()
main()
elif choice=="s":
setLimit()
main()
elif choice=="p":
game()
main()
else:
print("Invalid choice, please choose again")
print("\n")
print("Thank you for playing,",name,end="")
print(".")
When the program first execute and press "q", it quits. But after pressing another function, going back to main and press q, it repeats the main function.
Thanks for your help.
Put the menu and parsing in a loop. When the user wants to quit, use break to break out of the loop.
source
name = 'Studboy'
while True:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choice = raw_input(">>> ").lower().rstrip()
if choice=="q":
break
elif choice=="v":
highScore()
elif choice=="s":
setLimit()
elif choice=="p":
game()
else:
print("Invalid choice, please choose again\n")
print("Thank you for playing,",name)
print(".")
def Menu:
while True:
print("1. Create Record\n2. View Record\n3. Update Record\n4. Delete Record\n5. Search Record\n6. Exit")
MenuChoice=int(input("Enter your choice: "))
Menu=[CreateRecord,ViewRecord,UpdateRecord,DeleteRecord,SearchRecord,Exit]
Menu[MenuChoice-1]()
You're only getting input from the user once, before entering the loop. So if the first time they enter q, then it will quit. However, if they don't, it will keep following the case for whatever was entered, since it's not equal to q, and therefore won't break out of the loop.
You could factor out this code into a function:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
And then call it both before entering the loop and then as the last thing the loop does before looping back around.
Edit in response to comment from OP:
The following code below, which implements the factoring out I had mentioned, works as I would expect in terms of quitting when q is typed.
It's been tweaked a bit from your version to work in Python 2.7 (raw_input vs. input), and also the name and end references were removed from the print so it would compile (I'm assuming those were defined elsewhere in your code). I also defined dummy versions of functions like game so that it would compile and reflect the calling behavior, which is what is being examined here.
def getChoice():
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=raw_input(">>> ")
choice=choose.lower()
return choice
def game():
print "game"
def highScore():
print "highScore"
def main():
print "main"
def setLimit():
print "setLimit"
choice = getChoice()
while choice!="q":
if choice=="v":
highScore()
main()
elif choice=="s":
setLimit()
main()
elif choice=="p":
game()
main()
else:
print("Invalid choice, please choose again")
print("\n")
choice = getChoice()
print("Thank you for playing,")
This is a menu driven program for matrix addition and subtraction
def getchoice():
print('\n What do you want to perform:\n 1.Addition\n 2. Subtraction')
print('Choose between option 1,2 and 3')
cho = int(input('Enter your choice : '))
return cho
m = int(input('Enter the Number of row : '))
n = int(input('Enter the number of column : '))
matrix1 = []
matrix2 = []
print('Enter Value for 1st Matrix : ')
for i in range(m):
a = []
for j in range(n):
a.append(int(input()))
matrix1.append(a)
print('Enter Value for 2nd Matrix : ')
for i in range(m):
a = []
for j in range(n):
a.append(int(input()))
matrix2.append(a)
choice = getchoice()
while choice != 3:
matrix3 = []
if choice == 1:
for i in range(m):
a = []
for j in range(n):
a.append(matrix1[i][j] + matrix2[i][j])
matrix3.append(a)
for r in matrix3:
print(*r)
elif choice == 2:
for i in range(m):
a = []
for j in range(n):
a.append(matrix1[i][j] - matrix2[i][j])
matrix3.append(a)
for r in matrix3:
print(*r)
else:
print('Invalid Coice.Please Choose again.')
choice = getchoice()