not able to execute else part of this program in py - python

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)

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.

Finding fault in this recursive list addition in python

I need to create a program that takes in an array of numbers, check if each number is greater than the sum of all previous numbers, and output true if the condition is met, and false, if not. My trial is presented below:
import fileinput
a0 = [int(i) for i in fileinput.input()]
a = a0[1:]
b=[]
for i in range(1, a0[0]+1):
b.append(a[i])
if (a[i+1] > sum(b)):
print("true")
break
else:
print ("false")
break
My program works for half of the test cases but fails for the other test. Could you please help me figure out what i am doing wrongly. Many thanks for your assistance.
You are breaking too early in the true case. Only because the first element checks, doesn't mean all others will, too:
for i in range(1, a0[0]+1):
b.append(a[i])
if (a[i+1] <= sum(b)):
print ("false")
break
else: # for-else: else is executed only if loop isn't `break`ed out of
print("true")
Only once the loop has finished without finding a counter example, you can be sure that it holds for the entire list.
A more concise of writing this, would be:
import fileinput
_, *a = (int(i) for i in fileinput.input())
s = 0 # just keep track of total
for num in a:
if (num <= s):
print("false")
break
s += num
else:
print("true")

Python break for loop

I am new to Python, but I think reserved words must have similar meaning in programming. However, I don't know why the break inside the 2nd if-condition breaks two for-loop.
I want to check if the list is empty or not, so I use a while-loop. It is supposed that if newList still has elements, it will stay in the loop2. However, after the break in con2, it goes directly to loop1 even newList still has element.
while list:
print ("loop1")
result = 'n'
for e in list:
print ("loop2")
result = 'n'
for h in longList:
print ("loop3")
for i in e.getList():
print ("loop4")
if (i == h.getId()):
print ("con1")
result = 'y'
break
if (result == 'y'):
print ("con2")
break
Your break statement is breaking from both loops because if you look just before you execute the first break statement, you assign the value y to the variable result. After you break from your first loop, the next line that gets tested is if (result == 'y'): and then you break again
while newList:
print ("loop1")
result = 'n'
for node in newList:
print ("loop2")
result = 'n'
for parent in parents:
print ("loop3")
for neighbourId in node.getNeighbours():
print ("loop4")
if (neighbourId == parent.getId()):
print ("con1")
result = 'y' # assignment
break # first break
if (result == 'y'): # occurs after the first break and will be true
print ("con2")
break # second break
else:
print('This loop was not terminated with a break statement')
else:
print('while loop ended')
Update:
In Python you can add an else clause to a loop and this else clause will only run if the loop has executed in full i.e never reached a break statement

Ending a program

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

How to call an item from a dictionary in python?

So I have a dictionary which consists of a number and its definition is the corresponding element on the periodic table.
I have built up the dictionary like this:
for line in open("periodic_table.txt"):
temp.append(line.rstrip())
for t in temp:
if t[1] != " ":
elements[x] = t[3:]
else:
elements[x] = t[2:]
x += 1
I know that every element is in table because I ask the program to print the dictionary.
The point of this is that the user enters a number or element name and the number and name are both printed like this:
while count == 0:
check = 0
line = input("Enter element number or element name: ")
if line == "":
count = count + 1
break
for key,value in elements.items():
if line == value:
print ("Element number for",line,"is",key)
check = 1
break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
break
if check == 0:
print ("That's not an element!")
This works for every element except the last one, Ununoctium, in the dictionary. When the user enters 118 this element is printed, but if they enter 'ununoctium' then the program says "That is not an element!". Why is this and how do I fix it?
Thanks in advance
It is much easier to have python do the lookup for you. Ignoring empty lines for now:
elements = []
for line in open("periodic_table.txt"):
elements.append(line[3:])
You can then do a lookup like this:
if answer.isdigit():
print elements[int(answer)]
else:
print elements.index(answer)
I suspect this is a case sensitive issue.
Changing
if line == value:
to
if line.lower() == value.lower():
would solve that problem.
While you are there, why have the if inside the for loop?
You could check that first, and then don't need the break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
#<-------- break no longer required
else:
#for loop as above

Categories

Resources