python hangman code for a beginner - python-2.7

I just started to learn python about a week ago. I tried to create a simple hangman game today. All of my code in this works so far, but there is one thing that I cannot think of how to implement. I want the code to print 'you win' when it the player correctly types 'python', letter by letter. But I cant seem to end it after they get it right. It will end if they type 'python' in one attempt, opposed to letter form. My attempt to do it is on the line with the .join. I can't seem to figure it out though. Any help or advice for a new programmer would be greatly appreciated.
guesses = []
count = 1
ans = 'python'
word = ''
while count < 10:
guess = raw_input('guess a letter: ')
guesses.append(guess)
if ''.join(word) == ans:
print 'you win'
break
elif len(guess) > 1 and ans == guess:
print ans
print 'you win'
break
else:
for char in ans:
if char in guesses:
word.append(char)
print char,
else:
print '_',
count += 1
else:
print '\nyou lose'

First, I want to start off by saying, unless you are dealing with legacy code or some library which you need that only works in 2.7, do not use python 2.7, instead use python 3.x (currently on 3.6). This is because soon 2.7 will be deprecated, and 3.6 + has a lot more features and a lot of QOL improvements to the syntax and language you will appreciate (and has support for functionality that 2.7 just doesn't have now).
With that said, I'll make the translation to 3.6 for you. it barely makes a difference.
guesses = []
count = 1
ans = 'python'
word = ''
while count < 10:
guess = input('guess a letter: ')
guesses.append(guess)
if ''.join(word) == ans:
print('you win')
break
elif len(guess) > 1 and ans == guess:
print(ans)
print('you win')
break
else:
for char in ans:
if char in guesses:
word.append(char)
print(char)
else:
print('_')
count += 1
else:
print('\nyou lose')
The only two changes here are that print now requires parenthesis, so every print 'stuff' is now print('stuff'), and raw_input is now input('input prompt'). Other than that, I'm suprised you were able to get away with word.append(char). You cannot use append() on a python str in either 2.7 or 3.x. I think you were trying to use it as an array, as that is the only reason you would use ''.join(word). To fix this I would do word = [] instead of word = ''. now your ''.join(word) should work properly.
I would advise you to take the next step and try to implement the following things to your program: If the user doesn't enter a single character, make it so that the characters are not added to the guesses list. Try making this a main.py file if you haven't already. Make parts of the program into functions. Add a new game command. Add an actual hangman in chars print out every time. Add file io to read guess words (ie instead of just python, you could add a lot of words inside of a file to chose).

Related

NameError: name 'Right' is not defined

I'm trying to execute the following code in Spyder 3.3.1 using Python 2.7.15. I'm a beginner.
text = str(input("You are lost in forest..."))
while text == "Right":
text = str(input("You are lost in forest..."))
print "You got out of the forest!!!"
When I run the code with integer value it works. For example the following piece of code:
text = input("You are lost in forest...")
while text == 1:
text = input("You are lost in forest...")
print "You got out of the forest!!!"
How can I make the input() work with a string value? Thank you for your help.
Use raw_input() instead of input():
value = raw_input("You are lost in forest...") # String input
value = int(raw_input("You are lost in forest...")) # Integer input
...
In python 2, raw_input() takes exactly what the user typed and passes it back as a string. input() tries to understand the data entered by the user.Hence expects a syntactically correct python statement.That's why you got an error when you enter Right. So you can enter "Right" as input to fix this error.
But it is better to use raw_input() instead of input().

Python 2.7 - Raw_input and If and else

raw_input('What are you doing? ')
a = 'nothing'
if type(a):
print 'That seems boring'
else:
print 'Nice'
The meaning of this code, is that if a person answers the raw_input with 'nothing'. It should print that seems boring. And if a person writes something else it should print ok.
I am new to programming so please help me :)
If I understood your question correctly, what you are looking for is:
a = raw_input("What are you doing?")
Notice that the answer to the prompt is saved in the variable 'a'.
if a == 'nothing':
print 'That seems boring'
else:
print 'Nice'
Pay attention to the indentation. Also, we use '==' for comparison and '=' for assigning values to a variable.
I suggest you learn basics of python from https://www.codecademy.com/
I always like to make variables that show what they contain.
My version would look like this:
print "What are you doing?"
reply = raw_input()
if reply == "nothing":
print "That seems boring"
else:
print "Nice"
You can also do it like this, it will take input during run time in more oriented way
#!/usr/bin/env python
def user_input():
print "What are you doing?"
# takes user input
a = raw_input()
# if user enter "Nothing" or "nothing"
if (a == "Nothing") or (a == "nothing"):
print "boring"
# if he enters anything else
else:
print "nice"
if __name__ == '__main__':
user_input()

Can someone tell me whats wrong with this python code?

Note: I'm using Python 2.7
I'm not very experienced at Python, but I decided to make a small simple program. Here is the code:
import random
while True:
randomNumber = random.randrange(1, 3)
print randomNumber
guessedNumber = raw_input("Choose a number between 1 and 3 ")
if randomNumber == guessedNumber:
print 'Yay! You got it right!'
else:
print 'You got it wrong :( The number was:',randomNumber
#The first print is just for testing.
But when I try to run it I get this:
IDLE after i used the program a few times
Can someone tell me what i need to change or what is wrong with the code?
raw_input returns a string to guessedNumber, and your program compares a string (guessedNumber) to an integer (randomNumber), so if randomNumber == guessedNumber never evaluates to True.
The solution is to convert guessedNumber to an int and then compare the two values.

How to create multiple loops in python

I'm trying to create a basic maths program which will randomly generate a numerical question and then allows 3 attempts to complete it before it moves onto the next question however cant figure out how to make it do both together.
My code currently looks like this
print "What is your name?"
score = 0
Attempt = 0
loop = True
Name = raw_input()
import random
for i in range (1,6):
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
print "What is", question_1_part_1, "+", question_1_part_2, "?"
while Attempt <3: # inputing this while loop here means it will retry the same question.
Guess = raw_input()
Guess = int(Guess)
answer = question_1_part_1 + question_1_part_2
if Guess == answer:
print "Well done"
score = score + 1
else: print "try again"
Attempt = Attempt + 1
if Attempt == 3: print "You failed"
print Name, "your score is", score
A simple break statement will take you out of the loop when the answer is correct.
if Guess == answer:
print "Well done"
score += 1
break
else: print "try again"
Note the change to your assignment; this is considered a cleaner increment.
To answer your comment ... you don't use this when the person gets the question wrong. Your program logic freezes out the user after three wrong guesses total, on all questions. If you want them to have up to three guesses on every problem, then you have to reset the Attempt counter for every question. Pull that line into the outer loop:
for i in range (1,6):
Attempt = 0
loop = True
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
In the future, I strongly recommend that you program incrementally: get a few lines working before you add more. Insert tracing print statements to check that the values and program flow are correct. Don't remove them until that part of the code is solid -- and even then only comment them out until the entire program is working. Some of your problems stem from trying to write more than you can comfortably hold in your mind at once -- which is common at most levels of programming. :-)
Add another argument to your while loop.
while Attempt <3 and Guess != ... :
rest of loop code
Then you are exiting your loop when they get the correct answer. Or you could break from the statement when they get the answer right.

Trying to get my python loop to run for a specific amount of iterstions entered by the user

I am fairly new to python and was wondering how to make this loop run for a the number of iterations that is entered by the user, however it is an infinite loop at the moment:
def randMod():
import random
heads = 0
tails = 0
tries = raw_input('Enter a number:')
while True:
runs = 0
if tries == runs:
break
else:
runs + 1
coinFlip = random.randrange(0,1+1)
if coinFlip == 0:
print "Tails"
tails + 1
elif coinFlip == 1:
print "Heads"
heads + 1
print heads
print tails
randMod()
I am trying to make it so it will simulate a coin flip for how many times the user enters then tallies it at the end. Only problem is I am fairly new to python so I don't know if I got this right or not.
The problem I see here is that you are using raw_input() to read the user's input. That method stores the input as a string. You must convert the information contained in tries to a number in order for this to work. As it is comparing tries == runs and a string will never be equal to a int, it is stuck forever.
You can use the conversion like this:
Explained here