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.
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 want my code below to ask users to add contacts which i will save in a dictionary.
When user responds N to whether they want to add new contact, the loop is supposed to terminate. When Y, the loop must continue and when they enter something which is neither N nor Y, the question must keep repeating till they enter Y or N.
My code below does not return to beginning of function when i type yes
contactbook = {}
def addcontact():
name = input("Enter the name of your new contact")
number = int(input("Enter your phone contact"))
contactbook[name] = number
print("Contact book successfully updated with : ", contactbook.items())
while True:
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N").upper()
elif qu == 'N':
break
After I reply Y to the question, I do not get the program to repeat
You can achieve that logic more cleanly by sth. like:
def addcontact():
while True: # no variable like keepadding needed
name = ...
# ...
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N").upper()
if qu == 'N':
break
# no need to specify the 'Y' case, the outer loop just continues
This is because you are assigning to a variable named keepadding. The loop tests the value of a variable named keepreading. Because these variables are different the test will always be True and the loop will continue even if you enter N.
Update your code to initialise the variable at the top of the function and test the correct variable:
def addcontact():
keepadding = True
while keepadding:
....
Updated following OP code change:
Move the while loop to the top of the function so that the input() and contact book updates occur within the loop. Change elif to if. Here is a working version:
contactbook = {}
def addcontact():
while True:
name = input("Enter the name of your new contact")
number = int(input("Enter your phone contact"))
contactbook[name] = number
print("Contact book successfully updated with : ", contactbook.items())
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N: ").upper()
if qu == 'N':
break
Try this:
contactbook = {}
def addcontact():
keepadding = True
while keepadding:
name = input("Enter the name of your new contact: ")
number = int(input("Enter your phone contact: "))
contactbook[name] = number
print("Contact book successfully updated with {}, {}".format(name, number))
while True:
qu = input("Do you want to add a new contact? Y/N ").upper()
if qu in 'YN':
break
print("That's not a valid input. Try again.")
keepadding = qu.upper() == 'Y'
addcontact()
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
def teacher_student(): #defines subroutine
global t_s #globalizes variable
t_s = "" # sets variable to null
while t_s not in ["T","S","t","s"]: # creates array/list and starts the while loop
t_s = input ("Are you a T or an S? ").upper() #asks the user to input weather they are a T or an S
while t_s == "S":
welcome()
def welcome():
print (Welcome!)
This code will not call the subroutine even if I enter s or S. sorry if its a simple answer I'm new to programing, Thanks!
How about this, which adds an action for both good paths, T and S. It also changes your input() method to raw_input() to protect against input evil in python 2.x
def welcome(who):
if who == "S":
print "Welcome, student!"
else:
print "Welcome, teacher!"
def teacher_student(): # defines subroutine
userinput = "" # sets variable to null
while userinput not in ["T","S"]: # creates array/list and starts the while loop
userinput = raw_input("Are you a T or an S?") # asks the user to input weather they are a T or an S
userinput = userinput.upper()
if userinput == "S":
welcome(userinput)
if userinput == "T":
welcome(userinput)
teacher_student()
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()