i have troubling handling input in python. I have a program that request from the user the number of recommendations to be calculated.He can enter any positive integer and blank(""). I tried using the "try: , except: " commands,but then i leave out the possibility of blank input. By the way blank means that the recommendations are going to be 10.
I tried using the ascii module,but my program ends up being completely confusing. I would be glad if anyone could get me on the idea or give me an example of how to handle this matter.
My program for this input is :
while input_ok==False:
try:
print "Enter the number of the recommendations you want to be displayed.\
You can leave blank for the default number of recommendations(10)",
number_of_recs=input()
input_ok=True
except:
input_ok=False
P.S. Just to make sure thenumber_of_recs , can either be positive integer or blank. Letters and negative numbers should be ignored cause they create errors or infinite loops in the rest of the program.
while True:
print ("Enter the number of the recommendations you want to " +
"be displayed. You can leave blank for the " +
"default number of recommendations(10)"),
number_of_recs = 10 # we set the default value
user_input = raw_input()
if user_input.strip() == '':
break # we leave default value as it is
try:
# we try to convert string from user to int
# if it fails, ValueError occurs:
number_of_recs = int(user_input)
# *we* raise error 'manually' if we don't like value:
if number_of_recs < 0:
raise ValueError
else:
break # if value was OK, we break out of the loop
except ValueError:
print "You must enter a positive integer"
continue
print number_of_recs
Related
This is my code and I'm not allowed to use built in functions to convert bin to decimal. I have to implement try and except in this but have tried and failed.
I need the input to only accept 1s and 0s. I need to display an error message and have the user try again if anything else is inputted.
`#Declaration
strBinaryNumber= ""
intBinaryLength= 0
strBinaryInput= ""
intDecimalNumber= 0`
`#User input of binary number
strBinaryNumber= input("Enter your binary number: ")
intBinaryLength= len(strBinaryNumber)
strBinaryInput= strBinaryNumber`
`#Loop count for decimal conversion
intDecimalNumber = 0
while len(strBinaryNumber) > 0:
intDecimalNumber*=2
intDecimalNumber+= int(strBinaryNumber[0])
strBinaryNumber = strBinaryNumber[1:]`
`#Decimal Output
print("\nThe binary number is:", strBinaryInput)
print("\nThe length is:", intBinaryLength)
print("\nYour decimal number is:", intDecimalNumber)`
The basic idea of a try-except statement is that if the code could fail, there’s something to prevent it from breaking.
try:
(code you want to run)
except:
(code to run if the earlier code fails)
if you put this in a function then make it call the function again from the except statement if the code fails that might help.
Is this what you meant?
I am new to python and came around a scenario explained below-:
This is one from the .pdf I am referring to learn. Would be great if anyone could guide or share some other resources.
A program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.333333333333333*
I am unable to store the values into list.
Tried going with this logic-:
while True:
line = input('Enter Number-: ')
if type(line) == int():
continue
if line == 'done':
break
print(line)
print('Done!')
Just need to know how to store into lists without using spaces or commas,
The user should be able to enter the value as shown in example above and those should get stored in a list.
Thanks in advance.
In Python 2.7, input will evalulate any entry and will fail if the input is not a correct Python type to begin with. It's better to use raw_input here as any entry will be considered a string. If you move to Python 3, raw_input was removed and input acts how raw_input did. So your example expects you to give it '45' or 'done' instead of 45 or done.
But the reason you're unable to store any values into a list is because you're not adding them to a list in the first place. But since we've also switched to raw_input, we don't know if the entry is a valid number or not. So we need to try to convert it to a number and if it isn't one, then check to see if it's the keyword telling the code to stop.
values = [] # make an empty list
while True:
line = raw_input('Enter Number-: ') # all entries here are considered strings
try:
num = int(line) # convert to an integer
values.append(num) # add to list
continue # return to input query
except: # int(line) threw an error, so not a valid number input
if line == 'done': # check if should stop
break # get out of loop
else: # anything else
print 'bad data, invalid input'
continue # return to input query
print 'Done!\n'
print 'total:', sum(values)
print 'count:', len(values)
print 'average:', sum(values) / float(len(values))
If you're entering more than just integers, you may wish to change num = int(line) to num = float(line) to handle decimal inputs, as int only accepts integers.
Enter Number-: 4
Enter Number-: 5
Enter Number-:
bad data, invalid input
Enter Number-: 7
Enter Number-: done
Done!
total: 16
count: 3
average: 5.33333333333
The Tutorial may also be helpful in learning Python.
I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.
I want to write a python program, first it asks you to enter two numbers, and then output all daffodil numbers between the two numbers, and it will continue run, until I enter a "q". I write a program, but it is wrong:
#coding=utf-8
while 1:
try:
x1=int(raw_input("please enter a number x1="))
x2=int(raw_input("please enter a number x2="))
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
Can somebody help? I think it should be simple, but I am not able to write it correctly.
I believe you've misunderstood the problem statement. Try this instead:
if i*100+j*10+k==i**3+j**3+k**3:
ref: http://en.wikipedia.org/wiki/Narcissistic_number
for n in xrange(x1,x2):
digits = map(int,str(n))
num_digits = len(digits)
if sum(map(lambda x:x**num_digits,digits)) == n:
print "%d is a magic number"%n
you will still have the issue of not being able to enter "q" since you force the input to be integers
I would like to address the quit event.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
# The mathematical part... (for completeness) (not my code)
if x1>x2:
x1,x2=x2,x1
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print "%-5d"%n
The pass statement is used only when you don't have anything to be executed in certain block of code. It does nothing more, so don't use it if not needed. It is there for the sake of the code looking clean & with correct indentation.
if some_thing: # don't do anything
else:
some_thing = some_thing_else
Note how the above if statement is syntactically incorrect. This is where pass comes handy. Say, you decide to write the if part later, till then you must provide pass.
if some_thing: # don't do anything
pass
else:
some_thing = some_thing_else
It's a bit tricky to know what's going on without more hints, but some issues I see right off:
You need to be consistent with indentation in Python. Your last if statement is less indented than statements above it (like the previous if and the for loop). This will cause an error. You're also using different amounts of indentation in other places, but since it's not inconsistent that's allowed (if a bad idea). Its usually best to pick one indentation standard (like four spaces) and stick with it. Often you can set your text editor to help you with this (turn on "Expand tabs to spaces" or something in the settings).
You've got two pass statements where they're unneeded or harmful. The first, after the line that has if x1>x2: x1,x2=x2,x1 is going to cause an error. You can't have an indented "suite" of code if you've put a series of simple statements on the end of your compound statement like an if. Either put the assignment on its own line, indented, or get rid of the pass. The last pass at the end of the code is not an error, just unnecessary.
You're missing a colon at the end of your try statement. Every statement in Python that introduces an indented suite ends with a colon, so it should be easy to learn where they're needed.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
i have it! thx to Ashish! it is exactly what i want! and i will quit wenn i enter q! thx a lot!
I am trying to analyse user input and only allow integers to be inputted. I have succesfully managed to only allow denominations of 100s between a certain range, but I cannot work out how to prompt the user to re-enter data if they enter a random string.
Trying to use the "try" command just results in the program getting stuck:
while True:
try:
bet=int(raw_input('Place your bets please:'))
except ValueError:
print 'l2type'
#The following receives a betting amount from the user, and then assesses whether it is a legal bet or not. If not, the user is prompted to enter a legal bet.
while True:
if bet%100==0 and 100<=bet<=20000:
print bet,"Your bet has been accepted, can you make a million?"
break
else:
print bet,"Please enter a legal bet. The table minimum is 100, with a maximum of 20000 in increments of 100."
bet = input('Place your bets please:')
You have the right approach for rejecting non-integer input, but you need to break out of the loop if your user enters valid input. Use the break statement:
while True:
try:
bet=int(raw_input('Place your bets please:'))
break # we only get here if the input was parsed successfully
except ValueError:
print 'l2type'
You will probably also want to move the range checks within the loop. If input that's out of range doesn't naturally lead to an exception, use if statements to make sure "break" is only executed if the input is completely valid.
I rather prefer my recursive version:
def ask_bet(prompt):
bet = raw_input(prompt)
# Validation. If the input is invalid, call itself recursively.
try:
bet = int(bet)
except ValueError:
return ask_bet('Huh? ')
if bet % 100 != 0:
return ask_bet('Huh? ')
if not 100 <= bet <= 20000:
return ask_bet('Huh? ')
# The input is fine so return it.
return bet
ask_bet("Place your bets please: ")
In my opinion, that is much cleaner and easier to read than while loops. You don't have to bother what are attribute values after the first iteration? Adding new validation rules is also really simple.
Generally, I try to avoid while loop in favour of recursive version. Of course, not all the time, since it's slower and the stack is not infinite.