Essentially, I'm trying to create a main function that can take input, and use that list of input to calculate the median, mode, and mean by using another function. I'm a novice coder (taking my first class) so any help that can point me in the right direction while still helping me learn will be greatly appreciated.
def median(alist):
srtd = sorted(alist)
mid = len(alist) // 2
if len(alist) % 2 == 0:
return (srtd[mid -1] + srtd[mid]) / 2.0
else:
return (srtd[mid])
def main():
yourlist = []
addons = list(float(input("Enter your list of number to be calculated(stop to stop): ")))
if addons != "stop":
data.append(yourlist)
elif addons == "stop":
break
else:
print("Bad input, try again: ")
continue
medresult = median(yourlist)
return medresult
print(medresult)
break and continue are to only be used in a loop such as for or while
So your main () should have a while loop in it.
def main():
yourlist = []
while True:
addons = input("Enter your list of number to be calculated(stop to stop): ")
if addons != "stop":
data.append(yourlist)
elif addons == "stop":
break
else:
# This block will never run because an input can either equal or not equal "stop"
print("Bad input, try again: ")
continue
Personal preference, but I would change your if statements to
if 'stop' not in addons:
data.append(yourlist)
and the elif to
elif not all(isinstance(number, float) for number in addons):
print("Bad input, try again")
This checks each inputted number in the addons list to see if it is a float. If not all are floats, then print the try again message
Related
I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
again = str(input("Again? (Y or N) "))
again = again.upper()
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
EDIT:
So I have made some progress but I have one last problem
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
while True:
again = input("again? (Y or N)")
if again not in "yYnN":
continue
break
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?
You could create another loop (inside this main loop) where you are asking for input, and have a try block there, so that it loops just the section where the user is giving input until they give correct input.
I'm currently trying to run a program where the user inputs a word and then after they input the first word, the program will ask if they want to continue putting words. Once the user replies "no", the program will generate the list of words that has been input. I seem to be having trouble calling the array for my code below:
def word():
w1 = input("Please enter a word: ")
group = []
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
if (decide == "yes"):
return -1
elif (decide == "no"):
return 1
while (True):
crit = word()
if (crit == -1):
continue
elif (crit == 1):
print("words are: ", group)
break
How I can make this work properly?
I think you meant to pass the list into the function:
def word(group):
w1 = input("Please enter a word: ")
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
return decide == "yes"
group = []
while True:
crit = word(group)
if crit:
continue
else:
print("words are: ", group)
break
The array ‘group’ is defined inside the function word(). This means if the function is returned, the list ‘group’ disappears also.
You can either
Use global variable
Define group outside the function (in this case, at the top) and use that global list inside the function. I.e. add the line
global group in the first line of the function.
However, using global variable when not needed is not so recommandable.
Define group list outside the function and pass it to the function as an argument
Instead of def word(), use def word(group) and pass the list to the function when calling the function.
group = []
def word():
w1 = input("Please enter a word: ")
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
if (decide == "yes"):
return -1
elif (decide == "no"):
return 1
while (True):
crit = word()
if (crit == -1):
continue
elif (crit == 1):
print("words are: ", group)
break
The variable group is not available outside the function.
A variable created outside of a function is global and can be used by anyone.
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\": ")
shopping_list = []
def show_help():
print("\nSeperate each item with a comma.")
print("Type DONE to quit, SHOW to see the current list, and Help to get this message again.")
def show_list():
count=1
for item in shopping_list:
print("{}: {}".format(count, item))
count += 1
print("Give me a list of things you want to add to the list.")
show_help()
while True:
new_stuff = input("> ")
if new_stuff == "DONE":
print ("\n Here's your list:")
show_list()
break
elif new_stuff == "HELP":
show_help()
continue
elif new_stuff == "SHOW":
show_list()
continue
else:
new_list = new_stuff.split(",")
def spot_in():
index = input("Add this item at a certain spot? Press enter to place it at end of list, "
"or give me a mumber. Currently {} items in the list.".format(
len(shopping_list)))
return index
if spot_in():
try:
spot = int(spot_in()) - 1
except ValueError:
print ("That's not a number, trying to cheat eh? Enter a real number")
put_in()
for item in new_list:
shopping_list.insert(spot, item.strip())
spot += 1
else:
for item in new_list:
shopping_list.append(item.strip())
My problem is that as far as I know the only way to make sure the location is a number is to use a try and expect with a function inside it. But the code throws an error when I try to turn the return value of the function into an int.
Is there a better way to make sure the return number is an int? OR is there some other way to turn the function's return value into an int?
Thanks in advance.
Use the isdigit() function for strings which will return True if it is a number, and false if it has a character or is empty.
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()