Python guessing word game - python

I trying to convert my code using function. As this coding is not done yet but i manage to get the code running well. The only thing is every time i guess a letter, it reset my previous record. How to i store my previous guess result and continue add if the letter is guessed correctly?
import random
def chooseAword(wordList):
correct_word = random.choice(wordList)
return correct_word
#def spelltheword(word)
def guessAletter(guessedletter):
word = guessedletter
guess = input('Guess a letter: ')
letter = ''.join(x if x in guess else '-' for x in word)
if guess in word:
print("So far you have: ", letter)
else:
print("So far you have: ", letter)
return letter
def playAgame(wordList):
word = chooseAword(wordList)
for n in range(5):
guessletter = guessAletter(word)
def main():
wordList = ('python', 'csharp','java','oracle')
playAgame(wordList)
main()

No, it doesn't reset your previous record: you have no previous record. Every call to guessAletter very specifically puts a hyphen in any position that is not the currently guessed letter.
Yes, you return the word (which you named letter, for some reason) of hyphens and correct letters, but the calling program playAgame puts this into a local variable guessletter (another misleading name), and then never uses it again.
I have several suggestions:
Practice incremental programming. Write a few lines of code to perform a trivial part of your program. Debug them. Do not continue until you know they do what you want, through testing several possibilities. Then write a few more lines; repeat this process until your program works.
Use meaningful variable names. word doesn't tell us much; we don't know whether this is the word we're supposed to guess, the current game progress you show the user, or something else. At the worst, you use guessedLetter for something that is not a single letter, and is not a guess.
With the incremental programming, follow the status of your game state: this should be one value passed back and forth with your guess-and-check function. You update it in that function, and print it in the guess-a-letter loop.

Related

Python Lists , FIles, For Loops, Index

I am comfused with how to tackle this, I have done the first few parts by opening the file, converting it to a list and completing the first prompt but now I dont really understand how to do this. The prompt for this part is:
All Words that Have a User Chosen Letter in a Specified Location
This task builds on the first task, but instead of the letter appearing anywhere in the word, you need to output every word that has the letter in a very specific location. The user provides a single letter, and what location in the word it appears in. Make sure you give clear instructions to the user on how to denote the letter location (is the first letter 0? 1? something else? They won't know what your program expects unless you tell them).
All Words that Have a User Specified Number of Vowels
Supposedly the best way to play Wordle is to use a word with lots of vowels as your first guess. For this task you will let the user choose how many vowels they want in their word, and then output all words that have that number of vowels. This task is the hardest of the required tasks, so think about it after you've reasoned through the others. Recall that vowels in English are the letters a, e, i, o, and u.
import os.path
def name_file():
# asking user name of file
file_name = input("What is the name of the file to read the names from?")
while not os.path.exists(file_name):
print("This file does not exist")
file_name = input("What is the name of the file to read the names from?")
return file_name
name_file()
file_opener = open("5letterwords.txt","r")
read_line_by_line = file_opener.readlines()
word_list = []
for line in read_line_by_line:
word_list.append(line.strip())
print(word_list)
letter = input("Pick a letter of your choosing and every word with that letter will be outputted:")
for word in word_list:
if letter in word:
print(word)
letter2 = input("Pick another letter and every word with that letter will be outputted")
location = input("Pick what location you want the letter to be in from 1-5")
for word in word_list:
if letter2 in word and :
I currently have that done and starting from the variable letter 2 is where I start wrking on the prompt but I am clueless as to what to do. I would like some hints and tips on how to do this, i've been working on it for almost 3 weeks now and not much progress
I think there are three steps to your second task:
Get the input letter and index.
Iterate over the list of words.
Check each word to see if the letter is in the desired index and print the word if so.
You have part of number 1 and all of number 2 handled already.
To finish the first step, you need to convert your location value, which is a numeric string, into an integer and make sure it matches the zero-indexing of Python strings.
For the third step, you need to index your each word string with the converted index value you got from the user. You might want some error handling here, to correctly report invalid indexes, but since that isn't specifically called out in your requirements something minimal might serve (e.g. print an error message and quit). The comparison of the indexed letter to the input letter should be trivial after that.

Looping and Lists - BaSe fOO ThE AttAcK

In the war against Skynet, humans are trying to pass messages to each other without the computers realising what's happening.
To do this, they are using a simple code:
They read the words in reverse order They only pay attention to the words in the message that start with an uppercase letter So, something like:
BaSe fOO ThE AttAcK contains the message:
attack the base
However, the computers have captured you and forced you to write a program so they can understand all the human messages (we won't go into what terrible tortures you've undergone). Your program must work as follows:
soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
code: soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
says: destroy their ice-cream supplies ​
Notice that, as well as extracting the message, we make every word lowercase so it's easier to read.
Could you please help me with my code? This is my code so far:
output=[]
b=0
d=0
code=input("code: ")
code=code.split()
print(code)
a=len(code)
print(a)
while b<a:
c=code[b]
if c.isupper:
output.append(c)
b=b+1
elif c.islower:
b=b+1
else:
b=b+1
print(output)
I need the last line to say "BaSe ThE AttAck" eliminating "fOO" and I will be reversing the string in the last step to make sense, but it is not differentiating between a lowercase word and an uppercase word.
I have rewritten your code.
#code=input("code: ")
code = "soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess"
code=code.split()
output = []
for word in reversed(code): #iterate over the list in reverse
if word[0].isupper(): #check if the FIRST letter (word[0]) is uppercase.
output.append(word.lower()) #append word in lowercase to list.
output = " ".join(output) #join the elements of the list together in a string seperated by a space " "
print(output)
output
destroy their ice-cream supplies
Here's My answer, Tested on grok learning and green across the board:
code = input('code: ')
code=code.split()
output = []
for word in reversed(code):
if word[0].isupper():
output.append(word.lower())
output = " ".join(output)
print('says:', output)
There are two issues with your code:
isupper and islower are methods, i.e. you need to call them by writing ().
c.isupper() will check if the entire word is upper-case. However, your problem description says to just consider the first character of each word. Hence, try using c[0].isupper().
Now, after that has been fixed, you're still left with reversing the output list (and making each word lowercase) but I suppose you didn't get to that just yet. :-)

How do you add a space, using an index, to a string using an integer in python?

More information
Below is my code. I am in the process of making a small program that finds Palindromes. I want the program to take user input, save it to a variable, and then check for any spaces. If it finds a space to save its index, and then to take it out to check for a Palindromes. Out of curiosity and to further my programming skills, I want to be able to add the space back later while the word is in reverse. For example, nurses run = nursesrun backward and forwards, but I also want to display it backward and add the space back.
word = input("Please enter a word")
storeVal = word.count(" ")
print()
newWord = word.replace(" ", "")
print(newWord)
print()
while True:
if newWord == "":
print("Sorry, but you did not enter a word")
break
elif newWord == newWord[::-1]:
#use the index storeVal and add it in the string to put a space back
print(" is a palidrone")
break
elif newWord != newWord[::-1]:
print("This is not a palidron")
break
else:
print("You have reached an error")
Also, if you have any suggestions for how I can improve my ability to ask this question or a better way I can write this question, please let me know. Thank you for reading.
Just reverse word instead of reconstructing the modified newWord!
print("{} is a palidrone".format(word[::-1]))
Also storeVal in your example isn't storing the index of the space -- it's storing the number of spaces in your input string.
As per the other answer, just for displaying you can print word instead of newWord. But if you want to learn how get the original positions of spaces, here are a few hints:
word.find(" ") will give you the index of the first space or -1 if none found, you can save it into a list, and than call word.find(" ", space_index + 1) to call the next one, where space_index is the index of last found space, until you get -1 which means no more spaces
another, more educated (to my opinion), would to enumerate the string and collect all indexes for spaces in a list using list comprehension (or set, of you don't care about the order).

I am trying to write the python code that can check repeat word in sentance

for this code i try to find if the word is repeat it will say word is "not unique" and if word does not repeat it will say word is "unique". I run the program but it showing error after i enter the sentence.
def isUnique():
words = sentence.split()
unique = {}
for i in words:
if word not in unique:
count[i] = true
else:
unique[i] = false
def main():
user_input = input("Enter word sperated by space: ")
uniques = isUnique(user_input)
print(uniques)
main()
There are loads of things causing errors in your code. I suggest at least learning the basics of how to define and call a function before trying to create one. Also you need to learn about variables and how to correctly reference them, and how to define boolean values.
The issues here are things you should have read about before writing the code.
Issue 1: Indentation
You haven't indented your code properly. You need to indent after you start a for loop (and everything within the for loop must remain indented. You need to indent after every if/elif/else statement, and everything pertinent to the statement must remain indented. Proper indentation of your code looks like this:
def isUnique():
words = sentence.split()
unique = {}
for i in words:
if word not in unique:
count[i] = true
else:
unique[i] = false
def main():
user_input = input("Enter word sperated by space: ")
uniques = isUnique(user_input)
print(uniques)
main()
Issue 2: No argument in isUnique()
When you define a function, if it requires an argument, then you need to specify the argument when you create the function. Like this:
def isUnique(sentence):
words = sentence.split()
unique = {}
for i in words:
if word not in unique:
count[i] = true
else:
unique[i] = false
Here, sentence will be the same as user_input when you call the function. This way, when the computer sees sentence inside the function, it knows that sentence is the argument in the function (i.e. the user input). The way you've written it, how should the computer know what sentence is if it's not in the function argument? Answer: it doesn't.
Issue 3: The loop iterator
With the for loop, you call each object you're iterating over i. But then inside the for loop, you refer to this object as word. Again, how can the computer know what word is if you haven't defined it. This is the correct way:
for word in words:
if word not in unique:
count[i] = true
else:
unique[i] = false
Issue 4: What is count?
Again, inside the for loop you reference a dictionary called count, but you haven't defined anything called count. Maybe you mean:
for word in words:
if word not in unique:
unique[i] = true
else:
unique[i] = false
Issue 5: Booleans start with a capital
Python's booleans should be True and False, not true and false.
Now the errors should be gone, but I'll leave the rest up to you. I'm not sure that the code will solve your problem correctly as it is.
But you need to learn the basics. Before you start learning about data structures like dictionaries, you should be very adept with the use of variables, for loops and if statements, which this question demonstrates that you are not. Please learn these things.

Count Occurrences using for, in, and return

I have been trying to write the code for this program for a while now, but I just cannot figure it out. I am very confused. I would appreciate the help:
Write a function that takes two strings. The second string should only be one character long. The function should return how many times the second string occurs in the first string.
You will need:
A function declaration, with parameters.
A for loop.
An if statement.
A return statement.
What I have so far:
string_one = "I love coding!"
string_two = "I"
if string_two in string_one: print "Hi"
Considering the code you have provided, it indeed works if string_two is in string_one, meaning that your if-condition is correct. However, it will only run once, so if string_two occurs multiple times in string_one, it will ignore all other occurences and print Hi only once. As a result, you need to add your if-condition into a for-loop to catch all occurences of string_two in string_one.
string_one = "I love coding!"
string_two = "o" # changed to 'o' since it has more than 1 occurence in string_one
for letter in string_one: # look at each letter in string_one, one after another
if string_two in letter: # also possible: if string_two == letter
print "Hi" # print Hi when the letter is found
All that's left to do now according to your task is to wrap this code into a function with two parameters (ideally one parameter called sentence and another one called character or similar) and return something. However, I will leave figuring this out to yourself, good luck! :)
First off, let's note that this problem could be solved using str.count(thing_to_count). That's what you should use in general, but I see here you are probably asking for help on an assignement (generally discouraged on Stack Overflow, but I personally don't have an issue with it). Anyway, here's the code I made for this.
def count_in_string (sentence, thing_to_count):
times = 0
for word in sentence:
for letter in word:
if letter == thing_to_count: times += 1
return times
So:
Declare count_in_string as a function with the arguments sentence and thing_to_count.
Set times to be the amount of times thing_to_count_ appears in sentence (so far 0).
Loop through every word, and then letter in the sentence.
See if the letter is the thing_to_count, and if so add 1 to times.
Return times as the result.

Categories