I need assistance with a python assignment - python

the instructions are: write a simple python program that is controlled by a while loop. The sentry variable must evaluate to something other than true or false. There must be an indication of whether the loop is continued or if it is exited.
I am having trouble understanding the part that says "sentry variable must evaluate to something other than true or false". I thought that all while loops evaluate to true or false.

Are you looking for something like this? The code below evaluates if the variable "i" is equalled to 100 and if it isn't, re-iterate over the loop adding one to the counter. It indicates if it is currently in the loop or if the loop is broken.
i = 0
while i != 100:
i += 1
print("Continued.")
print("Exited.")

Try something like this:
myList = range(10)
while myList:
print myList.pop()
print myList
It the sentry variable, myList, is list and will allow the loop to continue executing until it is empty. Note that pop will remove the last element from the list at each iteration of the loop.

Related

Why statements after the while loop are not always executed?

I am very new to python and I have encountered the following code:
def function(array):
i = 0
j = 10
while i < j:
if array[i]!=array[j]
return False
i += 1
j -= 1
return True
I can't understand why the True value is not always assigned to the function no matter what happens in a while loop. The while loop just seems to check the if statement, and after finishing the loop, the True value should be assigned to the function anyway. But this code works as follows: the if statement checks for the condition and if it is true, we assign False to the function, if it is not true, we assign True to the function. But the assignment of True is not inside the while loop, so we should have assigned the True to function anyway, no matter what happens in while loop. I can't understand the logic here, can anyone enlighten me in this. Thanks a lot.
A return statement ends the execution of the function call and "returns" the result...
A return statement ends the function.
From https://www.python-course.eu/python3_functions.php
A return is used to hand the control of the program back to the calling function. So when you're in the while loop, and your condition in the if clause is evaluated to be true, your function terminates execution and the control of the program is handed back to the calling function. The only scenario in which your function will return true would be if the conditions in your if clause was never satisfied during the execution of your while loop.
Return exits the current function or method.
when you return False in if statement it will not continue the rest of the code and will always return false.
The condition is likely to have gotten executed before the rest of the loop has a chance to finish. When
if array[i]!=array[j]
is met, return False is called, exiting the loop and returning False.
This happens because
array[i]!=array[j]
is the condition that is met first, before the loop can finish and return with True.
Instead, you may want to 'skip' the part of the loop where this condition is met. If so, use the keyword
continue
This 'skips' the current iteration to the next one, and will continue on with your loop.
Code as follows:
while i < j:
if array[i]!=array[j]:
continue

loop is taking data from outside of loop

full code is here: https://repl.it/repls/UnevenLovingDecagons
line 29 with colony_size=(randrange(50,150)) is outside of loop
then at line 42 loop starts.
colony_size is in line 45 as well.
I would like the colony_size to be influenced by line 29 only once. With second run of loop I'd like the colony_size to be influenced only by what is going on inside of the loop. How can I do so?
part code below:
colony_size=(randrange(50,150))
the one above is still outside of loop
colony_size=(colony_size+immigrants)-died
this one is inside
enter code here
enter code here
enter code here
The concept you're looking at is scope. Loops do not have their own scope in python, the why of this was asked in this question: Scoping in Python 'for' loops
After the following code is executed:
x = 1
i = 1
for i in (2,3,4,5):
x = i
both x and i will contain 5. And the same would be true if they were set or changed in any other kind of loop.
There are several ways to control the scope.. and the most common is functions, which you aren't using in your code. Their variables are contained in their own scope, and you must explicitly pass variables to and from them (using the return keyword). You could also consider comprehensions, although their variables were not contained in the same way in earlier versions of python.
More specifically, in your code.. you may consider putting everything in the while True loop into a function.. (my_function as an example)
while True:
my_function(colony_size)
Or something like that. Then it will use the original colony_size the next time it runs (since you did not return it)
Of course, perhaps the easier option here is to just use a different variable name.
You should have another variable to define a default colony_size at line 29 like:
default_colony_size = (randrange(50,150))
Then define colony_size as a an empty int or just 0 before the loop.
At the start the loop you want to want to do something like this:
if colony_size == 0
colony_size = default_colony_size
Pardon syntax errors as I do not know Python very well

What is the right place to put "return"?

I am a new bird following udacity to learn some python. Got really confused about where to put the return to end a loop. I understand that the code provided in the answer will work. But I don't understand why my own code wouldn't.
I would really appreciate some help! Thank you very much!
The quiz is:
Define a procedure, add_to_index,
that takes 3 inputs:
an index: [[,[,...]],...]
a keyword: String
a url: String
If the keyword is already
in the index, add the url
to the list of urls associated
with that keyword.
If the keyword is not in the index,
add an entry to the index: [keyword,[url]]
my code is:
index = []
def add_to_index(index,keyword,url):
for element in index:
if element[0] == keyword:
element[1].append(url)
else:
index.append([keyword,[url]])
return index
and the answer given is:
index = []
def add_to_index(index,keyword,url):
for element in index:
if element[0] == keyword:
element[1].append(url)
return
index.append([keyword,[url]])
why does the index.append([keyword,[url]]) have to be out of the loop? I thought after each element in the index was went through, the loop will terminate itself. Is it true?
Your code will return the very first time the loop executes no matter what as it is outside the if/else. The given answer only returns when a condition is met
Please note that a loop, by its very definition, loops through all the iteratable items.
In the quiz mentioned above, a new [keword,[url]] item should be appended if it wasn't there before.
You can only tell that after you check the entire data structure, therefore after the loop.
Note that the interpreter will run the "return" statement only if the "keyword" was found in any of the iterations of the loop. Its purpose is simply to stop the execution of the function once the desired functionality has been achieved. Hence a return that returns "nothing" (more precisely None).

The for-loop only loops once, so it's like there was no loop used

so first thing I'm new to python and I came across a simple problem but still complicated. Basically I try to loop all of the things from a list, and make them go through a conditional check if there the ones.
This is to check if a sentence is a greeting.
greets = ["Hi","Hello", "Hey"]
#Thinking
def isGreet(mes): #Checks if it's a greeting
words = mes.split()
for greet in greets:
print(greet)
if (words[0]==greet):
return 1;
else:
return 0;
When a user types in something, the code should check if it's a greeting, and if it is, return true, and if it's not return false. Simple, isn't it? But when I type in something, the code only returns true if it's hi which is used, but when i type let's say hello there, it would return false. I added a print function to see if loops works, but it only prints Hi, so I concluded that there must be something wrong with the for loop. Reaally appreciate any help.
The for-loop only loops once, so it's like there was no loop used
yes, because you're returning from the function no matter what at the first iteration. So your test works if the first word tested is the first in the list only. Else it returns 0.
no need for a loop, use in
greets = {"Hi","Hello", "Hey"} # set should be faster, only if a lot of words, though
def isGreet(mes):
return mes.split()[0] in greets
as stated in comments, mes.split()[0] is somehow wasteful because it keeps splitting other words we don't need, so replace by mes.split(maxsplit=1)[0] or mes.split(None,1)[0] for python 2.
I am assuming that you expect the greeting to be the very first word. In that case you can do it in 1 line:
isGreet = True if mes.split(maxsplit=1)[0] in greets else False

Why do we not need "else" in an if-statement if it contains "return"?

I'm a beginner in Python, and I can't understand why we don't have to use else in cases like the one below:
def find_element(p,t):
i=0
while i<len(p):
if p[i]==t:
return i
i=i+1
return -1
In this code I thought I should use else return -1 if I wanted to return -1, but it seems that python understands this without else like in the code above.
Return terminates a function. Basically, if the "if" condition is satisfied within the "while" loop, the function will end. Alternatively, if the "while" loop is permitted to complete ("if" condition fails), then you force a return value. In this instance, you do not want an "else" statement if you expect to iterate through your entire "while" loop.
Well, in the exact case you provided, it's because you're "returning" after a match. Once a function returns, no code after the return is executed meaning if you ever pass the if conditional, the method breaks out of the loop and everything, making the else unnecessary.
Essentially: you don't need an else because if your conditional ever passes the code execution breaks out of method anyways.
You do not need else because you if the element t is found return i yields the index, otherwise you exit loop without encountering t, return -1 will be executed. But feel free to add else pass if it make you more comfortable.
As explained above, else: return -1, is an error, with such else clause the function will only the check the first element of the list being t
In Python the indentation decides the scope, so the return -1 is actually outside of the while loop. Your code will return -1 only if t is different from all p.

Categories