Python exercise - don't understand how this is working - python

I got stuck on this question on the Cisco training. I got to the answer, but don't understand why it works. Why does python remove the vowels after each 'continue'?
user_word = input("Enter your word: ")
user_word = user_word.upper()
for i in user_word:
if i == "A":
continue
elif i == "E":
continue
elif i == "I":
continue
elif i == "O":
continue
elif i == "U":
continue
else:
print(i)

It does not "remove" them, it just does not print() them.
The loop is executed for each character in the word. If it is a vowel, the current iteration is ended (see the continue statement) and the next character is considered. If it is NOT a vowel, it is printed to the output and you can "see" it.

The reason for this is as follows:
contunue means skip the loop, in fact it is this:
The continue statement, also borrowed from C, continues with the next iteration of the loop
So any vowel a, e, i, o, u gets skipped and any consonant is printed.
by way of example, if you replace the continue keyword with your own function you would see this more clearly:
user_word = input("Enter your word: ")
user_word = user_word.upper()
# a new function to replace continue
def replace_continue():
print('vowel is found')
for i in user_word:
if i == "A":
replace_continue()
elif i == "E":
replace_continue()
elif i == "I":
replace_continue()
elif i == "O":
replace_continue()
elif i == "U":
replace_continue()
else:
print(i)
try this code and it should be more obvious.
Here is a link to the docs:
https://docs.python.org/3/tutorial/controlflow.html

The vowels do not get removed as in deleted, they just get ignored. continue is a key word, which tells the loop to go to the next iteration. If you were to put another print in the loop, outside of the if/elif statements, it becomes more visible. You may want to check the documentation for further information
for i in user_word:
if i == "A":
continue
elif i == "E":
continue
elif i == "I":
continue
elif i == "O":
continue
elif i == "U":
continue
else:
print(i)
print('loop end')
Using the wourd 'continous' as value the above code yields :
C
loop end
N
loop end
T
loop end
N
loop end
S
loop end

Related

How come if I use the same variable in a for loop it works (retains its value) and if I use a different one it doesn't?

The code should replace all the vowels with the letter p. How come this code works. If I input "hello" it prints "hpllp"
for i in word:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
word = word.replace(i, "p")
print(word)
But this doesn't? It prints out "hellp"
translated_word = ""
for i in word:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
translated_word = word.replace(i, "p")
print(translated_word)
TYIA
In the first code you were setting the variable "word" to itself while performing replacements.
In the second you were setting the "translated_word" variable equal to the "word" replacement but without a way for the code to remember that in between loops and being constantly overwritten as the loop went on.
Depending on the use a function can be used with fairly little change to your current code.
def replace(word):
for i in word:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
word = word.replace(i, "p")
return(word)
translated_word = replace('hello')
print(translated_word)

How do I use the if statement for input starting with a certain letter

I am trying to print a certain output if the user's input (greet) begins with a certain word "hello" else if the input begins with h using the if statement.
I have tried:
if greet == "hello":
print("wrong")
elif greet == "h_" #(but not hello)
print(" okay")
else:
print("good")
You could also use .startswith():
if greet.startswith("hello"):
print("wrong")
elif greet.startswith("h"):
print("okay")
else:
print("good")
Try this. It ignores leading and trailing spaces by calling strip, it has a conditional for if nothing was placed in the input, and lastly it's case insensitive because it standardizes the input to lower:
greet = input().strip()
if len(greet) > 0:
firstWord = greet.split(" ")[0].lower()
if firstWord == 'hello':
print("wrong")
elif firstWord[0] == "h":
print("ok")
else:
print("good")
else:
print("You must enter something")

"while loop" not breaking (using Python)

This is my code :
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
When I input either a or b, it just asks me to "Enter A or B" again. It doesn't go to the functions its supposed to.
Any idea why is this?
The code is perfect, except a redundant else, as mentioned in the comment. Are you entering a (a + space) rather than simply a (a without space) ? The problem is in the input that you are providing and not in the code!
def chooseReport():
print "Choose a report."
t=True # t starts at true
while t:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
t=False # t turns false to break out of loop
elif choice == 'b' or choice == 'B':
reportB()
t=False
Try this. It keeps looping when t is true and stops when t is false. The problem might also be in reportA or reportB or how you are calling chooseReport.
The problem is in the raw_input(). It returns a string but maybe this string is "a " or "a\n" though you have entered "a" or "b".
I would do this:
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if "a" in choice or "A" in choice:
reportA()
break
elif "b" in choice or "B" in choice:
reportB()
break
else:
continue
Tried your code in the following script, it works fine both on Linux and on Windows.
def reportA():
print "AAAAA"
def reportB():
print "BBBBB"
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
chooseReport();
First, your code works fine, the most probably error is that you are writing a wrong input (e.g: with more characters). To solve that you could use "a" in choice or "A" in choice. But if it isn't working... keep reading.
It's seems that break isn't affecting the while loop, I don't have python 2 so I am not very sure why (in python 3 [after change raw_input to input and print to print()] your code works perfect). So you should use the condition of the while to break it.
while True work theorically for ever because each time the code is executed it checks the condition -True- and because it's true it keeps looping.
You could manipulate that condition in order to break the loop (don't allow execute again its code).
For example you could use this:
#Choose Report
def chooseReport():
print "Choose a report."
allow = True # allow start as True so the while will work
while allow:
choice = raw_input("Enter A or B: ")
if choice.lower().strip() == "a": # This is better. .lower() make "A" > "a", and .strip() delete " a " to "a", and "a/n" to "a".
reportA()
allow = False # allow now is False, the while won't execute again
elif choice.lower().strip() == "b":
reportB()
allow = False # allow now is False, the while won't execute again
# The else is complete redundant, you don't need it
Code is fine. I think you call your chooseReport() function in a loop or your input has extra characters and if conditions didn't satisfied.

How to find certain letters in a string when there are multiple?

I want to be able to pick out certain letters in a string but need to be able to get the place of multiple rather then just the first (Python). I currently have this code:
word=apple #just and example
character=input("Take a guess")
if character == "a":
place=word.find("a")
elif character == "b":
place=word.find("b")
elif character == "c":
place=word.find("c")
elif character == "d":
place=word.find("d")
elif character == "e":
place=word.find("e")
elif character == "f":
place=word.find("f")
elif character == "g":
place=word.find("g")
elif character == "h":
place=word.find("h")
elif character == "i":
place=word.find("i")
elif character == "j":
place=word.find("j")
elif character == "k":
place=word.find("k")
elif character == "l":
place=word.find("l")
elif character == "m":
place=word.find("m")
elif character == "n":
place=word.find("n")
elif character == "o":
place=word.find("o")
elif character == "p":
place=word.find("p")
elif character == "q":
place=word.find("q")
elif character == "r":
place=word.find("r")
elif character == "s":
place=word.find("s")
elif character == "t":
place=word.find("t")
elif character == "u":
place=word.find("u")
elif character == "v":
place=word.find("v")
elif character == "x":
place=word.find("w")
elif character == "w":
place=word.find("x")
elif character == "y":
place=word.find("y")
else:
place=word.find("z")
This works to find the place of one letter, but if I wanted to find both p's it wouldn't work, it'd only tell me the position of the first. So what I'm really wondering is if there is some loop I can put it through to find the letters and set them as two different variables such as "place" and "place2" or do I have to have this same thing multiple different times for each separate starting point.
You can use re.finditer() to get all occurrences of the substring:
>>> import re
>>> word = "apple" #just and example
>>> character = input("Take a guess: ")
>>> for occurrence in re.finditer(character, word):
... print('character: {}, {}'.format(character, occurrence.start()))
Regular expressions are a powerful tool. However, there is a considerable overhead in using regexps for a trivial string literal search.
Here is a simple alternative repeatedly calling str.find until all occurrences are found:
def findall(mainstring, substring):
pos = -1
while True:
pos = mainstring.find(substring, pos+1)
if pos == -1:
break
yield pos
for occurence in findall("apple", "p"):
print(occurence)
# prints: 1 2

How do I keep repeating "if"s?

I want my if function to keep repeating on python when it falls onto else. How do I do that? I've added an example of my code.
if selection1 == "C":
print("Ok")
elif selection1 == "E":
print("Ok")
elif selection1 == "Q":
print("Ok...") quit()
else:
selection1 == print("The character you entered has not been recognised, please try again.")
I don't know whether you meant this but this program does exactly as what your question asks
while True:
selection1 = input("Enter Character\n")
if selection1 == "C":
print("Ok")
elif selection1 == "E":
print("Ok")
elif selection1 == "Q":
print("Ok...")
break
else:
selection1 == print("The character you entered has not been recognised, please try again.")
The program takes in characters as inputs and checks them with the hardcoded characters. If not matched it will ask for the user to repeat until the letter Q is matched. An output can be
Enter Character
C
Ok
Enter Character
E
Ok
Enter Character
v
The character you entered has not been recognised, please try again.
Enter Character
Q
Ok...
Here are two possible approaches
while True: # i.e. loop until I tell you to break
selection1 = GetSelectionFromSomewhere()
if selection1 == 'C':
print('Okay...')
break
elif selection1 == 'E':
print('Okay...')
break
elif selection1 == 'Q':
print('Okay...')
quit()
else:
Complain()
Some purists dislike while True loops because they don't make it explicit what the looping condition is at first glance. Here's another listing, which has the advantage of keeping break statements and other housekeeping out of your if cascade, so you can focus on the necessary actions there:
satisfied = False
while not satisfied:
selection1 = GetSelectionFromSomewhere()
satisfied = True
if selection1 == 'C':
print('Okay...')
elif selection1 == 'E':
print('Okay...')
elif selection1 == 'Q':
print('Okay...')
quit()
else:
Complain()
satisfied = False
while selection1 != "Q":
if selection1 == "C":
print "Ok"
elif selection1 == "E":
print "Ok"
else:
print " Chose again"
print "quit"
quit()
while True:
n = raw_input("\nEnter charachter: ")
if n == "C" OR n=="E" OR n=="Q":
print("Ok !")
break # stops the loop
else:
n = "True"
characters = {'C','E','Q'}
def check():
ch=raw_input("type a letter: ")
if ch == q:
quit()
print "ok" if ch in characters else check()
check()
But you have already your answer from the previous posts. This is just an alternative.

Categories