Im trying to check the length of the string entered by the user and if its < 5 it goes through however no matter what length it still goes through my try except statement
print """
Please put in the Stock symbol for the Company
whose last closing stock price you wish to see."""
while True:
symbol = raw_input("Enter Stock Symbol: ")
try:
len(symbol) < 5
break
except ValueError:
print 'Greater than 4 characters, Try again'
print 'Great your stock symbol is less than 5'
You don't need a try/except:
while True:
symbol = raw_input("Enter Stock Symbol: ")
if len(symbol) > 4:
print 'Greater than 4 characters, Try again'
else:
print 'Great your stock symbol {} is less than 5'.format(symbol)
break
In [3]: paste
while True:
symbol = raw_input("Enter Stock Symbol: ")
if len(symbol) > 4:
print 'Greater than 4 characters, Try again'
else:
print 'Great your stock symbol {} is less than 5'.format(symbol)
break
## -- End pasted text --
Enter Stock Symbol: FOOBAR
Greater than 4 characters, Try again
Enter Stock Symbol: YHOO
Great your stock symbol YHOO is less than 5
In your code:
try:
len(symbol) < 5 # always checks len
break # always breaks
except ValueError:
You would use a try/except if for instance you wanted to cast the input to an int catching a ValueError there but it is not applicable in your case.
You must first call (TypeError or ValueError or ..Error) in try section in the if statement, and decide what to do with this error in the except section. More information: here
while True:
name = input (': ')
try:
if (len (name) >= 4):
raise ValueError()
break
except ValueError:
print ('Account Created')
else:
print ('Invalid Input')
Related
Hi i'm new to python and i am having issues with exceptions. i have added an exception but it is not working. Below is a sample of my problem.
if x == '1':
print("----------------------------------")
print("1. REQUEST FOR A DOG WALKER")
print("----------------------------------")
try:
print("Select a Date (DD/MM/YY) - eg 12/04/21")
except ValueError:
raise ValueError('empty string')
date = input()
try:
print("Select a Duration (in hours) - eg 2")
duration = input()
except ValueError:
print('empty string')
print("Select a breed : 1 - Rottwieler , 2 - Labrador Retriever, 3 - Pitbull, 4 - Other ")
breed = input()
print("Number of Dogs - eg 3 ")
dogsNumber = input()
Whenever you use a try/except statement you are trying to catch something happening in the code the shouldn't have happened. In your example, you are haveing the user enter a number for a duration:
print("Select a Duration (in hours) - eg 2")
duration = input()
At this point, duration might equal something like '2'. If you wanted to add 10 to it then you could not because it is a string(you cannot and int+str). In order to do something like this, you would have to convert the user input to an int. For example:
duration = int(input())
The problem is that if the user enters a letter A, then the program will break when it tries to convert it to an int. Using a try/except statement will catch this behavior and handle it properly. For example:
try:
print("Select a Duration (in hours) - eg 2")
duration = int(input())
except ValueError:
print('empty string')
There is nothing in your code that can produce ValueError.
So the except ValueError: is not matched.
1 - You are not checking any conditions to raise the error
2 - You're not catching the ValueError, you have to raise it and then catch in with the except statement.
Try this:
if x == '1':
print("----------------------------------")
print("1. REQUEST FOR A DOG WALKER")
print("----------------------------------")
print("Select a Date (DD/MM/YY) - eg 12/04/21")
try:
date = input()
if len(date) == 0:
raise ValueError('empty string')
except ValueError as error:
print(error)
I am trying to get a program to run if you dont type a number, but i dont get it.
Can anyone help?
loop=True
print("Velcome to the pythagorean triples generator, if you want the machine to stop type stop")
print("Choose an uneven number over 1")
while loop:
number1 = input("write here: ")
try:
number = int(number1)
except:
print("It has to be a whole number")
if int(number)%2 == 0 or int(number)==1
print("the number has to be uneven and bigger than 1")
else:
calculation = int(number) ** 2
calculation2 = int(calculation) - 1
calculation3 = int(calculation2) / 2
print ("Here is your first number,", int(calculation3))
calculation4 = int(calculation3) + 1
print ("Here is your second number,", int(calculation4))
if str(tal) == "stop":
break
Edit: translated
I'm guessing that you want your program to continue asking for a number when the user's input it not a number.
If this is the case, which you should clarify, then this will do the trick:
except:
print("It has to be a whole number")
continue
The continue keyword skips the current iteration and continues with the next iteration. The continue keyword in Python
Without doing this your code will print "Must be a number" in your exception, but will continue execution at the next line where you try to convert number, which at this point we know can't be converted to an int, thereby causing an unhandled exception. This will be solved by using the continue keyword as I suggested.
However, if there was no exception raised (i.e. the input can be interpreted as an int), than there is absolutely no point in saying int(number) as number at this point is already an int!
loop = True
print("Velkommen til pythagoras tripler generatoren, hvis du vil stoppe maskinen skal du bare skrive stop")
print("Vælg et ulige tal over 1")
while loop:
tal = input("Skiv her: ")
try:
number = int(tal)
except Exception as e:
print("Det skal være et tal")
raise e // You should raise a Exception to let this program stops here.
if int(number) % 2 == 0 or int(number) == 1: // You lack one ':'
print("tallet skal være ulige og større end 1")
else:
udregning = int(number) ** 2
udregning2 = int(udregning) - 1
udregning3 = int(udregning2) / 2
print("Her er dit ene tal,", int(udregning3))
udregning4 = int(udregning3) + 1
print("Her er dit andet tal,", int(udregning4))
if str(tal) == "stop":
break
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
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
I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here