List Comprehension python? - python

I have a function like this:
for product in responseSoup.findAll("offersummary"):
try:
if product.lowestnewprice.formattedprice != None:
price.append(product.lowestnewprice.formattedprice.text)
else:
price.append("")
except:
price.append("")
I am confused how to do the if/else statement with the try/except block? Will list comprehension speed up efficiency?
[product.lowestnewprice.formattedprice for product in responseSoup.findAll("offersummary")]

Here is a very readable solution:
prices = []
for product in responseSoup.findAll("offersummary"):
price = product.get(lowestnewprice, {}).get(formattedprice, {}).get(text)
if price is not None:
prices.append(price)
else:
prices.append('')
If you really don't care about readability, here's a very atrocious looking one-liner:
price = [''
if product.get(lowestnewprice, {}).get(formattedprice, {}).get(
text) is None else
product.lowestnewprice.formattedprice.text
for product in responseSoup.findAll("offersummary")]
They do essentially the same thing, but, in my opinion, the more readable solution is better.
EDIT
I just figured out a much better one-liner:
price = [product.get(lowestnewprice,{}).get(formattedprice,{}).get(text) or ''
for product in responseSoup.findAll("offersummary")]
It's still less readable than the "very readable" solution, but it is not too bad. Now the decision really comes down to a matter of your preference.

try and except blocks are used to see if the following code works. If not and it matches the given error, run that block of code. Else, run the other line of code. For example:
try:
m = raw_input("Please enter an integer")
n = int(m)
except ValueError:
print "Invalid number"
else:
print n
So, the program attempts to assign m the input from the user. Then n is assigned the input as an integer. Now the error chosen is ValueError since if m is a string, the conversion to n will raise that error. If it does, then it does the code in the except block, which is to print "Invalid number". If the conversion is successful, then print n.
Now with your program, you will try the if and else block. If the code doesn't work and it raises the error given in the except block, it will do price.append(""). Else, it will run the code in the else block, which you don't have. You need the else: to work in your try/except block for it to work including a specified error after the keyword except in your except statement.

Related

Why my try-exception-finally cant work properly

it's homework from udemy,my solution cant work,here is the question:
Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs.
here is my solution:
def ask():
while True:
try:
user_input = int(input('give me int energe:'))
squ = user_input**2
print('boom! show you my power:'+squ)
except:
print('lack of int energe')
continue
else:
print('Gotcha')
break
finally:
print('boooooom')
pass
if I input str, the exception works well but even I input an int also show the same result as str,why this happens??
here is the correctly solution:
def ask():
while True:
try:
n = int(input('Input an integer: '))
except:
print('An error occurred! Please try again!')
continue
else:
break
print('Thank you, your number squared is: ',n**2)
I am not sure why my attempt cant going well
Your print statement is throwing an exception. You cannot append a string and an int using +. Either use
print('boom! show you my power:' + str(squ))
or
print('boom! show you my power:', squ)
In general untyped except statements are a really bad idea. If you had instead written except ValueError:, catching only the error thrown by trying to convert a string to an int using the int() function, you would have immediately seen the problem.
In your code, the error lies in:
print('boom! show you my power:'+squ)
squ is type int, and you're using the + operator where the left side has a string and the right side has an int. Either change the int to a string, or use the , character. Either of these would work:
print('boom! show you my power:', squ)
print('boom! show you my power:' + str(squ))

error displaying when trying to error capture

I am having the problem where i need some code to be error captioned, so if the user does not enter a number it should tell them that they have done something wrong. Below is the code that i would like to error capture, and i am not sure how to do about doing this.
if cmd in ('L', 'LEFT'):
Left_position = (int(input("How many places would you like to move left")))
if args:
step = int(args[0])
else:
step = Left_position
y -= step
This line:
Left_position = (int(input("How many places would you like to move left")))
Will throw an error if the input is not a string that can be turned into an integer. To capture this, surround this with a try block:
try:
Left_position = (int(input("How many places would you like to move left")))
except ValueError:
print('Error is handled here')
if args:
....
You might want to rearrange your code slightly. As far as I can see, you only actually want to ask the user for input if args haven't been provided. If this is the case, the following should work:
if args:
step = int(args[0])
else:
while True:
try:
Left_position = (int(input("How many places would you like to move left")))
break
except ValueError:
print 'This is not an integer! Please try again'
step = Left_position
y -= step
First, if there are args we use the first element and carry on. If there aren't, we enter a (potentially infinite) loop where the user is asked to provide an input. If this is not wrappable as an integer, an error message is printed and then the user is asked again for an input value. This terminates once an integer is provided - the break line can only be reached if an error isn't thrown by the input.

Exceptions and Output

I have problem when calling my function, I am receiving bad output as I will explain later in the text.
These are the resources I am working with:
Main_Building=[10,12,14,17,21,25,30,36,43,52,62,74,89,107,128,154,185,222,266,319,383,460,552,662,795,954,1145,1374,1648,1978]
Barracks=[16,19,23,28,33,40,48,57,69,83,99,119,143,171,205,247,296,355,426,511,613,736,883,1060,1272]
Stables=[20,24,29,35,41,50,60,72,86,103,124,149,178,214,257,308,370,444,532,639]
Workshop=[24,29,35,41,50,60,72,86,103,124,149,178,214,257,308]
Blacksmith=[19,23,27,33,39,47,57,68,82,98,118,141,169,203,244,293,351,422,506,607]
Market=[10,12,14,17,21,25,30,36,43,52,62,74,89,107,128,154,185,222,266,319,383,460,552,662,795]
Axe=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Clay_Pit=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Mine=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Settler_House=[5,6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989]
Warehouse=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Wall=[8,10,12,14,17,20,24,29,34,41,50,59,71,86,103,123,148,177,213,256]
Here is my code:
def buildings(points):
for i in range(0,30):
try:
if Main_Building[i]>=points:
del Main_Building[i:]
if Barracks[i]>=points:
del Barracks[i:]
if Stables[i]>=points:
del Stables[i:]
if Workshop[i]>=points:
del Workshop[i:]
if Blacksmith[i]>=points:
del Blacksmith[i:]
if Market[i]>=points:
del Market[i:]
if Axe[i]>=points:
del Axe[i:]
if Clay_Pit[i]>=points:
del Clay_Pit[i:]
if Mine[i]>=points:
del Mine[i:]
if Settler_House[i]>=points:
del Settler_House[i:]
if Warehouse[i]>=points:
del Warehouse[i:]
if Wall[i]>=points:
del Wall[i:]
except IndexError:
continue
The problem is when the it comes to Condition of Blacksmith, it looks to me as the condition is only passed, and the same for others continuing to Wall condition. The condition is determining where to stop and delete rest of the list for further use. The lists are different lengths so I used simple exception for when it is out of range it just skips and continue to next condition.
Suggested output when def buildings(100):
Blacksmith=[19,23,27,33,39,47,57,68,82,98]
Actual output is whole list without any change. The same applies to continuing condition.
What I tried:
I tried to restart Python but that unfortunately was not it.
If I misspelled the variable name.
Redoing spacing on every condition.
Maybe solution but not effective, adding to each condition try exception ?(Not a good Idea in my opinion).
Why it skips the conditions ?
Thank you for your help and time.
Continue will return to the beginning of current loop and grab next index. This means that if an error occurred halfway, the last half is skipped. It was also quite lengthy. Here is my solution.
data = [Main_Building, Barracks, Stables, Workshop, Blacksmith, Market, Axe, Clay_Pit, Mine, Settler_House, Warehouse, Wall]
def buildings(points):
for building in data: # loop through each building seperately, shortens code and removes arbitrary loop number
for point in building: # loop through each buildings index, same as your code
if point >= points:
del building[building.index(point):]
buildings(20)
print data
If any error occured between try-except, Python will pass or continue all of the codes between try-except.
try:
a = int(input("integer: "))
print("print this")
print("print that")
except:
pass
Output:
>>>
integer: ab
>>>
See that print this and print that not printed. You should catch the errors one by one.
try:
a = int(input("integer: "))
except:
pass
print("print this")
print("print that")
>>>
integer: ab
print this
print that
>>>

Python 3.x - Input only returns first item

I have been having problems with a block of code in a little project and I can't seem to fix it.
In the below code, I define inputrace() so that a process is carried out where the player types in a number that is above 0 and below 13 (there are 12 choices, each dictated by a number); it also checks for blank lines and strings and has the program state that there is an error and ask for user input again if they are detected. If it passes the check, RaceInp is returned and set to RaceChoice which allows the code below it to assign a Race to the player based on their selection.
#race check
def inputrace():
print ("Input number")
RaceInp = input()
Check = RaceInp
try:
int(RaceInp)
except ValueError:
print("Numbers only!")
inputrace()
if not int(Check)>12 or int(Check)<1:
return RaceInp
print (RaceInp) #this is here so I can check the value returned
Race = "NA"
RaceChoice = inputrace()
print (RaceChoice)
#assign race
if RaceChoice == "1":
Race = "Human"
#continues down to twelve
Everything works when valid strings are put in (any number 1-12), but things break when I purposefully put in an invalid string. It seems like RaceInp only retains the first user input and does not change, even after the function is recalled from an error. That means if I were to put in "a," the program will tell me it is wrong and ask again. However, when I put in "1" in an attempt to correct it, it accepts it but still keeps RaceInp as "a."
Is there any fix to this? I have no clue what's going on.
I appreciate the help and sorry if I got anything wrong in the question!
It seems that the problem is that you put the inputrace in a recursion instead of a loop. Something like this would probably be better:
def input_race():
while True:
print("Input a number between 1 and 12.")
race_input = input()
try:
race_input = int(race_input)
if race_input >= 1 and race_input <= 12:
return race_input
except ValueError:
pass
print ("'{input}' is not a number.".format(input=race_input))
race = "NA"
race_choice = input_race()
if race_choice == 1:
race = "Human"
print(race)

Python input string error (don't want to use raw_input) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I have a menu that asks for the user to pick one of the options. Since this menu is from 1 to 10, I'm using input besides raw_input.
My code as an if statement that if the number the user inputs is from 1 to 10 it does the option. If the user inputs any number besides that ones, the else statement says to the user pick a number from 1 to 10.
The problem is if the user types an string, lets say for example qwert. It gives me an error because its an string. I understand why and I don want to use raw_input.
What can I do to wen the user types a string it goes to my else statement and print for example "Only numbers are valid. Pick a number from 1 to 10"
I don't want to use any advanced programing to do this
Regards,
Favolas
EDIT
Thanks for all your answers and sorry for the late response but I had some health problems.
I couldn't use try or except because my teacher didn't allow it.
In the end, I've used raw_input because it was the simplest alternative but was glad to see that are many ways to solve this problem.
Regards,
Favolas
You can throw an exception when you try to convert your string into a number.
Example:
try:
int(myres)
except:
print "Only numbers are valid"
You should use raw_input(), even if you don't want to :) This will always give you a string. You can then use code like
s = raw_input()
try:
choice = int(s)
except ValueError:
# choice is invalid...
to try to convert to an int.
Im not sure what you consider advanced - a simple way to do it would be with something like this.
def getUserInput():
while True:
a = raw_input("Enter a number between 1 and 10: ")
try:
number = int(a)
if (0 < number <= 10):
return number
else:
print "Between 1 and 10 please"
except:
print "Im sorry, please enter a number between 1 and 10"
Here, I have used try/except statements, to ensure that the entered string can be converted to an integer. And a loop (which will keep running) until the entered number is between 1 and 10 (0< number <=10)
What you really are after is how to figure out if something could pass as an integer. The following would do the job:
try:
i = int(string_from_input)
ecxept ValueError:
# actions in case the input is anything other than int, like continuing the loop
You clearly have something against exception handling. I don't understand why -- it's a fundamental part of (not just Python) programming and something you should be comfortable with. It's no more 'advanced' than handling error codes, just a different mentality.
Here are the docs. It's pretty simple:
It is possible to write programs that
handle selected exceptions. Look at
the following example, which asks the
user for input until a valid integer
has been entered, but allows the user
to interrupt the program (using
Control-C or whatever the operating
system supports); note that a
user-generated interruption is
signalled by raising the
KeyboardInterrupt exception.
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
The try statement works as follows.
First, the try clause (the
statement(s) between the try and
except keywords) is executed. If no
exception occurs, the except clause is
skipped and execution of the try
statement is finished. If an exception
occurs during execution of the try
clause, the rest of the clause is
skipped. Then if its type matches the
exception named after the except
keyword, the except clause is
executed, and then execution continues
after the try statement. If an
exception occurs which does not match
the exception named in the except
clause, it is passed on to outer try
statements; if no handler is found, it
is an unhandled exception and
execution stops with a message as
shown above. A try statement may have
more than one except clause, to
specify handlers for different
exceptions. At most one handler will
be executed. Handlers only handle
exceptions that occur in the
corresponding try clause, not in other
handlers of the same try statement. An
except clause may name multiple
exceptions as a parenthesized tuple,
for example:
... except (RuntimeError, TypeError, NameError):
... pass
The last except clause may omit the
exception name(s), to serve as a
wildcard. Use this with extreme
caution, since it is easy to mask a
real programming error in this way! It
can also be used to print an error
message and then re-raise the
exception (allowing a caller to handle
the exception as well):
Personally, I liked my first answer better. However, this one should fit your requirements with more code.
import sys
def get_number(a, z):
if a > z:
a, z = z, a
while True:
line = get_line('Please enter a number: ')
if line is None:
sys.exit()
if line:
number = str_to_int(line)
if number is None:
print('You must enter base 10 digits.')
elif a <= number <= z:
return number
else:
print('Your number must be in this range:', a, '-', z)
else:
print('You must enter a number.')
def get_line(prompt):
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline()
if line:
return line[:-1]
def str_to_int(string):
zero = ord('0')
integer = 0
for character in string:
if '0' <= character <= '9':
integer *= 10
integer += ord(character) - zero
else:
return
return integer
May I recommend using this function in Python 3.1? The two arguments are the expected number range.
def get_number(a, z):
if a > z:
a, z = z, a
while True:
try:
line = input('Please enter a number: ')
except EOFError:
raise SystemExit()
else:
if line:
try:
number = int(line)
assert a <= number <= z
except ValueError:
print('You must enter base 10 digits.')
except AssertionError:
print('Your number must be in this range:', a, '-', z)
else:
return number
else:
print('You must enter a number.')

Categories

Resources