Yesterday I coded a Hangman game. I got it finished and it works but now im asking myself "could it be better"?
I thought of a line of underscores to let the user know how many digits there are and than a way to chose. If the chosen letter is in the word that needs to be guessed it replaces the underscore with the letter.
This is my try
I dont know how to change the printed string or refresh the choice option.
Thx for any answer.
You can add end='\r' to the line which should be overwritten.
For the last line you should use the default end switch, otherwise the line is overwritten in the terminal (at least on linux).
import time
print('This is line 1', end='\r')
time.sleep(1)
print('This is line 2')
Related
I'm currently working through a introductory python book called "Think Python". In one of the exercises, I'm supposed to write a program that takes a string of characters, and counts how many words in file called "words.txt" (http://greenteapress.com/thinkpython2/code/words.txt) do not have letters from that string of characters.
My code is here:
fin = open('words.txt')
def avoids(word,forbidden):
avoided=True
for i in forbidden:
if i in word:
avoided=False
break #break out of for loop
if avoided==True:
return avoided
def number_avoids(forbidden):
"""Finds number of words excluded by character"""
avoided=0
for line in fin:
if avoids(line,forbidden):
avoided+=1
return avoided
print(number_avoids("a"))
print(number_avoids("a"))
What I'm confused about though, is why I got two different answers for the same code. For the first print(number_avoids("a")), the result was 57196. For the second one, the program printed out 0. Could someone explain to me why the same code will give out two different answers?
Thanks.
Problem
When you open a file, there's a cursor which points to the current position in file. At first function call, this cursor is at the starting of the file. So, it reads all the contents and your program works well.
But, when you call the function second time, the cursor is at the End of File. So, there are no more characters to read. You can verify it by adding a print(line) statement inside your loop of number_avoids function.
Solution
There's a builtin function to move the file cursor. You can use it to move your cursor to initial position:
...
print(number_avoids("a"))
fin.seek(0)
print(number_avoids("a"))
It will move your cursor to the start of file. So, all of the file contents will be read and evaluated again.
Note: I have tried to make this answer as basic as I can so that it can be understood by anyone without the knowledge of file handling. Feel free to ask for any clarifications in comments.
I just want to know why it's doing this, and how to fix it.
I've tried changing the screen size and it still doesn't work.
Any Ideas?
If you try to run the code, choose option C as that's the one that doesn't work for me. It's meant to print off all the moderate/high client's times, but it puts the total time on a new line.
Code + files:
Text file
Python code
Print statements automatically append "\n" to the end of the statement. This ensures that the next print statement will write to a new line instead of on the previous line.
If you want to prevent this, you can use this parameter:
print("This is a: ", end="")
print("message")
Notice the end="" on the first print statement. This will output
This is a: message
If that doesn't solve your issue, I suggest taking a close look at the text you're printing. Make sure that none of the lines have a "\n". Note that reading text from a .txt file will yield lines that automatically have "\n" appended to them.
I'm writing a program in python and I'd like to replace more than one line in the console with new text.
For example if I have 3 sentences printed to the console with:
print("Hello World!")
print("How are you!")
print("What's going on?")
Where each on is on a different line (and so has an \n).
How do I go about replacing all of this text when it displays in the console? I can't us \r in this situation due to the \n.
This is kind of an old post, but I came across it and worked out a solution as well. Added a timer, because otherwise the print statements bury each other and you'll only be able to read the last one. I'm on python 2.7:
import os
import time
os.system("printf 'Hello World!'")
time.sleep(1)
os.system("printf '\rHow are you?!'")
time.sleep(1.5)
os.system("printf '\rWhats going on?'")
os.system("echo ")
A simple fix would be to simply change the end separator for printing your strings. you can specify how you want the print function to separate calls with the end argument
print("hello world!", end="")
print("\rhello world again!")
In this case, we're setting the separator to "", which is nothing. So printing the next strings starts on the same line thus \r can be used. Compiling that gives you hello world again! on one line.
I have to write a program in python where the user is given a menu with four different "word games". There is a file called dictionary.txt and one of the games requires the user to input a) the number of letters in a word and b) a letter to exclude from the words being searched in the dictionary (dictionary.txt has the whole dictionary). Then the program prints the words that follow the user's requirements. My question is how on earth do I open the file and search for words with a certain length in that file. I only have a basic code which only asks the user for inputs. I'm am very new at this please help :(
this is what I have up to the first option. The others are fine and I know how to break the loop but this specific one is really giving me trouble. I have tried everything and I just keep getting errors. Honestly, I only took this class because someone said it would be fun. It is, but recently I've really been falling behind and I have no idea what to do now. This is an intro level course so please be nice I've never done this before until now :(
print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print
choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice
while choice != "q":
if choice == "a":
#wordlen = word length user is looking for.s
wordlen = raw_input("Please enter the word length you are looking for: ")
wordlen = int(wordlen)
print wordlen
#letterex = letter user wishes to exclude.
letterex = raw_input("Please enter the letter you'd like to exclude: ")
letterex = letterex.lower()
print letterex
Here's what you'd want to do, algorithmically:
Open up your file
Read it line by line, and on each line (assuming each line has one and only one word), check if that word is a) of appropriate length and b) does not contain the excluded character
What sort of control flow would this suggest you use? Think about it.
I'm not sure if you're confused about how to approach this from a problem-solving standpoint or a Python standpoint, but if you're not sure how to do this specifically in Python, here are some helpful links:
The Input and Output section of the official Python tutorial
The len() function, which can be used to get the length of a string, list, set, etc.
To open the file, use open(). You should also read the Python tutorial sec. 7, file input/output.
Open a file and get each line
Assuming your dictionary.txt has each word on a separate line:
opened_file = open('dictionary.txt')
for line in opened_file:
print(line) # Put your code here to run it for each word in the dictionary
Word length:
You can check the length of a string using its str.len() method. See the Python documentation on string methods.
"Bacon, eggs and spam".len() # returns '20' for 20 characters long
Check if a letter is in a word:
Use str.find(), again from the Python sring methods.
Further comments after seeing your code sample:
If you want to print a multi-line prompt, use the heredoc syntax (triple quotes) instead of repeated print() statements.
What happens if, when asked "how many letters long", your user enters bacon sandwich instead of a number? (Your assignment may not specify that you should gracefully handle incorrect user input, but it never hurts to think about it.)
My question is how on earth do I open the file
Use the with statement
with open('dictionary.txt','r') as f:
for line in f:
print line
and search for words with a certain length in that file.
First, decide what is the length of the word you want to search.
Then, read each line of the file that has the words.
Check each word for its length.
If it matches the length you are looking for, add it to a list.
For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.
I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?
How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?
You mentioned this was a simple game so a simple solution seems fitting.
[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print '\n' * numlines
word = raw_input("Your word: ")
import sys
sys.stdout.write("\x1b[1A" + 25*" " + "\n")
This will replace the last line printed with 25 spaces.
I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.
Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.
Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline