Python array loop not looping/validator issues - python

I'm not exactly sure what I did, but when testing my code it either crashes immediately or gets stuck in a loop. If the first input is a value error (string) and the next is a number it loops as long as the pattern is kept. But if first user entry is int then program crashes. Please any help would be appreciated.
def main():
courseArray = []
keepGoing = "y"
while keepGoing == "y":
courseArray = getValidateCourseScore()
total = getTotal(courseArray)
average = total/len(courseArray)
print('The lowest score is: ', min(courseArray))
print('The highest score is: ', max(courseArray))
print('the average is: ', average)
keepGoing = validateRunAgain(input(input("Do you want to run this program again? (Y/n)")))
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray)
except ValueError:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
counter += 1
return courseArray
def valScore(courseArray):
score = int(courseArray)
if score < 0:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
elif score > 100:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
else:
return courseArray
def validateRunAgain(userInput):
if userInput == "n" or userInput == "N":
print("Thanks for using my program")
return "n"
elif userInput == "y" or userInput == "Y":
return "y"
else:
print("Please enter y or n")
validateRunAgain(input("Do you want to run this program again? (Y/n)"))
return getValidateCourseScore()
def getTotal(valueList):
total = 0
for num in valueList:
total += num
return total
main()

There are too many inputs from the user, so I have cut down on them and changed it.
Here are the sections of your code which I have changed :
Here valScore() I presume validates the input score so, I also gave the index of element to be validated. If it is not valid we remove it from the array and raise ValueError, since it raises error our counter is not updated.
keepGoing = validateRunAgain()
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray, counter - 1)
counter += 1
except ValueError:
print("Please enter a valid score between 0-100")
continue
return courseArray
def valScore(courseArray, counter):
score = courseArray[counter]
if score < 0 or score > 100:
courseArray.pop()
raise ValueError
def validateRunAgain():
while True:
userInput = input("Do you want to run this program again? (Y/n)")
if userInput == 'y' or userInput == 'Y':
return 'y'
elif userInput == 'n' or userInput == 'N':
print('thank you for using my program')
return 'n'
else:
print('Enter Y or N')

Related

Question about the while loop for supermarket checkout case

I tried to make simple codes for supermarket checkout, but I have an issue with the while loop statement. Please check the code below and picture I sent.
I don't know why after I input "n", it does not go back to the loop.
def start():
quan = 1
price = 0
end = False
total = 0
while end == False:
food = (input("Enter your food: "))
quan = int(input("Enter quantative: "))
price = float(input("Price of food: "))
disscount = float(input("Do you have disscount? enter '0' for no disccount. "))
end = input("Finish? y or n: ")
sum = price * quan
sub_total = sum - (sum * disscount * 0.01)
total += sub_total
if end == "y":
print("Total price is ", total)
end = True
elif end == "n":
end = False
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
start()
The if again block needs to be indented:
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
Otherwise, you hit your if statement without necessarily having defined again. If it is not defined, you get the error you cite.

Wanting to input bowling scores, total, average them

Need for a user to input bowling scores and store them, to be totaled and averaged later and they can press "q" or "Q" to quit and total/average them. I've tried fumbling around figuring out loops but not sure how to deal with inputting integers and also accepting "Q" to stop loop. Thanks for any help.
nums = []
scores = ""
while scores != 'q'.lower():
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores != 'q':
nums.append(int(scores))
elif scores == 'q'.lower():
print("quitting")
break
scores = int()
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
Getting error:
Traceback (most recent call last):
File "/Users/ryaber/PycharmProjects/pythonProject/main.py", line 11, in
scores = input("Please enter a score (xxx) or 'q' to exit: ")
File "", line 1, in
NameError: name 'q' is not defined
So not sure how to allow it to accept "Q" to stop loop and total/average them.
Remove .lower() in q.lower() and move it and make it to score.lower().
So if user types in q or Q both will be accepted as quit
You do not need average function or while scores != 'q' instead you could change it to something simple
So complete code -
nums = []
scores = ""
while True:
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == 'q':
print("quitting")
break
scores = int()
total = sum(nums)
print(f"The total score is: {total}")
average = total/len(nums)
print("The score average is: ", round(average, 2))
Result:
Please enter a score (xxx) or 'q' to exit: 25
Please enter a score (xxx) or 'q' to exit: 32
Please enter a score (xxx) or 'q' to exit: Q
quitting
The total score is: 57
The score average is: 28.5
Edit -
While this may be complicated, this will solve your problem -
nums = []
scores = ""
while True:
scores = input("Please enter a score (xxx) or 'q' to exit: ")
try: # This will run when scores is a number
scores = int(scores)
if scores.lower() == type(0):
nums.append(int(scores))
except: # Will run when it is a alphabet
if scores.lower() == 'q':
print("quitting")
break
else:
continue
scores = int()
total = sum(nums)
print(f"The total score is: {total}")
average = total/len(nums)
print("The score average is: ", round(average, 2))
break
nums.append(int(scores))
just cast it to an int ...
You only need to convert your input string to an int before storing it:
nums = []
scores = ""
while scores != 'q'.lower():
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores != 'q':
nums.append(int(scores))
elif scores == 'q'.lower():
print("quitting")
break
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
You need to append integral value of score to the list
nums.append(int(scores))
Also, I guess you might want to use a f-string here
print(f"The total score is: {total}")
EDIT :
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == "q":
print("quitting")
break
As pointed out by #PCM, you need to use the .lower() method on the variable
The final working code :
nums = []
scores = ""
while scores != 'q':
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == "q":
print("quitting")
break
scores = int()
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
You can read more about f-strings here

I want to print when the user fails to type a positive number it will tell them the number was not valid (eg -8.25)

def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue

Why does the process just stop even though I have some command? [duplicate]

This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
Closed 2 years ago.
I am trying to make a code guessing game where the user can choose the range of the code. The user tries to guess the randomly generated code until he/she gets it right. The computer also shows which digits the user gets correct. The problem is that when the user does guess the code correctly, the process just stops even though my codes says to print a congratulations message and go to the play again function. Please can anyone help? Thanks. Code:
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
elif Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if Guess == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("NOT QUITE! YOU GOT", Digits_Correct, " DIGITS CORRECT!")
print(Digits)
get_guess(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
Choice = input("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()
I think the problem here is that your Guess is a string and your Random is an integer. To fix this, you can try to convert the Guess to an integer or the Random to a string.
Try this:
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
I think your problem is with types str and int. First of all your Min and Max are strings, so your line:
elif Min > Max: print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
does not work correctly. The other problem is that your variables Guess and Random are of different types, so Guess == Random will return False all the time.
Here's correct version of your code.
I've also added a few if cases to be able to quit the program without closing it.
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
if Min == 'q':
return
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
Min = int(Min)
Max = int(Max)
if Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("NOT QUITE! YOU GOT", Digits_Correct, " DIGITS CORRECT!")
print(Digits)
get_guess(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
print("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
Choice = input()
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()

How to stop loop?

I'm a step away from completing my binary converter, though it keeps on repeating, it's and endless loop.
def repeat1():
if choice == 'B' or choice == 'b':
while True:
x = input("Go on and enter a binary value: ")
try:
y = int(x, 2)
except ValueError:
print("Please enter a binary value, a binary value only consists of 1s and 0s")
print("")
else:
if len(x) > 50:
print("The number of characters that you have entered is", len(x))
print("Please enter a binary value within 50 characters")
z = len(x)
diff = z - 50
print("Please remove", diff, "characters")
print(" ")
else:
print(x, "in octal is", oct(y)[2:])
print(x, "in decimal is", y)
print(x, "in hexidecimal is", hex(y)[2:])
print(" ")
def tryagain1():
print("Type '1' to convert from the same number base")
print("Type '2' to convert from a different number base")
print("Type '3' to stop")
r = input("Would you like to try again? ")
print("")
if r == '1':
repeat1()
print("")
elif r == '2':
loop()
print("")
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
else:
print("You didn't enter any of the choices! Try again!")
tryagain1()
print("")
tryagain1()
I'm looking for a way to break the loop specifically on the line of code "elif r== '3':. I already tried putting 'break', but it doesn't seem to work. It keeps on asking the user to input a binary value even though they already want to stop. How do I break the loop?
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
return 0
else:
print("You didn't enter any of the choices! Try again!")
choice = try again()
if choice == 0:
return 0
print("")
tryagain1()
return is suppose to be used at the end of the Function or code when you have nothing else to do

Categories

Resources