Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try except in while loops
#1
The following code snippet works..
from some_py_file import Thing
#I'm still shaky relying on functools' partial function so for this portion I'm writing out code in 'bulk' style
code = Thing()
some_num = 100
while True:
	question = input('[yes/no]')
	if question =='yes' or 'y':
		try:
			num = float(input('Enter num...'))
			if num ==4 or num == '':
				num = float(some_num /4)
			if num ==5:
				num =float(some_num /5)
			if amount_down == 5:
				num = float(some_num/20)
			num2 = float(input(''))
			print('some_num: ',some_num,'  num: ',num)#just to make sure loop reaches here, with question = 'yes'
			code.func_in_Thing(num, num2)
			break
		except ValueError:
			print('please enter numbers...')
			continue
So the above works...the opposite should also work...but does not.

from some_py_file import Thing
code = Thing()
some_num = 100
while True:
	question = input('[yes/no]')
	if question =='no' or 'n':
		break:#this should kick me out of the while loop ALTOGETHER if question != 'no/n' 
#if question =='foo' it should move the code try/except
#BUT question =='foo' just kicks me out altogether.
	try:
		num = float(input('Enter num...'))
		if num ==4 or num == '':
			num = float(some_num /4)
		if num ==5:
			num =float(some_num /5)
		if amount_down == 5:
			num = float(some_num/20)
		num2 = float(input(''))
		print('some_num: ',some_num,'  num: ',num)
		code.func_in_Thing(num, num2)
		break
	except ValueError:
		print('please enter numbers...')
		continue
The way I understand break it should kick me out of the while ONLY when question == 'no/n'...so why is it the first snippet operates properly and this one breaks regardless of question == 'foo'. if question !='no/n' python SHOULD move down to the try/except code....why doesn't it?
Reply
#2
https://python-forum.io/Thread-Multiple-...or-keyword
check line#6
Reply
#3
I did! sorry about that. Blush I've noticed so much of coding is testing and debugging it's ridiculous!

I'm surprised break is so useful ...did not expect to rely on it SO MUCH!

Also in my nascent experience I've relied on while loops...but most textbooks emphasize while & do-while loops almost equally...in real life when do you guys rely on do while loops (I get the 'practice' examples but what instances would you want to iterate through a loop and then find the variables are false? The instances seem far and few between...
Reply
#4
well, there is no do-while loops
see https://www.python.org/dev/peps/pep-0315/
proposal was rejected back in 2003
I think you are confused...
Reply
#5
u r right Blush it's a js/php loop (not to mention c++)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020