I made a program in python that basically gets each word from a sentence and puts them into a palindrome checker. I have a function that removes any punctuation put into the sentence, a function that finds the first word in the sentence, a function that gets the rest of the words after the first word of the sentence, and a function that checks for palindromes.
#sent = input("Please enter a sentence: ")#sent is a variable that allows the user to input anything(preferably a sentence) ignore this
def punc(sent):
sent2 = sent.upper()#sets all of the letters to uppercase
sent3=""#sets sent3 as a variable
for i in range(0,len(sent2)):
if ord(sent2[i])==32 :
sent3=sent3+sent2[i]
elif ord(sent2[i])>64 and ord(sent2[i])<91:
sent3=sent3+sent2[i]
else:
continue
return(sent3)
def words(sent):
#sent=(punc(sent))
location=sent.find(" ")
if location==-1:
location=len(sent)
return(sent[0:location])
def wordstrip(sent):
#sent=(punc(sent))
location=sent.find(" ")
return(sent[location+1:len(sent)])
def palindrome(sent):
#sent=(words(sent))
word = sent[::-1]
if sent==word:
return True
else:
return False
stringIn="Frank is great!!!!"
stringIn=punc(stringIn)
while True:
firstWord=words(stringIn)
restWords=wordstrip(stringIn)
print(palindrome(firstWord))
stringIn=restWords
print(restWords)
Right now I am trying to use the string "Frank is great!!!!" but my problem is that I'm not sure how to stop the program from looping. The program keeps getting the "GREAT" part of the string and puts it into the palindrome checker and so on. How do I get it to stop so it only checks it once?
you can stop it like that
while True:
firstWord=words(stringIn)
restWords=wordstrip(stringIn)
#if the word to processed is the same as the input word then break
if(restWords==stringIn) : break
print(palindrome(firstWord))
stringIn=restWords
print(restWords)
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 months ago.
Apologies for the vague title. I wasn't sure how to make it specific enough.
I have some code that asks for a word and then turns it into a list of characters. I wanted to pass it through a loop to check in its isalpha().
When I run it. If my word is alpha it works fine. If my word has digits, it will restart the loop as planned and ask again.
However, the word gathered after a digit attempt will return a "None" and throw up an error when it tries to turn it into a list.
def start():
word = input("Enter word to turn into a list")
if word.isalpha():
word = word.lower()
return word
else:
print("Alpha only please")
start()
user = start()
word_list = list(user)
print (word_list)
This is because an implicit return None is observed in cases where a function does not return a value.
The above code is the same as below:
def start():
word = input("Enter word to turn into a list")
if word.isalpha():
word = word.lower()
return word
# all paths above return a value, so technically `else` is redundant here
# else:
print("Alpha only please")
start()
## added ##
return None
However, as mentioned in the comments, what you really want to use here is a while loop:
def start():
while 1: # infinite loop, exited with a `return` or `break` statement
word = input("Enter word to turn into a list: ")
if word.isalpha():
# looks good, exit loop and return the value
return word.lower()
print("Alpha only please\n")
# continue to the next `while` loop iteration
user = start()
Write a function longest_word that asks the user for words and returns the longest word entered by the user. It should stop when the user hits return without typing a word. If multiple words have the same maximum length, return the first word entered by the user. If the user quits before entering any words, return “No words were entered”. This function should use a searching loop. (Hint: remember that the len function returns the length of a string.)
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0
while len(word) > max :
max = len(word)
new_word = input("enter a word")
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
longest_word()
I understand that I need to iterate the while loop until the user enters without typing any words, but I do not know how to write the corresponding code.
The logic of your code had some flaws.
You need to run the while loop until the input is "" or an empty string and the len(word)>max needs to be inside an if statement. This is because the input value decides whether to break the loop or continue it, the difference in lengths just determines the result.
The returned word should be the longest one(only). But the block:
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
Prints every entered word that is longer than the previous one.
3. You need to change the value of the previous word or the longest word every time a longer word is entered so that it is updated, not just the value of the length.
The code might look like:
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0 # This variable is not exactly required
longest = word # this variable stores the longest word(currently)
new_word = None # This assignment is for checking for empty strings
while new_word != "" :
max = len(word)
new_word = input("enter a word")
if len(new_word) >= len(longest): # If the entered word is longer, change
# value of the longest word
longest = new_word
print(longest) # Print the longest word.
longest_word()
This is not necessary but avoid naming variables the same as keywords as it often causes a confusion
Some key points of what this function needs to do:
It needs to return the longest word, not print it.
It needs to keep track of the longest word seen so far (so it can return it when it's done). Keeping track of the length of the longest word is not sufficient.
Here's how I might write it:
def longest_word():
longest = ""
while True:
word = input("enter a word")
if not word:
return longest or "No words were entered"
if len(word) > len(longest):
longest = word
Note that the return line immediately ends the loop once no word is entered, and the or statement handles the case where nothing was entered prior to that point.
The remaining if statement ensures that longest is the longest word seen so far.
I want to make a hangman game that randomises the word each time you guess a letter, but keeps the wrong letters wrong and the ones you guessed at the same place in the new word. (Like if your word was cat in the beginning and you guessed the 'a'; now the word can be hat.)
I feel like I want to implement too many statements in a while loop and it breaks somehow.
I have this function
def RevealLetters(inputLetter):
LetterPositons.clear()
global WrongGuessCounter
for pos,char in enumerate(Word):
if(char == inputLetter):
LetterPositons.append(pos)
for x in LetterPositons:
if MaskedWord[x] == "_":
MaskedWord[x] = inputLetter
if len(LetterPositons) == 0:
WrongGuessCounter += 1
WrongLetters.append(inputLetter)
Which adds the wrongly guessed letter to a list and those letters should not be used again.
Then in another function I have this while loop which should be able to go thru the list of words and select words that are a specified length (the length was set in another function)
def RandomiseWord():
global Word
print("Randomising Word!")
Word = random.choice(WordBank)
LetterPositons.clear()
while (len(Word) != len(MaskedWord)) and (all(letter in Word for letter in WrongLetters)) :
Word = random.choice(WordBank)
but this somehow gives me words that either contain a letter from the list or a word with a different length.
I tried using if statements inside the while but it broke it further.
And lastly how may I check for words that have the same letters in the same place?
The issue was in my while. it has to be the "Or" statement.
in the end the randomise function looked like this:
def RandomiseWord(): #Randomises the word to add a challange to the game
global Word
global MaskedWord
global WrongLetters
print("Randomising Word!")
Word = random.choice(WordBank)
LetterPositons.clear()
while len(Word) != (len(MaskedWord)+1) or all(letter in Word for letter in WrongLetters) or not all(CheckWord()) :
Word = random.choice(WordBank)
and for finding words with letters in the same place I used:
def CheckWord(): #checks if the word contains the letters in the same place as the hidden one
global MaskedWord
global Word
Match = []
LetterList = list(Word)
LetterList.pop()
for x in range(len(MaskedWord)):
if MaskedWord[x] == "_":
continue
elif MaskedWord[x] == LetterList[x]:
Match.append(True)
else:
Match.append(False)
return Match
I'm trying to make a Hangman game in Python but I lack the knowledge of several things it seems. This code below is a rough draft on what I got so far. The idea here is using words from a text file, separating them into a list and then taking a random entry on that list to use as the word for the game. After that, it takes an input from the user on a letter: if the input is in the list, it should print a the word, but turning the letters that weren't guessed yet into "_". So, for example: ____a _. The problem is, I don't know how to do this and it's very confusing. As you can see below, I was trying to use a "for" loop.
import random
import string
# Opening the text file that contains the words that are going to be used in the game
with open('words.txt') as file:
text = file.read()
words = list(map(str, text.split()))
result = random.choice(words)
list_of_letters = list(result)
attempts = 1
for attempts in range(6):
pick = input("Pick a letter: ")
if pick in list_of_letters:
print(pick)
else:
print("_")
#Here is supposed to be what you get as a result when you lose, I want to keep track of the progress like __a__a__, for example.
else:
print("You lost! The word was", result, "\n Here's your progress: ", )
You should do a few more tutorials in python you have made some minor errors in terms of efficiency and methodology. But to answer your question I made this example of a hangman game. Hopefully you can learn from it
My words.txt file looks like this these are some words
# String or str() is a primitive type in python. You don't need to import it.
import random
# Opening the text file that contains the words that are going to be used in the game
with open('words.txt') as file:
# Here I read the file, replace newlines ('\n') with a space and then split the entire thing.
words = file.read().replace('\n', ' ').split(' ')
# function to grab a new word and list of letters
def new_choice(words):
res = random.choice(words)
l_of_letters = list(res)
return res, l_of_letters
# function to evaluate the pick and manage progress
def check_pick(l_of_letters, pick, progress):
new_progress = []
match = False
# if you have already guessed the letter it returns immediately
if pick in progress:
print('You have already guessed that letter!')
return progress, False, True
for letter in l_of_letters:
# if the letter has not been guessed previously
if letter not in progress:
# see if it matches the pick
if pick == letter:
# if it does return a successful match and add it to new_progress
match = True
new_progress.append(pick)
else:
# otherwise add the default underscore
new_progress.append('_')
# if it has been guessed before then add it
else:
new_progress.append(letter)
# you win if new_progress is all letters
w = '_' not in new_progress
return new_progress, w, match
# function to continually ask for input until it is appropriate
def pick():
p = input("Pick a letter: ").strip(' ')
if p == '':
print('Guess cannot be blank!')
pick()
return p
# Beginning of main loop. This will loop forever until break is called in the main loop
while True:
# get a word choice
result, list_of_letters = new_choice(words)
print('_' * len(list_of_letters))
# progress is started as a list of underscores the length of the word
progress = ['_'] * len(list_of_letters)
win = False
attempts = 6
# this nested while loop asks the user to input their choice, evaluates and tracks progress. It does this until you run out of attempts
while attempts is not 0:
print('Attempts: ', attempts)
# ask for a pick
p = pick()
# check the pick and the progress
progress, win, match = check_pick(list_of_letters, p[0], progress)
# if check_pick() returns win == True the game is over
if win:
print(f'You win! The word was \"{result}\"')
# this breaks out of the nested while loop
break
# if you haven't won it prints your progress
print(''.join(progress))
# if your pick was not a match you lose an attempt
if not match:
attempts -= 1
# if the loop finishes and you haven't won it prints this message
if not win:
print(f"You lost! The word was \"{result}\"\nHere's your progress: {''.join(progress)}")
So I am trying to create a function that calls two functions within the function where one function called "encode" checks if the first letter of a word is a vowel and if yes it will add "way" to the end of the word and if the word starts with a consonant it will move the first letter to the third position in the word and adds gar.
my problem is creating that function that calls from the encode function to read a sentence and change each word accordingly based on the first letter.
So here are some text cases for the function:
encode() function:
The output will look like this:
Please enter your message: python is fun
The secret message is: ythonpar isway unfar
translation is correct when words are separated by more than one space character.
Please enter your message: simple is better than complex
The secret message is: implesar isway etterbar hantar omplexcar
Here is my script. They are suppose to be connected.
def get_input():
user_input = input('Please enter a message: ')
more_message = True
while more_message:
user_input = input('Please enter a message: ')
if not user_input==' ':
more_grades = False
return
def starts_with_vowel(word):
while True:
data = word
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
print ('true')
else:
print ('false')
return
def encode(word):
while True:
data = starts_with_vowel(word)
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
new_word=word+'way'
print ('The secret word is:',new_word)
else:
new_word2=word+'ar'
scrambled_word=new_word2[1:-2]+new_word2[0]+new_word2[3]+new_word2[4]
print (scrambled_word)
print ('The secret word is:',new_word2)
return
def translate(text):
secret_message= encode(text)
return (secret_message)
translate('gin is a boy')
A better approach would be to use split on the sentence (input) and loop over the words:
vowels = 'aeiou'
sentence = 'python is fun'
new_words = []
for word in sentence.split():
if word[0].lower() in vowels:
new_words.append(word+'way')
else:
new_words.append(word[1:3]+word[0]+word[3:]+'gar')
' '.join(new_words)
'ytphongar isway unfgar'
I think in the first part of the code you will need to change the more_grades section with more_message, because first off more_grades has not been initialized and more_messages is controlling your loop so i think that's what you meant to do. Don't worry I believe that's only one error I have caught I will check the rest of the code and get back to you. Don't stress it.Happy coding :-)