This is my code and I made it say "Please enter the right letter next time." when the incorrect base is inputted to the code, it does that it like:
Please enter the right letter next time.
None
How can I remove the "None" from appearing when ran?
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return print("Please enter the right letter next time.")
#main program
base1 = match_base("X")
print(base1)
It's because you're trying to return a print statement which doesn't make any sense.
Please change to:
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return "Please enter the right letter next time."
#main program
base1 = match_base("X")
print(base1)
If you don't want to recover, use an exception.
def match_base(base):
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
raise ValueError("Please enter the right letter next time.")
If you do want to recover, let the caller do the work:
def match_base(base):
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return None
base1 = match_base("X")
if not base1:
print("Please enter the right letter next time.")
else:
print(base1)
Note that this would be easier with a dictionary:
maps = {'A':'T', 'T':'A','C':'G','G':'C'}
def match_base(base):
return maps.get(base, None)
The reason you are getting None is because your program is trying to assign the print statement to a variable. print("Please enter the right letter next time.") cannot be a stored in a variable.
So it should look like this instead:
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
print("Please enter the right letter next time.")
Related
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
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
When user input is anything different from the specified letters "A", "a", "B", "b", "C", "c", "E", "e", it doesn't run the else statement but just closes. I would also like to have it repeat the program again if user input is not any of the specified letters, how can I achieve that? I believe it would be something I'd have to add in the else statement.
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Python is very indentation specific. This should do the trick:
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Your else should be part of the outer if (so same indentation), for now it is part of the inner if
Also you can simplify the tests, by first using .upper() to deal only with uppercase letters, and test the inclusion with user_input in "ABCDE"
user_input = input().upper()
if user_input in "ABCDE":
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Ask again version
user_input = input("Please choose: ").upper()
while user_input not in "ABCDE":
print("Something went wrong, try again: ")
user_input = input().upper()
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")
I am using python to create a text to binary translator, I checked everything and it seems alright but when I execute it, the program only prints the first letter of the text. Here's the code:
if beep == 1:
letter = letter + 1
if letter > length:
beep = 2
if list1[letter] == "a":
print abinary
elif list1[letter] == "b":
print bbinary
elif list1[letter] == "c":
print cbinary
elif list1[letter] == "d":
print dbinary
elif list1[letter] == "e":
print ebinary
elif list1[letter] == "f":
print fbinary
elif list1[letter] == "g":
print gbinary
elif list1[letter] == "h":
print hbinary
elif list1[letter] == "i":
print ibinary
elif list1[letter] == "j":
print jbinary
elif list1[letter] == "k":
print kbinary
elif list1[letter] == "l":
print lbinary
elif list1[letter] == "m":
print mbinary
elif list1[letter] == "n":
print nbinary
elif list1[letter] == "o":
print obinary
elif list1[letter] == "p":
print pbinary
elif list1[letter] == "q":
print qbinary
elif list1[letter] == "r":
print rbinary
elif list1[letter] == "s":
print sbinary
elif list1[letter] == "t":
print tbinary
elif list1[letter] == "u":
print ubinary
elif list1[letter] == "v":
print vbinary
elif list1[letter] == "w":
print wbinary
elif list1[letter] == "x":
print xbinary
elif list1[letter] == "y":
print ybinary
elif list1[letter] == "z":
print zbinary
else:
print "error."
Anyone know what is going on, I am fairly knew but I cant find this in any of my books.
If you want the code to run multiple times, you need to use a loop:
while beep == 1:
if list1[letter] == "a":
print abinary
...
letter = letter + 1
if letter >= length(list):
beep = 2
You can even do this more beautiful using a for-loop to iterate over all letters in your list:
for letter in list1:
if letter == "a":
print abinary
...
instead of chaining alot of elifs you should store the binary representation of the letters in a dictionary:
binary_letters = {
"a": "01100001",
"b": "01100010",
...
"z": "01111010"
}
this will simplify the loop to:
for letter in list1:
print binary_letters[letter]
The for loop that you can implement it as follows, you can even convert the letters to a binary string:
letter="k"
for n in range(97,123):
if ord(letter)<97 or ord(letter)>123:
#if character is not between 97-123 (a-z) print an error message
print("Error:Not in range")
break
#print(n)
if n==ord(letter):
#print the binary string if character is between the codes 97-123 (a-z)
print(format(ord(letter),'b'))
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
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.