Blank line left in before input - python-3.x

I am trying to get my output to look like this:
You have 6 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: ​ a
Good guess: _ a_ _
But mine looks like this:
You have 1 guesses left
Available Letters: bcdfghjklmnopqruvwxyz
Please guess a letter: m
That letter in not in my word: _ i_ _ s
What Python 3.X is doing is putting a blank line above when I use an input statement like this:
user_guess = input('Please guess a letter: ')
Anyway to get rid of that blank line?

Related

I dont know how to program one part of a word guess program

I am creating a guess a letter game in python. the program chooses a random word from a file and the user has the amount of letters to guess the letters to the word. There is one part I am having trouble coding. I need to display the word as dashes and after every guess change the dashed word to include the correctly guessed letters in their corresponding position. So the output looks something like this.
Welcome to Guess a Letter!
Your word has 10 letters
You have 10 incorrect guesses.
Here is the word:
Enter a letter: e
Awe, shucks. You missed with that letter
Enter a letter: a
You got a hit! Here's what the word looks like now:
-------a-a
Enter a letter: o
Awe, shucks. You missed with that letter
Enter a letter: u
Awe, shucks. You missed with that letter
Enter a letter: i
You got a hit! Here's what the word looks like now:
---i---a-a
Enter a letter: y
You got a hit! Here's what the word looks like now:
-y-i---a-a
Enter a letter: t
You got a hit! Here's what the word looks like now:
-y-i-t-ata
Enter a letter: l
You got a hit! Here's what the word looks like now:
ly-i-t-ata
Enter a letter: s
You got a hit! Here's what the word looks like now:
lysist-ata
Enter a letter: r
You got a hit! Here's what the word looks like now:
lysistrata
You won!
Great job!
so here is what i have so far
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = ""
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word = hidden_word + "-"
print(hidden_word)
list(hidden_word)
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
hidden_word.join(' ')
print(hidden_word)
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
Just need help with what is in the game() function
Since strings a immutable, I would use a list to keep track of the guesses and then transfer that to a string in order to print it out. Here is your code modified to reflect those changes :
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = []
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word.append ("-")
print_out = ''
print(print_out.join (hidden_word))
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
print_out = ''
print(print_out.join (hidden_word))
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
I group all functions into one so we don't need to declare global variables. I also add something:
use .lower() to accept uppercase input
a statement telling user how many guesses left
win and lose condition
import random
def game():
# pick_word_from_file()
# using with to close the file automatically
with open("wordlist.txt") as f:
wordlist = f.readlines()
word = random.choice(wordlist).strip("\n")
# game_intro()
print("Welcome to Guess a Word!\n")
print("Your word has", len(word), "letters")
# why we need to say incorrect guesses from the start?
# print("You have", len(word), "incorrect guesses.")
# dashed_word()
# use a list to save letters because string is immutable
hidden_word = ["-" for w in word]
print("".join(hidden_word))
# number of guesses equal to length of word
for guesses in range(len(word)):
# tell user how many guesses left
print(f"You have {len(word) - guesses} guesses left.")
# use .lower() so user can also input uppercase letter
guess = input("Please enter a letter as your guess: ").lower()
change = False
for i in range(len(word)):
if word[i] == guess:
hidden_word[i] = guess
change = True
if change:
print("You got a hit! Here's what the word looks like now:")
print("".join(hidden_word))
else:
print("Awe, shucks. You missed with that letter.")
if "".join(hidden_word) == word:
print("You won! Great job!")
break
# you lose when you are out of guesses
else:
print("You lose.")
game()
Output:
"""
Welcome to Guess a Word!
Your word has 10 letters
----------
You have 10 guesses left.
Please enter a letter as your guess: E
Awe, shucks. You missed with that letter.
You have 9 guesses left.
Please enter a letter as your guess: A
You got a hit! Here's what the word looks like now:
-------a-a
You have 8 guesses left.
Please enter a letter as your guess: O
Awe, shucks. You missed with that letter.
You have 7 guesses left.
Please enter a letter as your guess: U
Awe, shucks. You missed with that letter.
You have 6 guesses left.
Please enter a letter as your guess: I
You got a hit! Here's what the word looks like now:
---i---a-a
You have 5 guesses left.
Please enter a letter as your guess: Y
You got a hit! Here's what the word looks like now:
-y-i---a-a
You have 4 guesses left.
Please enter a letter as your guess: T
You got a hit! Here's what the word looks like now:
-y-i-t-ata
You have 3 guesses left.
Please enter a letter as your guess: L
You got a hit! Here's what the word looks like now:
ly-i-t-ata
You have 2 guesses left.
Please enter a letter as your guess: S
You got a hit! Here's what the word looks like now:
lysist-ata
You have 1 guesses left.
Please enter a letter as your guess: R
You got a hit! Here's what the word looks like now:
lysistrata
You won! Great job!
"""

Words containing given letters

I'm trying to solve a task with the following content:
Create a function that retrieves the word and string of required letters and returns True if the word has all the required letters at least once.
My code looks like that:
def uses_only(letters, word):
letters = str(input("Enter letters : "))
word = str(input("Enter word : "))
if letters in word:
print("T")
else:
print("F")
uses_only(input, input)
But it doesn't work properly, becouse it returns F if the letter occurs more than once in the word. I searched the internet, but I didn't find anything that would help me. Can somebody explain me how to solve this task correctly?
I'm not sure I understood what you're trying to do.
This is a possible solution: the function checks whether each letter exists at least once in the word.
def f(word, letters):
return all(l in word for l in letters)
For example:
f("information", "oat") # true
f("information", "zfa") # false
you can also do it on this way, probably its something what you was trying:
def uses_only(letters, word):
letters = str(input("Enter letters : "))
word = str(input("Enter word : "))
for letter in letters:
if letter not in word:
return False
return True
print (uses_only(input, input))

I don't know why this is not printing the way I think it should

This is for a homework assignment, we were asked to write a for loop that starts at the beginning of a user inputted string and then print every 2nd letter
I have tried to add a new line but that didn't solve the issue. I have tried to do it without using the range function by using
for char in s: and that produces the same results as using the range function
s = input('Please enter a string: ')
for i in range(len(s)):
print(i, s[0::2].upper())
If the word was Testing it should print out like this
T
S
I
G
with every letter capitalized. It wouldn't be double spaced I just had to format it look right on here. My code will pick up every 2nd letter but it prints it all out on one line instead of printing it out individually and then prints out TSIG 7 times.
This one is probably what you want.
INPUT:
s = raw_input('Please enter a string: ')
s=s[0::2].upper()
for i in range(len(s)):
print(s[i])
OUTPUT:
Please enter a string: TESTING
T
S
I
G
Try this:
s = 'testing'
for i in s[::2]:
print(i)
Your issue is that you are printing s[0::2].upper() every loop, and it is not affected by i:

LUA: Reading text after reading number does not work

I am struck with the io.read command in LUA. The example below jumps over the text-read line. That only happens if there is a number input before.
repeat
print("Input number!")
number=io.read("*n")
print("Would you like do to this again? (y/n)")
again = io.read()
until again == "n"
I tried this in two IDEs (repl and ZeroBrane) and it drives me MAAAD!!!
Cany anyone help, please?
Cheers,
Ulrich
Try reading line by line as string and convert string to number using tonumber()
repeat
print("Input number!")
num = tonumber(io.read())
print('Would you like do to this again? (y/n)')
again = io.read()
until again == 'n'
While debugging, I see that second io.read is using the buffer started just after your number ends.
Your code with some more prints
repeat
print("Input number!")
-- num = tonumber(io.read())
num = io.read('*n')
print('you entered-> ' .. tostring(num))
print('Would you like do to this again? (y/n)')
again = io.read()
print('your choise from (y/n)-> ' .. again)
until again == 'n'
output
Input number!
234
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)->
Input number!
234y
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)-> y
Input number!
234234n
you entered-> 234234
Would you like do to this again? (y/n)
your choise from (y/n)-> n
This description is from Programming in Lua: 21.1
The call io.read("*number") reads a number from the current input file. This is the only case where read returns a number, instead of a string. When you need to read many numbers from a file, the absence of the intermediate strings can make a significant performance improvement. The *number option skips any spaces before the number and accepts number formats like -3, +5.2, 1000, and -3.4e-23. If it cannot find a number at the current file position (because of bad format or end of file), it returns nil.
Please apologize for the poor description.

What is going wrong in my hangman program?

I'm trying to get a function to put correct guesses in their blanks in a hangman program, but all it does is, whatever the guess and no matter whether it's right or wrong, it just gradually reveals the word. Where am I going wrong?
code:
while lettersrevealed!=word:
guess=getGuess(lettersrevealed)
for i in range(len(word)):
if guess in word:
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
ex:
(secret word is badger)
Guess a letter:
a
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
OR:
Guess a letter:
h
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
The issue is with the for loop
for i in range(len(word)): # This will run 6 times for "badger" | 0, 1, .., 5
if guess in word:
# blanks == ****** then gradually gets the next letter added replacing a *
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
You probably want something like this.
def convert_to_blanks(word, letters):
return ''.join(c if c in letters else '*' for c in word)
>>> word = 'badger'
>>> letters = set()
>>> convert_to_blanks(word, letters)
'******'
>>> letters.add('g')
>>> letters
{'g'}
>>> convert_to_blanks(word, letters)
'***g**'
And so you have a while loop prompting for letter something like this.
guessed = set()
word = 'badger'
while True:
guess = input("Guess a letter")
guessed.add(guess)
blanks = convert_to_blanks(word, guessed)
print(blanks)
if blanks == word:
break

Resources