Python While Loop w/ Exception handling never ending - python

I am running into a little problem that I cannot figure out. I am getting stuck in a while loop. I have 3 while loops, the first one executes as planned and then goes into the second. But then it just gets stuck in the second and I cannot figure out why.
A little explanation on what I am trying to do:
I am suppose to get 3 inputs: years of experience (yearsexp), performance (performance) and a random int generated between 1-10(level). The program will ask the user for their experience, if it is between 3-11 they are qualified. If not, it will tell them they are not qualified and ask to re-enter a value. Same thing with performance. If they enter a number less than or equal to 11 it will procede to generate the random int (level) at which point level will be used to asses their bonus. The user gets prompted for experience and will function correctly and proceed to performace. However, even when entering a valid input, it keeps asking them to re-enter the performance #. I cannot figure out why its getting stuck this way.
import random
error = True
expError = True
performanceError = True
# Get users name
name = input("Enter your name: ")
# Get users experience *MINIMUM of 3 yrs py
while (expError):
try:
yearsexp = int (input(name+", Enter the years of your experience: "))
if (yearsexp >= 3 and yearsexp <= 11):
expError = False
print(name, "You are qualified")
else:
raise ValueError
except:
print ("You have entered an invalid number! Try again...")
#Get users performance
while (performanceError):
try:
performance = int (input(name+", Enter the performance: "))
if (performance <= 11):
expError = False
print(name, "You are qualified")
else:
raise ValueError
except:
print ("You have entered an invalid number! Try again...")
performanceError = False
# Get random level number
level = random.randint(1,11)
print ("Random Level: ", end =' ')
print (level)
bonus = 5000.00
while (error):
try:
if (level >=5 and level <=8):
error = False
print ("Expected Bonus: $5,000.00")
print (name + ", your bonus is $", end =' ')
print (bonus)
elif (level <= 4 ):
error = False
bonus = bonus * yearsexp * performance * level
print ("Expected bonus: ", end =' ')
print (bonus)
print (name + ", your bonus is $", end =' ')
print (bonus)
else:
raise ValueError
except:
print ("You do not get a bonus")

You didn't set the performanceError to False
if (performance <= 11):
expError = False
needs to be changed to
if (performance <= 11):
performanceError= False

Related

First time getting this message 'IndexError: list index out of range'

I'm a beginner and this is my first receiving this message "IndexError: list index out of range," can someone please tell me how to fix it? and what exactly did I do wrong? Also if someone can run it and make sure it does what it's supposed to because I need another person other than me to run it(Professor's instruction)
This is the output it gave me -
Traceback (most recent call last):
File "", line 74, in
File "", line 24, in user
IndexError: list index out of range
Here's my code:
print ("Dish No. Dish Name Price ")
print (" -------- --------- ------")
print (" 1 Gang Gai $10.00")
print (" 2 Pad Thai $8.75")
print (" 3 Pad Cashew $9.50")
print (" 4 Pad Prik $10.25")
print (" 5 Peanut Curry $9.50")
print (" 6 Curry Noodles $11.25")
def user():
array = [10,8.75,9.50,10.25,9.50,11.25]
cart = []
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
xx=input("Would you like to order another item( Yes or No)?: ")
if xx.lower() == "no":
break
checkout(cart)
# if xx=='No'.lower():
# return array[x-1]
# else:
# return array[x-1]+user(array)
def seniorCitizen():
print("Are you 65 years or older(Yes or No)? ")
xsenior = input()
if xsenior.lower() == "yes":
senior = True
else:
senior = False
return senior
def checker(num):
if num > 6 or num < 1:
return "wrong number"
def checkout(cart):
senior = seniorCitizen()
titems = 0
for item in cart:
titems = titems + item
print(" Bill Information ")
print("-------------------------------")
print("Total of all items: $",titems)
if senior == True:
boomercount = titems * 0.1
boomercount = round(boomercount, 2)
print("Total senior discounts:-$", boomercount)
tax = round((titems-boomercount)*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round(((titems-boomercount)+tax), 2))
else:
tax = round(titems*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round((titems+tax), 2))
user()
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
The problem is the pass statement. It does not restart the loop -- it does nothing at all. So if the user enters a wrong number, it prints an error message but then it keeps going and tries to access array[x-1] which is out of range.
Use continue which will start the loop over, instead of pass.

Receive User Input and Test Whether It is a Float or Not

I am trying to create a function that will receive input from a list and justify whether it is a float value or not, and if it is, continue with the program, and if it is not, ask the user to enter the answer a second time. The new value should go into the list at the same index as the previous, incorrect value.
For example, if somebody inputted into my code the value 'seventy-two' instead of 72, I want the inputHandler function to receive this incorrect value, tell the user that it is invalid, and ask the user to answer the same question again.
I want my function to use try-except-else statements. Here is my code:
QUIZ_GRADES = int(input("How many quiz grades? "))
PROGRAM_GRADES = int(input("How many program grades? "))
TESTS = int(input("How many tests? "))
def main():
globalConstantList = [QUIZ_GRADES, PROGRAM_GRADES, TESTS]
scoreList = []
returnedScoreList = getGrades(globalConstantList,scoreList)
returnedScoreValue = inputHandler(returnedScoreList)
returnedScoreValue2 = inputHandler(returnedScoreList)
returnedScoreListSum, returnedScoreListLength = totalList(returnedScoreList)
returnedScoreListAverage = calcAverage(returnedScoreListSum,
returnedScoreListLength)
returnedLetterGrade = determineGrade(returnedScoreListAverage)
userOutput(returnedScoreListAverage,returnedLetterGrade)
def getGrades(globalConstantList,scoreList):
for eachScore in globalConstantList:
#totalScoreList = 0.0
index = 0
for index in range(QUIZ_GRADES):
print("What is the score for", index + 1)
scoreList.append(float(input()))
index += 1
for index in range(PROGRAM_GRADES):
print("What is the score for", index + 1)
scoreList.append(float(input()))
index += 1
for index in range(TESTS):
print("What is the score for", index + 1)
scoreList.append(float(input()))
index += 1
return scoreList
def inputHandler(scoreList):
index = 0
try:
print("What is the score for", index + 1)
scoreList.append(float(input()))
return scoreList
except ValueError:
print("Your value is not correct. Try again.")
print("What is the score for", index + 1)
scoreList.append(float(input()))
return scoreList
def totalList(newScoreList):
returnedScoreListLength = len(newScoreList)
returnedScoreListSum = sum(newScoreList)
return returnedScoreListSum, returnedScoreListLength
def calcAverage(newScoreListSum, newScoreListLength):
returnedScoreListAverage = newScoreListSum / newScoreListLength
return returnedScoreListAverage
def determineGrade(newScoreListAverage):
if newScoreListAverage >= 90:
return 'A'
elif newScoreListAverage >= 80:
return 'B'
elif newScoreListAverage >= 70:
return 'C'
elif newScoreListAverage >= 60:
return 'D'
else:
return 'F'
def userOutput(newScoreListAverage, newLetterGrade):
print("Your overall grade is",format(newScoreListAverage,'.2f'))
print("Your letter grade is",newLetterGrade)
print()
main()
As far as I understand, you want to check an user's input and convert it to a float. If successful, you want to proceed, if not, you want to ask again.
Assuming this is the case, you might want to write a function which asks for user input, tries to convert input to float, and returns it if successful.
def input_float(prompt):
while True:
try:
inp = float(input(prompt))
return inp
except ValueError:
print('Invalid input. Try again.')
f = input_float('Enter a float')
print(f)
You can then use this snippet as a starting point for further handling of f (which is a float) the user provided.
You can check your number float or int or string using if elif statement then do your work in side the body of your code
num = input("Enter a number ")
if type(num ) == int : print "This number is an int"
elif type(num ) == float : print "This number is a float"
here you can use function to call this code again and again and place this code in that function and also use try bock to catch exception .

expected an indented block age = input("Age or Type: ")

I have written some code for a piece of work i need to do but when i run the code it says
File "/home/ubuntu/workspace/Odeon/153670.py", line 24
age = input("Age or Type: ")
^
IndentationError: expected an indented block
I was wondering if anyone can help ammend this please.
PART of the code where the error is happening is listed below. age = input("Age or Type: ")
print ("Please Input Your age or type.")
while True:
age_type = None
int_count = 0
peak_flag = None
int_age = 0
totalprice = 0
while True:
**age = input("Age or Type: ")** This line brings the error
if unpeak_price_list.keys().__contains__(age.lower()):
age_type = age.lower()
break
try:
int_age = int(age)
if int_age < 2 and int_age > 130:
print("Please Input Correct age.")
continue
break
except:
print("Please Input Correct age or type")
Indentation, Python doesn't have brackets like other languages to denote blocks of code, instead it has indentations.
print ("Please Input Your age or type.")
while True:
age_type = None
int_count = 0
peak_flag = None
int_age = 0
totalprice = 0
while True:
age = input("Age or Type: ")** This line brings the error
if unpeak_price_list.keys().__contains__(age.lower()):
age_type = age.lower()
break
try:
int_age = int(age)
if int_age < 2 and int_age > 130:
print("Please Input Correct age.")
continue
break
except:
print("Please Input Correct age or type")
Python does not use '{}' to start or to finish a function or flow control structures as other interpreted or compiled languages, it uses the ':' and the indentation typically 4 spaces, every time a ':' is set you need to put 4 spaces more and if the code inside that flow control structure is finished you need to go back 4 spaces, for example:
if a is '':
a = "Hello word" # Here we add 4 spaces because you start an if
if b == 4:
a += str(b) # Here we add 4 spaces because you start an if
else: # Go back 4 spaces because the last if was finished
b += 1
same case for the while and every other flow control structure:
while statement_1:
a += 1
while statement_2:
b += 2
if you are already aware of this and you are following what is written above, the error could be that your text editor is using tabs instead of spaces, the text editor that are used for coding usually have a future that changes the tab for spaces, you could enable it.
The problem with this code is that the different blocks of code are not well structured, in other languages, when you use a loop for example to start and end it you use {}, in Python you have to use tabs like this:
while True:
print('Hello World!')
etc..
...
The same happens to all your code, you have to structure it using tabs.
:)
Here's a fixed version of your code:
print ("Please Input Your age or type.")
while True:
age_type = None
int_count = 0
peak_flag = None
int_age = 0
totalprice = 0
while True:
age = input("Age or Type: ")
if unpeak_price_list.keys().__contains__(age.lower()):
age_type = age.lower()
break
try:
int_age = int(age)
if int_age < 2 and int_age > 130:
print("Please Input Correct age.")
continue
break
except:
print("Please Input Correct age or type")
You need to make sure you're indenting inside a while loop, if statement and try/except statements. I would recommend using larger indents as well to make your code more readable

Python loop just keep going

I'm making a dart score keeper but it just keeps going round and round. I just need some help as to why this is.
The code:
import time
import sys
from sys import argv
script, name1, name2 = argv
def dartscore():
print "Play from 501 or 301?"
threeorfive = int(raw_input())
if (threeorfive == 501):
def playerone():
startnum1 = threeorfive
while (startnum1 > 0):
print "Ready ", name1,"?"
print "Please enter your score."
minusnum1 = int(raw_input())
startnum1 = startnum1 - minusnum1
playertwo()
if (startnum1 == 0):
print "Well done! You win!"
elif (startnum1 < 0):
print "Sorry but you have entered a wrong score"
playertwo()
def playertwo():
startnum2 = threeorfive
print "Ready ", name2,"?"
print "Please enter your score."
minusnum2 = int(raw_input())
startnum2 = startnum2 - minusnum2
if (startnum2 == 0):
print "Well done! You win!"
print "Unlucky ", name1,". Well played though."
sys.exit()
if (startnum2 < 0):
print "Sorry but you have entered an incorrect score. Please try again"
startnum2 += minusnum2
playerone()
playerone()
dartscore()
Now the two functions playerone() and playertwo() are different because I was trying something with the playerone() function to see if that solved my problem.
Well you have a while(startnum1 > 0):. It seems like startnum1is always bigger then 0. The only way to exit your loop is player 2 has a startnum2 on 0.
Your problem is:
threeorfive = 501
Throughout the entire game, and you begin each of your functions with
startnum = threeorfive
Which means the game 'resets' after both player takes a turn.
A possible fix would be to add global variables:
cumulative1 = 0
cumulative2 = 0
then update cumulative in each iteration:
cumulative1 += minusnum1
cumulative2 += minusnum2
and change your while loop to:
while(threeorfive - cumulative1 > 0)
while(threeorfive - cumulative2 > 0)

Comparing 2 string values, not working!?

I'm trying to compare two string values that was retrieved in my first function, but it doesn't work. It keeps telling me 'invalid syntax' and moves my cursor over to the elif line.
This is my program...
def find_number_of_service():
with open('TheData.txt', 'r') as data_file:
data = data_file.read()
countS = data.count('S')
countW = data.count('W')
print ("There are " + str(countS) + " S's")
print ("There are " + str(countW) + " W's")
return
def find_popular_service():
if (countS) > (countW):
print ("The most used service to buy tickets was the school.")
elif print ("The most used service to buy tickets was the website.")
return
#Main program
find_number_of_service()
find_popular_service()
Thank you in advance.
Problem in second function elif you have not defined correctly it should be elif <condition>:
Here the working function
def find_popular_service():
if (countS) > (countW):
print ("The most used service to buy tickets was the school.")
else:
print ("The most used service to buy tickets was the website.")
return
You don't give elif a condition. elif means otherwise if.... Perhaps you mean else.
elif should be in line with if
print ... should be on a new line.

Categories

Resources