Ending a program - python

How do I end my program if something is true?
This is my code
count=0
num=input("What would you like to do [1,2,3,4]? ")
while (num>'0' and num<'5'):
while num=='1':
Do something
while num=='2':
Do something
While num=='3':
Do something
while num=='4' and count!=1:
print("The End")
count= count+1
I want the program to end while num is '4'

First of all use integers not strings:
>>> '100' > '5'
False
And use if instead of while, if any of the conditions is True then you can use the break statement to break out of the loop.
count = 0
num = int(input("What would you like to do [1,2,3,4]? "))
while 0 < num < 5:
if num == 1:
Do something
...
if num == 4 and count != 1:
print("The End")
count += 1
break #breaks out of the `while` loop
Also note that you should use if-elif-else conditions here instead of just if's, because here all if conditions are going to be checked, but with if-elif-else conditions will short-circuit(jump to the end of if-elif-else block) as soon as one of the condition is True.

Use
if num=='4' and count!=1:
not
while num=='4' and count!=1:

Add a break statement and use numbers
while (num > 0 and num < 5):
while num == 1:
#Do something
while num == 2:
#Do something
while num == 3:
#Do something
if num == 4 and count != 1:
print ("The End"); count += 1
break

Use if in place of while loop like,
while (num>0 and num<5):
if num==1:
Do something
if num==2:
Do something
if num==3:
Do something
if num==4 and count!=1:
print("The End")
count= count+1
break

Related

Program must ask the user for an even integer max six times, if not it ends

The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.

while function with the in operator not working

gone = []
turn = 0
def play(XO,player):
while 0 == 0:
num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
while ((str(num).isdigit() == False) or ((int(num) <= 9 and int(num) >= 1) == False)) or (num in gone):
num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
So, in the second while loop I'm having a problem. You see the (num in gone) part? I'm trying to make it so if num is found in the gone list then it will be true, but it isn't working. Instead it passes through it.
I've tested to see if (not num in gone) applies the opposite effect, and it does!
If you need to see my entire code I can post it... btw this is for a Tic-Tac-Toe program I am making.
You're putting too much logic in one condition. Splitting it up will help you a lot.
Try something like this:
gone = []
turn = 0
def play(XO, player):
while True:
num = input(
f"\n{player} enter an available number "
f"where you want to put an '{XO}'.\n > "
)
try:
num = int(num)
except ValueError:
print("Not a valid number, try again")
continue
if num < 1 or num > 9:
print("Number not in correct range, try again")
continue
if num in gone:
print("Number already gone, try again")
continue
gone.append(num)
turn += 1

not able to execute else part of this program in py

li = []
n = int(input("Enter numbers: "))
count = 0
for i in range(0,n):
a=int(input())
li.append(a)
print( li)
s = int(input('\nEnter a number for search : '))
for j in li:
if s == j:
li.remove(j)
count+=1
if count == 1:
print(f" {j} is removed . \n")
break
#else part is not executed
else:
print(f"Nothing is removed. \n")
print(li)
The else statement you identified is not executed because it lines up with the if count == 1: statement above it. Since count always equals 1 the first time through the loop and you break in the if statement, you exit the loop before count can be anything other than 1.
If you want the else statement to match the if s == j: statement then will have to outdent it. Note, however, once you do that you will have other problems based on your loop logic, but hey, one thing at a time. ;^)
It looks like the else statement belongs to the wrong if statement. Try moving the else statement back one indent. This will print Nothing is removed each time an element is not found.
for j in li:
if s == j:
li.remove(j)
count+=1
if count == 1:
print(f" {j} is removed . \n")
break
#else part is not executed
else:
print(f"Nothing is removed. \n")
print(li)

ValueError works but prevents code from running

I can get the program to count properly and I can get the program to not except float and strings but when i put the two pieces of code together the program won't run the count. Thanks for the help.
print("\tProgram counts the number of positive integers.")
def numCount():
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
total = 0
while True:
try:
num = int(input("Input an integer to count 0 exits program: "))
except ValueError:
print("Please enter an integer.")
continue
else:
return num
if num == 0:
break
elif num < 1:
continue
elif num % 2 == 0:
even_count += 1
even_sum += num
else:
odd_count += 1
odd_sum += num
total += 1
print("\nTotal positive intger count is:", total)
numCount()
You should not return num in the else statement of the try/except. This will immediately exit the function and return the current value of num, instead of it continuing to be processed in the rest of your code.
To fix this, you can simply remove the else statement.
You can simply remove:
else:
return num
This is because return will exit the function early and stop the while loop from continuing.

Break outside of two loops

I'm writing a code with a while loop inside a while loop and am wondering how to break out of the outer loop if I meet the necessary conditions in the inner loop.
while N <= 8:
while i < 60:
if this:
that
elif this:
that other thing
else:
break
i += 1
if while loop has found the right thing:
N += 1
else:
change conditions
This break command will only break out of the first loop, so I'm wondering how to simply break out both. It might be worth mentioning that all this is in another for loop which I wouldn't want to break out of. Thank you.
Encapsulate it in a function and return when you are done?
Use a flag; trigger is used here
trigger = False
while N <= 8:
while i < 60:
if this:
that
elif this:
that other thing
else:
trigger = True
break
i += 1
if trigger:
break
elif while loop has found the right thing:
N += 1
else:
change conditions
Use flag:
flag = True
while N <= 8:
while i < 60:
if this:
that
elif this:
that other thing
else:
flag = False # To exit from outer while loop
break
i += 1
if(not flag):
break # Condition in inner loop is met
if while loop has found the right thing:
N += 1
else:
change conditions

Categories

Resources