I'm just trying Python, and really like it! But I get stucked with try/except.
I have a code that checks raw_input for being integer, but i'd like to make it function, and it doesn't want to be it :)
here the code, I have this:
number_of_iterations = raw_input("What is your favorite number?")
try:
int(number_of_iterations)
is_number = True
except:
is_number = False
while not is_number:
print "Please put a number!"
number_of_iterations = raw_input("What is your favorite number?")
try:
int(number_of_iterations)
is_number = True
except:
is_number = False
I don't want to repeat myself here& So I think smth about to make function:
def check_input(input_number):
try:
int(input_number)
return True
except:
return False
But it make an error if input a string, saying that int can't be used for strings. Looks like it does not see 'try' keyword.
Can smone explain why it happens and how to prevent it in future?
Try this, it avoids repeating yourself without needing a def
while True:
try:
number_of_iterations = int(raw_input("What is your favorite integer?"))
break
except ValueError:
print "Please put an integer!"
EDIT: Per the suggestions of the commenters, I have added break to the try portion of the block to eliminate the else (the original remains as a reference below). Also, I changed "number" to "integer" because "3.14" would be invalid in the above code.
This was my original suggestion. The above is fewer lines (some may call this cleaner), but I prefer the below because to me the intent is clearer.
while True:
try:
number_of_iterations = int(raw_input("What is your favorite integer?"))
except ValueError:
print "Please put an integer!"
else:
break
If you want it as a function, decide two things:
What is it going to need to work, and
What it's going to need to spit back out.
Your use case is that you need some sort of int back, and if it bombs out for whatever reason, it's defined as not a number.
Let's create a tuple as our return value, so we can return a number of some kind and a boolean for "if it is a number".
def check_input(number):
try:
return (int(number), True)
except ValueError:
return (-999999, False) # Care more about boolean here
We can then use that return value in our while loop like so. Note that I explicitly set the loop condition to False, so we enter in at least once.
is_number = False
num = -999999 # Define out of scope of loop so it can be used
while not is_number:
print "Please put a number!"
num, is_number = check_input(raw_input("What is your favorite number?"))
The line num, is_number is a result of tuple packing. Since we're returning a tuple from our method, we can set two distinct variables to the results of that tuple.
Related
In the second line, I am trying to make it not crash if a string is entered but can't find a way to use an exception or something similar. In the while loop it works normally as the exception deals with this case.
number = 0 #this to be removed
number = (float(input('pick a number'))) #I want to make this not crash if a string is entered.
while number not in [100, 200, 3232]:
try:
print('wrong number ')
number = (float(input('pick a number;'))) #Here it does not crash if a string is entered which is fine
except ValueError:
print("retry")
while followed by a variable condition often ends up with bugs/repeating code => bad maintenability.
Use a while True condition to avoid repeating your code, then break out the loop when it's valid.
while True:
try:
number = float(input('pick a number;'))
if number in [100, 200, 3232]:
break
print("wrong number")
except ValueError:
print("illegal number, retry")
note: be careful with float equality in the general case (see also strange output in comparison of float with float literal, Is floating point math broken?)
Maybe create a function to take input:
def get_input():
while True:
a = input("Pick a number: ")
try:
return float(a)
except:
pass
So the task is to:
"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."
I'm still kind of new to Python but I can't seem to achieve this assignment on my own. I kind of want to avoid just copying someone else's code because the teacher of the module Charles Severence, says that's not a good idea. But I'm also getting tired of this assignment that probably does not reflect anything I would normally want to use python for as a programmer.
This is my code at the moment. It seems like no matter what I change there is always a new error:
Please help, suggest solutions and tell me the mistakes I'm making.
EDIT:
I have received comments about the indentation errors and I wanted to clarify that these were typos I caused when copying my code into this forum. Anyway, I have adjusted my code and it no longer has the problem of not accepting 'done' or not continuing the loop after an invalid input. Now, the difficulty I'm having is retrieving the maximum and minimum values with or without a list function. Also, at this point I'm so stuck I wouldn't mind receiving some direct answers with working code.
largest = None
smallest = None
number_list = []
while True:
num = input('Enter a number:')
if num == 'done' : break
try:
num = int(num)
number_list.append(num)
except:
print ('Invalid Input')
continue
def max(num):
for largest in number_list[num]:
if largest < num:
largest = num
return largest
def min(num):
for smallest in number_list[num]:
if smallest is None:
smallest = num
if smallest > num:
smallest = num
return smallest
print ('Maximum is',max(num))
print ('Minimum is',min(num))
While not giving away the complete code due to the reasons your teacher stated, there are quite a few things to look at there:
The values aren't currently being returned since input always returns a string, and you need integers to compare, so after you input, you should add a line that tries to convert the input to an integer variable, something like this:
num = input('Enter a number:')
if num != "done":
try:
num = int(num)
number_list.append(num)
except ValueError:
print("Must be a number or the word 'done'")
Note that I also checked for a number_list variable that should be defined as an empty list beforehand. Lists are great for the purpose of storing many numbers on a single variable and then checking it for the largest and smallest number with the max() and min() arguments.
I assume you haven't heard of lists yet.
The way I would solve it would be to use a list to store all the values and then applying the max(list) and min(list) built-in functions.
alln = list()
num=""
while num!='done':
num = input('Enter a number:')
try:
alln.append(float(num))
except:
print('invalid input')
print ('Maximum is',max(alln))
print ('Minimum is',min(alln))
Like this
Check this and this to understand the basics of lists and how to work with those two functions.
Now the problems with your code
1. You have several indentation errors.
for largest_num in [uval]:
if largest is not None or uval > largest:
^here, the 'if' should be inside the 'for' block and it wasn´t. You have this problem twice in your code
while True:
num = input('Enter a number:')
uval = float(num)
if num == str:
elif num == str('done'):
^here, all four need an extra space to be properly indented
2. Because of this
num = input('Enter a number:')
uval = float(num)
When you write "done", you get another error. Try doing this instead:
while True:
if num == 'done':
break
#check if it's not a number
else:
num = float(num)
#store the value as a float
That way you can avoid converting a string to a float, which is why you are getting the error
Other problems I found
Both prints have indentation errors. But assuming that's just a typo, the indentation itself will make the loop print every single time it runs because it's inside the 'for' block.
str('done') this doesn't work because str() will transform the argument to a string. Remember that 'done' is already considered a string by python, so you can just write num == 'done'
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!
Question 1:
Just tried to execute the program but i am getting syntax error
i=input('Enter the value of i')
for j in range(10):
if i==j:
print'The value of i is %d'%(i)
elif i!=j:
print'Please enter a valid value'
else:
print 'This is not a number'
The difference between the below two codes is that code one will ask for input once and then loop trying to compare, while code two will ask for input each loop (10x)...
If your code is really indented as you put it here, the reason you are getting a syntax error is that your elif and else blocks are indented too far. Another problem with your code is that i can be either equal or not equal to j. There is no third option. Another problem is that the first time it comes across a number that is not equal to the number typed, it will say that it is not a valid value. Also, just saying "Please enter a valid value" will not make it so. Here is a better version of your code:
i = None
while True:
i = input("Enter the value of i")
if i.isdigit():
if int(i) in range(10):
print "The value of i is %d" % i
else:
print "Please enter a valid value"
else:
print "This is not a number"
As for question 2, the difference between the two is that in the first, i=input('Enter the value of i') will be executed before the loop, and in the second it will be executed for each iteration of the loop. (That is, one time for each time the loop is executed. Because range(10) returns ten items, it runs ten times.) More about for loops here, here, and here
You appear to be having a syntax error because of inconsistent levels of indentation in your code. Please try the following instead and adjust the program to suit whatever your needs might be.
#! /usr/bin/env python3
import sys
def main():
loop = True
while loop:
try:
i = int(input('Enter of the value of i: '))
except EOFError:
sys.exit()
except ValueError:
print('This is not a number')
else:
if 0 <= i <= 9:
print('The value of i is', i)
loop = False
else:
print('Please enter a valid value')
if __name__ == '__main__':
main()
I simply cannot understand what is happening here. The problem is important for my homework (studying programming so I'm a beginner... also my English is not that good, sorry).
I am trying to read a string... it can be either a number or a set number of commands.
I'll just give a very small example of what I'm trying to do and what is going wrong.
def validate():
choice = str(input(">>> "))
if (choice == "exit"):
return 0 # should exit validate
else:
try:
aux = int(choice) # Tries converting to integer
except:
print("Insert integer or exit")
validate() # If it can't convert, prompts me to try again through
# recursivity
else:
return aux
rezult = validate()
print (rezult)
Problem is that this small script returns totally random stuff.
If "exit", returns "None".
If first input is correct, it returns correct number.
If first input is an "error" and second input is correct, it's "None" again and I simply can't understand what is going wrong... Why it doesn't want to work or what should I do (alternatively).
In case you enter the except block, the function validate() uses a recursive call to call itself. When this call returns, it returns to the place where the function was called, i.e. into the except block. The return value of validate() is ignored at this point, and control reaches the end of the outer call without hitting a return statement, so None is implicitly returned.
Don't use recursion here. Use a loop.
Use raw_input instead of input (unless you are on Python 3.x):
choice = raw_input(">>> ")
And you are missing a return here:
except:
print ("Insert integer or exit")
return validate () # <<< here
Also, don't use recursion for this. Use a loop instead.
Ok, decided to listen and changed the recursive part into a loop, thank you for your help. (Works now)
def validateChoice():
condition = False
while (condition == False):
choice = str (input (">>> "))
if (choice == "exit"):
return 0
else:
try:
aux = int (choice)
except:
print ("Insert integer or 'exit'")
else:
condition = True
return aux