I decided to learn python and I chose the book "The python book" to do so but I encountered a problem while coding one of the exercise programs, I'm doing a program that shows how control structures work but it gets stuck in a while loop, I think it is because a boolean variable (isint) is not setting to true so it just gets stuck there, but I'm not sure because I'm new to programming.
#!/usr/bin/env python2
import sys
target_int=raw_input("How many integers? ")
try:
target_int=int(target_int)
except ValueError:
sys.exit("You must enter an integer")
ints=list()
count=0
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
print("Using a for loop")
for value in ints:
print(str(value))
print("Using a while loop")
total=len(ints)
count=0
while count<total:
print(str(ints[count]))
count+=1
I would get this result everytime I ran the program:
jonathan#Jonathan:~/Python$ ./construct.py
How many integers? 1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:4
Please enter integer1:4
Please enter integer1:23
Please enter integer1:13
As you can see no matter what I put there the while loop just keeps going.
Indentation is important in python:
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
This is two separate blocks of code: the if isint==True: part is not inside the while count<target_int: block.
You need to change it to this:
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
Additionally, isint is never set to anything but False, anywhere. So the body of your if statement is never going to execute.
You probably want to set isint to True when you know the input is a valid integer.
You aren't setting isint flag to true when checking for an integer.
while count<target_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint=True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
First your indentation looks wrong for:
if isint==True:
ints.append(new_int)
count+=1
Then you should add isint = True in (at the end of) the block
try:
new_int=int(new_int)
Related
I don't want to make the user be able to enter anything other than numbers as the input for the "number" variable, except for the string "done".
Is it possible to somehow make an exception to the rules of the try-except block, and make the user be able to write "done" to break the while loop, while still keeping the current functionality? Or should I just try something different to make that work?
while number != "done":
try:
number = float(input("Enter a number: ")) #The user should be able to write "done" here as well
except ValueError:
print("not a number!")
continue
Separate the two parts : ask the user and verify if it is done, then parse it in a try/except
number = None
while True:
number = input("Enter a number: ")
if number == "done":
break
try:
number = float(number)
except ValueError:
print("not a number!")
continue
print("Nice number", number)
Instead of trying to make exceptions to the rules, you can instead do something like,
while True:
try:
number=input("Enter a number: ")
number=float(number)
except:
if number=="done":
break
else:
print("Not a number")
Check if the error message contains 'done':
while True:
try:
number = float(input("Enter a number: "))
except ValueError as e:
if "'done'" in str(e):
break
print("not a number!")
continue
also in this case continue is not necessary here (for this example at least) so it can be removed
Maybe convert the number to float afterwards. You can check if number is not equal to done,then convert the number to float
number = 0
while number != "done":
try:
number = input("Enter a number: ") #The user should be able to write "done" here as well
if number=="done":
continue
else:
number = float(number )
except ValueError:
print("not a number!")
continue
There are various ways to approach this situation.
First one that came across my mind is by doing:
while True:
user_input = input("Enter a number: ")
if user_input == "done":
break
else:
try:
number = float(user_input)
except ValueError:
print("not a number!")
continue
while True:
try:
user_input = input("Enter a number: ")
if user_input == "done":
break
number = float(user_input)
except ValueError:
print("not a number!")
continue
You can cast the input to float after checking if the input is 'done'
This question already has answers here:
What is the intended use of the optional "else" clause of the "try" statement in Python?
(22 answers)
Closed 1 year ago.
Just started learning python and wanted to make a calculator. I currently have some code that tries to turn what the user inputs into an integer, but what I want to do is be able to check if the attempt was successful or not.
Here is the part i'm having trouble with.
import sys
first_number = input('Enter a number: ')
try:
int(first_number)
except:
print("Sorry, that's not a number.")
exit()
You can just do:
try:
int(first_number)
print("try successful!")
except ValueError:
print("Sorry, that's not a number.")
print("try unsuccessful!")
exit()
You can set a flag after int that is only set on success:
success=False
nums=iter(['abc','123'])
while not success:
try:
x=int(next(nums))
success=True
except ValueError as e:
print(e, 'Try Again!')
print(x)
Prints:
invalid literal for int() with base 10: 'abc' Try Again!
123
First time with 'abc' is an error, second time a success.
Since nums first try is an error, that will not set success to True. Second time is not an error, success is set to True and the while loop terminates. You can use the same method with user input. The iterator is just simulating that...
So for your example:
success=False
while not success:
try:
n_string = input('Enter a number: ')
int(n_string)
success=True
except ValueError as e:
print(f'"{n_string}" is not a number. Try again')
Which is commonly simplified into this common idiom in Python for user input:
while True:
try:
n_string = input('Enter a number: ')
int(n_string)
break
except ValueError as e:
print(f'"{n_string}" is not a number. Try again')
To have this make more sense, make it a function:
def getNumber():
while True:
number = input('Enter a number: ')
if number.isnumeric():
return int(number)
print( "Not a number, please try again." )
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
I am new to Python.Trying to learn it.
This is my Code:
import sys
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
except ValueError:
("You must enter an integer")
ints=list()
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
The code is executing but the loop is always repeating and is not allowing me to enter 2nd integer.
Output:
How many integers?3
Please enter integer1:1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:
Can i know what is wrong with my code?
Thank you
The problem of your code is that isint is never changed and is always False, thus count is never changed. I guess your intention is that when the input is a valid integer, increase the count;otherwise, do nothing to count.
Here is the code, isint flag is not need:
import sys
while True:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
break
except ValueError:
print("You must enter an integer")
ints=list()
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
try:
new_int=int(new_int)
ints.append(new_int)
count += 1
except:
print("You must enter an integer")
isint needs to be updated after asserting that the input was int
UPDATE:
There is another problem on the first try-except. If the input wasn't integer, the program should be able to exit or take you back to the begining. The following will keep on looping until you enter an integer first
ints=list()
proceed = False
while not proceed:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
proceed=True
except:
print ("You must enter an integer")
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint=True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
A better code:
import sys
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
except ValueError:
("You must enter an integer")
ints = []
for count in range(0, my_int):
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint = True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
Im still very new when it comes to python so be easy on me. Whenever I test this code it comes back with "None" instead of the input entered. Any idea why it could be happening?
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
def main():
while(1):
landValue = inputLandValue()
print(landValue)
doMoreStuff = input('Do you want to continue? y/n ')
if(doMoreStuff.lower() != 'y'):
break
main()
input()
You indented your return value line too far. It is part of the except: handler, so it is only executed when you have no value! It should be outside the while loop:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
or replace the break with return value:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
return value
except:
print('Please enter a whole number (10000)')
You should really only catch ValueError however; this isn't Pokemon, don't try to catch'm all:
except ValueError:
You can fix your problem by just putting 'return value' in place of the break in main().