I'm making a Morse code program:
def main ():
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
phrase = input("please enter your word or words: ")
for key in phrase:
print("your word or sentence translated to morse code is : ")
print(morse_code[key], end = " ")
if phrase == int or float:
print("try the input")
retry()
def retry ():
main()
retry()
main()
How do I print an error if someone enters a number?
This is what you need:-
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
phrase = input("please enter your word or words: ")
if any(char.isdigit() for char in phrase):
print("try the input")
else:
print("your word or sentence translated to morse code is : ")
code = ' '.join(morse_code[key] for key in phrase)
print(code)
You can use str.isdigit
for key in phrase:
if not key.isdigit():
print("your word or sentence translated to morse code is : ")
print(morse_code[key], end = " ")
You can check if the input is between a and z by doing:
try:
index = ord(key.lower())
if index >= 97 and index <= 122:
# Do your thing
except TypeError:
# Wrong input
The TypeError shouldn't happen, it's just good practice to wrap code with errors handling.
Or, you can do:
if not key.isdigit():
# Key isn't between 0 and 9. Can be uppercase or a symbol, though.
if ord(key.lower()) >= 97 and ord(key.lower()) <= 122:
# Do your thing. It's pretty much the same as before but with one more step.
Your first problem you will have is that the if statement is A: after the printing out of the Morsecode version of the letter, and B: it is outside of the for loop completely.
You can rectify this by putting it in the for loop before the printing like so:
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if phrase == int or float:
print("try the input")
else:
print(morse_code[key], end = " ")
However the above code still won't work, as the way you are checking if the current letter being printed out is a int or float isn't how you do it.
The easiest method is to change the codition of the if statement to if key.isdigit():
This will leave you with this final block of code:
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if key.isdigit:
print("try the input")
else:
print(morse_code[key], end = " ")
This now works, however, lets say I enter abc123. The output I would get is .-
-...
-.-.
try the input
try the input
as the code is running the forloop regardless of if there are numbers in the input or not. To prevent this, you should check the input for numbers, before you have the for loop printing out the morse code.
phrase = input("please enter your word or words: ")
while not phrase.isalpha():
phrase = input("invalid input: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
print(morse_code[key], end = " ")
If you need any help, let me know!
Using isdigit() will solve your problem also use break to receive new input
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in range(0,len( phrase)):
if phrase[key].isdigit():
print("you inderted an digit , Try another input")
break
else:
Morse_Parse.append(morse_code[phrase[key]]+" ")
print("Morse for your input is "Morse_Parse)
using flag will improve print task
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
flag=1
for key in range(0,len( phrase)):
if phrase[key].isdigit():
print("you inderted an digit , Try another input")
flag=0
break
else:
Morse_Parse.append(morse_code[phrase[key]]+" ")
if flag==1:
print("Morse for your input is "Morse_Parse)
how to only allow letters
How do I print an error if someone enters a number?
The second case is covered easily by checking .isdigit on each character as others mentioned. But I will cover the first case.
Start by defining a string of valid characters. Assuming your valid character set is lowercase a-z, this would be the same as string.ascii_lowercase
import string
valid_characters = string.ascii_lowercase # a-z
def char_valid(c):
'''Check if a character is valid, returns True/False'''
return c in valid_characters
def phrase_valid(phrase):
'''Check if the phrase is valid, returns True/False'''
return all(char_valid(char) for char in phrase)
while True:
user_phrase = input('Enter some characters')
if phrase_valid(user_phrase):
# If the phrase is valid, end the loop
break
else:
print('That was not a valid phrase')
# the loop continues and will ask for input again
This pattern works any time you want to keep asking for input until it is valid.
Related
I have this simple program that takes input of a word, asks the user what part they would like to substring out and then asks what to replace it with and lastly print the result. But i need to convert it into working recursively.
I've created it in a basic sense working in Python here.
word = input("Enter a word: ")
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)
It should work recursively and display like:
Enter a word: world
Please enter the substring you wish to find: or
Please enter a string to replace the given substring PP
Your new string: is wPPld
Help would be greatly appreciated.
You can use a while loop, but you need to define a stop word to have a way out. In this example, I defined the stop word as quit:
word = ''
while (word != 'quit'):
word = input("Enter a word: ")
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)
I think that this is what you want, but please note that this is not recursion.
EDIT: a version of the code using recursion with the same stop word:
def str_replace_interface():
word = input("Enter a word: ")
if word != 'quit':
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)
str_replace_interface()
str_replace_interface()
So I am stuck with the part of checking if the letter is present in the word or not. The game needs to let a person guess a letter in the word, and tell if this letter is present in word or not(5 attempts only)
import random
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
for j in range(0,len(word)):
if inp == word[j]:
print("Yes, we have this letter.")
else:
print("No, we don't have this letter.")
i=i+1
The expected output would be one sentence, either confirming that the letter is present in word, or disproving. However, the actual output is that is prints one sentence per each of letters in the given word, like this:
What's your guess for a letter in the word?
p
Yes, we have this letter.
No, we don't have this letter.
Instead of checking against each letter of the word (and thereby printing it each time), just check whether the letter is in the word:
while i<5:
inp = input("What's your guess for a letter in the word?\n")
if inp in word:
print("Yes, we have this letter.")
You can try regular expression:
import random
import re
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
res = re.findall(inp, word)
length = len(res)
if length == 0:
print("Your guess is wrong :( ")
else:
print(f"You guess is right :) ")
i +=1
here the output of regular expression is a list so you can do whatever you want with it, e.g. hangman game or ...
I am working on an assignment where we have to ask the user for a word, and then if the word has a letter that repeats the initial letter in the word, such as: ApplesAuce (the A repeats), the program will store the word in the list and then print out the list when the user is done entering words.
I am getting this error
if word[0].lower() in word[1:].lower(): IndexError: string index out
of range
Here is my code:
wordlist = []
word = input("Please enter a hilariously long word: ")
# I said "hilariously long" to increase the likelihood of a repeat letter
while wordlist != '':
word = input("Please enter another hilariously long word: ")
if word[0].lower() in word[1:].lower():
wordlist.append(word)
word = input("Please enter another hilariously long word: ")
print("All of the words that had repeated first letters are: ")
print(wordlist)
Test for the presence of a word and break out of the while loop if it isn't there.
wordlist = []
msg = "Please enter a hilariously long word: "
# I said "hilariously long" to increase the likelihood of a repeat letter
while True:
word = input(msg)
if word:
if word[0].lower() in word[1:].lower():
wordlist.append(word)
else:
break
print("All of the words that had repeated first letters are: ")
print(wordlist)
Note also that wordlist is a list so the test while wordlist != "" will always be the case because a list is not a string
This should work.I have introduced the breaker that is quit or done will break the loop. I have also moved your first input inside which will add another if wordlist is populated.
wordlist = []
# I said "hilariously long" to increase the likelihood of a repeat letter
while 1:
word = input("Please enter {}hilariously long word: ".format('another ' if wordlist else ''))
# get out if done or quit is typed
if word in ('done','quit'):
break
if word[0].lower() in word[1:].lower():
wordlist.append(word)
print("All of the words that had repeated first letters are: ")
print(wordlist)
Here is my code:
letters = ['a','b','c']
print("here are the letters you already searched",letters)
letter = input("please enter a letter")
print(letter)
letters = letters.append(letter)
It won't append it to the list. I also tried this:
letters = ['a','b','c']
print("here are the letters you already searched",letters)
letter = input("please enter a letter")
print(letter)
letters.append(letter)
Your first example won't work because you're using letters = letters.append which with = is trying to reassign the letters variable, your second example is the correct one, but...
...what you might be looking for is a loop so you can continuously enter letters, while True: is one way of creating a loop:
letters = ['a','b','c']
while True:
print("here are the letters you already searched",letters)
letter = input("please enter a letter: ")
letters.append(letter)
to have an option to break out of the loop use break
letters = ['a','b','c']
while True:
print("here are the letters you already searched",letters)
print("type '_done_' to finish")
letter = input("please enter a letter: ")
if letter == "_done_":
break
letters.append(letter)
Use raw_input (with your second example) instead:
letter = raw_input("please enter a letter")
letters.append(letter)
You were probably entering a letter like d when asked for input when it actually should have been "d" (which will append properly). raw_input will always convert your letter to a string, so you may enter it like d. Please read over the difference:
input() interprets and evaluates the input which means that if the user enters an integer, an integer will be returned, if user enters string, string is returned.
raw_input() takes exactly what the user typed and passes it back as a string. It doesn’t interpret the user input. Even an integer value of 10 is entered or a list is entered its type will be of string only.
Source
How do I repeat the program so its asks for a another word and let it only print my sentences once?
usersentence= input("Please type in a sentence without punctuation: ")
word= input("Please enter a word you want to search for in the sentence: ")
words = usersentence.split(' ')
for (i, words) in enumerate(words):
if (words == word):
print("your word appears in position(s): ")
print(i+1)
else:
print("Sorry yout word does not seem to be here")
To repeat the code, we use loops. You can use for or while loop depending on your problem. If you wont to repeat part of your code a specific number of times, for loop is your answer. For example:
usersentence= input("Please type in a sentence without punctuation: ")
for i in range(3): # number of words you wont to search
word= input("Please enter a word you want to search for in the sentence: ")
words = usersentence.split(' ')
passed = False # Something to check if the word is found
for (i, words) in enumerate(words):
if (words == word):
print("your word appears in position(s): ")
print(i+1)
passed = True # The word has been found
if not passed:
print("Sorry yout word does not seem to be here")