Running code through iPython or command window by double clicking - python

When coding with Python, I've been using Spyder (as it came part of the package that I needed for work)
It comes with an editor, and of course a console, so I write my code and then run it there also.
It looks like this for those who are unfamiliar:
Here I can run my code no problem and get no errors.
Of course, I also save this code to a file, and I would like to get that code running by just double-clicking on the file name. Is that possible?
I can do it now and get a command prompt, but when I do it now I get this error:
(I'm using the same code that's in the images, can anyone tell me what I am doing wrong?
Here is my clear() code in case that matters:
def clear():
os.system(['clear','cls'][os.name =='nt'])
Edit:
Here's the last portion of the code, since the pictures are hard to read.
player = raw_input("What is your name? ")
The game itself
def hangman(player):
clear()
print "Hello! \nWelcome to Hangman, %s" % player
if init_play() == "quit":
print "Ok. Goodbye"
return
word = word_gen("text")
word_hidden = ["-" for x in range(0,len(word))]
av_letters = [chr(x) for x in range(97,123)]
guessed = []
turn = 1
print ("I am thinking of a word that is %d letters long\n" % len(word))
print "Here is the board\n"
print_board(word_hidden)
print "\nHere are your available letters:\n"
show_letters(av_letters)
while turn <= 5:
if word_hidden.count("-") == 0:
print "\nYou won!"
play_again()
print "\nGuess %d out of %d\n" % (turn, 5)
turner = word_hidden.count("-")
guess = raw_input("Guess a letter! ")
als = av_letters.count(guess)
guess_check(guess, guessed, word, word_hidden, turn, av_letters)
if als == 0:
pass
elif word_hidden.count(guess) == 0:
turn+=1
print ("You lose.\nThe word was %s\n" % word)
print ""
play_again()
clear()
hangman(player)

To use os.system, you need to import the os module first. The code is missing the import statement.
Put the following line at the beginning of the code:
import os

Related

My hangman program is stuck at asking for input and not printing any letters i guess

I am quite new to programming and I tried making a program like hangman. However I just can't figure out why it's not working. All it does is it asks for input and then does nothing. The input just loops over and over again and nothing changes whatever I type in.
Also any tips on how to improve my code are welcome, I feel like I've done a lot of mistakes here.
import random
word_list = ["car", "house", "shop", "shoes", "tractor", "microphone", "camera"]
game_state = True
blank_spaces = []
word_picked = ""
already_guessed = []
word_letters = []
def Word_picker():
word_number = random.randint(0, (len(word_list) - 1))
word_picked = word_list[word_number]
word_picked = word_picked.lower()
word_letters = [char for char in word_picked]
print("\n")
print(word_picked)
print(word_letters)
print("\n")
for char in word_letters:
blank_spaces.append("_ ")
def Printer():
print("\n \n")
for x in range(len(blank_spaces)):
print(blank_spaces[x], end='')
def Main():
guessed_letter = input("Try a letter:")
guessed_letter = guessed_letter.lower()
if guessed_letter in already_guessed:
print("You've already tried this letter. Try a different one. \n")
Main()
for z in word_letters:
if guessed_letter == word_letters[z]:
blank_spaces[z] = guessed_letter + " "
already_guessed.append(guessed_letter)
Main()
else:
print("Incorrect.")
already_guessed.append(guessed_letter)
Main()
def Already_guessed():
for a in already_guessed:
print("Already guessed letters:" + already_guessed[a] + ", ", end='')
Word_picker()
Printer()
while game_state:
Already_guessed()
Printer()
Main()
Your code isn't working for a number of reasons, but let's walk through some tips on how to debug your code and get it working.
An IDE-agnostic way of debugging is to add print statements to help figure out if your variables contain the values that you think they should.
Try adding this print statement print("This is word_letters: ", word_letters) in your Main() function before the line starting with for z in word_letters:
Ask yourself:
What do I expect this to return?
What does this actually return?
If there is anything unexpected, what is causing this?
For the print statement above: you'll find that your word_letters returns an empty list.
Is this what you expect?
Try doing this with the if statements and function calls.
If you work your way through your Main() and function calls, you should be well on your way to figuring out how to get your program running :)
I did some changes:
as pointed our by #Barmar, you are never returning the Main() function. I am now calling the function in a loop until gam_state changes to False.
also pointed out by #Barmar, you are using z as index which gives you an IndexError. z is already already_guessed[i] so you don't need that.
you are only changing the lists locally in the Word_picker, which did not work. I changed it to return the respective words and now you can access those from the Main() function.
you added the guessed letter in the for loop over all letters of the word, which did not break your code but itmade the output horrible and for more guessed causes your code to get unnecessary slow.
then some changes to your output so you only print text once outside the loop, etc.
import random
word_list = ["car", "house", "shop", "shoes", "tractor", "microphone", "camera"]
game_state = True
blank_spaces = []
word_picked = ""
already_guessed = []
word_letters = []
def Word_picker():
w_number = random.randint(0, (len(word_list) - 1))
w_picked = word_list[w_number]
w_picked = w_picked.lower()
w_letters = [char for char in w_picked]
print("\n")
print(w_picked)
print(w_letters)
print("\n")
b_spaces = []
for char in w_letters:
b_spaces.append("_ ")
print(b_spaces)
return b_spaces, w_picked, w_letters
def Printer():
print("\n \n")
for x in range(len(blank_spaces)):
print(blank_spaces[x], end='')
def Main():
guessed_letter = input("Try a letter:")
guessed_letter = guessed_letter.lower()
print(already_guessed)
if guessed_letter in already_guessed:
print("You've already tried this letter. Try a different one. \n")
for i, z in enumerate(word_letters):
if guessed_letter == z:
blank_spaces[i] = guessed_letter + " "
else:
print("Incorrect.")
already_guessed.append(guessed_letter)
def Already_guessed():
print("Already guessed letters:")
for a in already_guessed:
print(a)
blank_spaces, word_picked, word_letters = Word_picker()
Printer()
while game_state:
Already_guessed()
Printer()
Main()
Some Tipps for future work:
use print statements or import pdb;pdb.set_trace() for debugging, so you know what your code is doing
write short, small elements first and test straight away, don't code everything up from scratch and look later. Try to test-run your code early and see if it is behaving as desired.
usually, its a good rule of thumb that you want to call your main function only once.

Remove prompt from console after user enters text with input() [duplicate]

This question already has answers here:
How to stop the input function from inserting a new line?
(9 answers)
Closed 4 years ago.
Is it possible to remove the prompt and the text that the user typed when using input()? I am using cmd on Windows 10 and would prefer a solution that works cross platform, but I don't really mind.
First attempt
Using the code:
user_input = input("Enter some text: ")
print("You just entered " + user_input)
produces:
Enter some text: hello
You just entered hello
but I would like:
Enter some text: hello
and then:
You just entered hello
Second attempt
I've used the getpass module, but that hides what the user is typing because it is designed for passwords. I looked at the code for getpass2 here and found that it uses the getch() function from msvcrt. I tried using a similar method, but it did not work. This code:
import msvcrt
prompt = "Enter some text: "
user_input = ""
print(prompt, end="\r")
current_character = ""
while current_character != "\r":
current_character = msvcrt.getch()
user_input += str(current_character, "utf8")
print(prompt + user_input, end="\r")
print("You entered" + user_input)
produces this output:
Enter some text: h e l l o
and then when I press enter:
nter some text: h e l l o
It also allows the user to use the backspace key to delete the prompt.
Third attempt
I know I can use os.system("cls") to clear everything in the console, but this removes text that was in the console before. For example, this code:
import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)
removes the foo that was printed to the console before the input. If what I'm asking isn't directly possible, is there a workaround that can save the text in the console to a variable, and then after the user input clear the console and reprint the text that was in the console?
This is definitely not the optimal solution;
However, in response to
is there a workaround that can save the text in the console to a
variable
, you could keep appending the required text to a variable, and re-print that each time, as you suggested. Again, I would not recommend this as your actual implementation, but while we wait for someone to come along with the correct approach...
import os
to_print = ""
to_print += "foo" + "\n"
print(to_print)
user_input = input("Enter some text: ")
os.system("cls")
to_print += "You just entered " + user_input + "\n"
print(to_print)

Text-base game inventory list (Python)

so I'm new to python and I am making a text base game. I created an inventory list and in case the player picks up an item more than once, the second time it should be able to give a message saying that they already have this item. I got it to work to an extent where the item doesn't go over the value more than one, but it does not print the message. Please help!!
elif decision == "use H on comb":
global inventory
if inventory.count("comb")>1:
print ("You already got this item.")
print ("")
print ("Inventory: " + str(inventory))
if inventory.count("comb")<1:
print ("(pick up comb)")
print ("You went over to the table and picked up the comb,")
print ("it's been added to your inventory.")
add_to_inventory("comb")
print("")
print ("Inventory: " + str(inventory))
game()
just use the in operator to test for membership
if "comb" in inventory:
print("I have found the comb already...")
else:
print("Nope not here")
but as to why your code was failing was that
inventory.count('comb') == 1
# which fails inventory.count('comb') > 1 test
# but also fails inventory.count('comb') < 1 test so its not re added
you could have easily solved this yourself by printing the value of inventory.count('comb') , which is a useful method for debugging your program for beginners... basically when something doesnt work correctly, try printing it, chances are the variable is not what you think it is...
maybe a little more structuring can be done and avoid using global inventory .jsut a basic idea below:
def game():
inventory = []
# simulate picking up items( replace this loop with your custom logic )
while True:
item = raw_input('pick up something')
if item in inventory: # use in operator to check membership
print ("you already have got this")
print (" ".join(inventory))
else:
print ("pick up the item")
print ("its been added to inventory")
inventory.append(item)
print (" ".join(inventory))

Why if-then statement isn't working?

This is the code that I made when I tried making an if-then statement but, it always defaults to else. Also i just started trying to code from online tutorials today.
print('yes or no?')
if sys.stdin.readline() == 'yes' :
print('Yay')
else :
print('Aww')
This is what happens:
Console:yes or no?
Me:yes
Console:Aww
I've been looking stuff up for half an hour and can't figure out how to fix this please help
sys.stdin.readline() reads a line which ends with '\n' (when you hit "enter").
So you need to remove this '\n' from the captured input using strip().
print('yes or no?')
if sys.stdin.readline().strip() == 'yes' :
print('Yay')
else :
print('Aww')
I tried to explain and solve your specific problem but you could of course use raw_input() or input() (PY3) as mentioned in the other answer.
In python, getting the input of a user's string can be done via input() (or in python 2.7, use raw_input()).
If you include the code:
user_input = raw_input("yes or no?")
This will first print the string "yes or no?", then wait for user input (through stdin), then save it as a string named user_input.
So, you change your code to be:
user_input = raw_input("yes or no?")
if user_input == "yes":
print("Yay")
else:
print("Aww")
this should have the desired effect.
Ok I used user_input and input instead of sys.stdin.readline() on strings and i used it in a basic calculator here it is :
import random
import sys
import os
user_input = input("Would you like to add or subtract?")
if user_input == 'add' :
print('What would you like to add?')
plus1 = float(sys.stdin.readline())
print('Ok so %.1f plus what?' % (float(plus1)))
plus2 = float(sys.stdin.readline())
print('%.1f plus %.1f equals %.1f' % (float(plus1),float(plus2), float(plus1+plus2)))
elif user_input == 'subtract' :
print('What would you like to subtract?')
minus1 = float(sys.stdin.readline())
print('Ok so %.1f minus what?' % (float(minus1)))
minus2 = float(sys.stdin.readline())
print('%.1f minus %.1f equals %.1f' % (float(minus1), float(minus2), float(minus1 - minus2)))
else :
print('That is not one of the above options')
Thanks alot guys!

Importing function in python

I am trying to create menu where user can choose which part of the program he/she wants to run. When I am importing function computer automatically runs it rather to wait for user input. What shall I do to run function only when called? My code:
import hangman
menu = raw_input("""Welcome to Menu, please choose from the following options:
1. Hangman game
2.
3.
4. Exit
""")
if menu == 1:
hangman()
elif menu == 2:
"Something"
elif menu == 3:
"Something"
elif menu == 4:
print "Goodbye"
else:
print "Sorry, invalid input"
The code for hangman.py looks like that:
import random
words = ["monitor", "mouse", "cpu", "keyboard", "printer",]
attempts = [] # Stores user input
randomWord = random.choice(words) # Computer randomly chooses the word
noChar = len(randomWord) # Reads number of characters in the word
print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."
def game():
guess = raw_input ("Please choose letter")
attempts.append(guess) # Adds user input to the list
print (attempts)
if guess in randomWord:
print "You have guessed the letter"
else:
print "Please try again"
while True:
game()
chance = raw_input ("Have a guess")
if chance == randomWord:
print "Congratulations, you have won!"
break
Without seeing hangman.py, I would assume that it directly contains the code for running the hangman game, not wrapped in a function. If that's the case, you created a module, no function (yet).
Wrap that code in
def run_hangman():
# Your existing code, indented by 4 spaces
# ...
import it like this:
from hangman import run_hangman
and finally call the function like this:
run_hangman()
So here is the start menu:
import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
hangman.main()
elif option == '2':
hangman.run_hangman('SKIP')
elif option == '3':
handman.run_hangman('Default User')
Inside your hangman code you want to have it modulated. You should have somthing like this:
def main():
stuff = raw_input('Starting new game. Please enter stuff to do things')
run_hangman(stuff)
def run_hangman(options):
if options == 'SKIP':
important_values = 5
vales_set_by_user = 'Player 1'
else:
values_set_by_user = options
rest_of_code()

Categories

Resources