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
Related
This question already has answers here:
Breaking out of nested loops [duplicate]
(8 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
As I am a new learner in python, I was trying to do an exercise having while loop in it.
I have written a piece of code which will ask user to enter his details.
After getting all the details the program should stop, but In my case after entering Account Number, it again start asking Mobile number to enter.
Please have a look at the code and suggest where I am going wrong.
bnkName = ["SBI", "PNB", "CBI", "ICICI", "BOB"]
targetattmpt = 10
appliedattmpt = 1
while (appliedattmpt <= targetattmpt):
mobilenum = input("Please Enter your Mobile Number:\n")
if (len(mobilenum) == 10):
while (True):
Bankname = input("Please Enter your Bank Name\n").upper()
if Bankname in bnkName:
print("Valid Bank\n")
print("Please enter your Account Number\n")
accnum = input("Account Number:\n")
print(accnum)
break
else:
print("Invalid Bank")
else:
print(mobilenum, "IS NOT VALID!!!", "You have", targetattmpt - appliedattmpt, "attempts left\n")
appliedattm = appliedattm + 1
if (appliedattmpt > targetattmpt):
print("Account locked!!")
The break statement inside the inner loop will break the inner loop but not the outer. You should re-think the logic and maybe add bool variable to check if inner loop broke so you can break the outer loop. For/while loops have else statements which will check if the loop called finished successfully or was aborted with a break. In the case of a while loop, the else will be executed if the condition in the is no longer true.
Take a look at: https://book.pythontips.com/en/latest/for_-_else.html
To give you an example:
j = 0
bank = True
while(j < 2):
print('check_this')
i = 0
while(i < 2):
print('check that')
if bank:
break
else:
i += 1
else:
break
print('I checked both !')
j += 1
Output:
check_this
check that
I checked both !
check_this
check that
I checked both !
Now change the bank to False
j = 0
bank = False
while(j < 2):
print('check_this')
i = 0
while(i < 2):
print('check that')
if bank:
break
else:
i += 1
else:
break
print('I checked both !')
j += 1
Output:
check_this
check that
check that
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'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
I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error.
I can't figure out why this is not working.
from math import pi
def get_area(r):
area = pi * (r**2)
print "A= %d" % area
def is_number(number):
try:
float(number)
return True
except ValueError:
return False
loop = True
while loop == True:
radius = input("Enter circle radius:")
if is_number(radius) == True:
get_area(radius)
loop = False
else:
print "That's not a number!"
When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the print statement in the except block:
try:
radius = input("Enter circle radius:")
except (ValueError, NameError):
print "That's not a number!"
get_area(radius)
radius is still a string,
replace
get_area(radius)
with
get_area(float(radius))
You also have to replace input with raw_input since you're using Python 2
in= 0
while True:
try:
in= int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
try:
num=float(num)
except:
print "Invalid input"
continue
this part of my code seems to be bugging, but when i remove the try and except everything works smoothly, so this seems to be the problem.
i want to convert the input inside a while loop to an integer, if the input isn't an integer it'll display an error and just continue with the loop and ask again. however, it doesn't continue the loop and just keeps printing "Invalid input" forever. how come it isn't continuing the loop?
here is the entire code, in case something else might be wrong:
c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
except:
print "Invalid input"
continue
c=c+1
num2=num+num2
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg
You can solve the problem by moving the variable assignments into the try block. That way, the stuff you want to skip is automatically avoided when an exception is raised. Now there is no reason to continue and the next prompt will be displayed.
c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
c=c+1
num2=num+num2
except:
print "Invalid input"
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg
You can tighten this a bit further by removing the need to duplicate the prompt
c=0
num2=0
while True:
num=raw_input("Enter a number. ")
if num == "done":
break
try:
num2+=float(num)
c=c+1
except:
print "Invalid input"
avg=num2/c
print num2, "\t", c, "\t", avg
continue means return back to while, and as num never changes, you will be stuck in an infinite loop.
If you want to escape the loop when that exception occurs then use the term break instead.
# this function will not stop untill no exception trown in the try block , it will stop when no exception thrown and return the value
def get() :
i = 0
while (i == 0 ) :
try:
print("enter a digit str : ")
a = raw_input()
d = int(a)
except:
print 'Some error.... :( '
else:
print 'Everything OK'
i = 1
return d
print(get())