ok so i was coding the "hangman" game on python and I basically want to know how to tell what position in the word the letter is in, and then ask the question what letter do I choose again. Instead it keeps spamming the position of the letter that it is in the word. Any help?
while True:
for i in range(0, len(word)):
if word[i] == guess and i > 2:
print("Your letter is " + str(i + 1) + "th" + "!")
elif word[i] == guess and i == 2:
print("Your letter is " + str(i + 1) + "rd" + "!")
elif word[i] == guess and i == 1:
print("Your letter is " + str(i + 1) + "nd" + "!")
elif word[i] == guess and i == 0:
print("Your letter is the " + str(i + 1) + "st" + "!")
guess = (str(input("Guess one letter!: ")))
I don't really know what youre base programm was, your code gives out lots of indent problems when I copy-pasted it. I only moved the "guess" input to the begin and fixed the indentation. I think this is what you want (I added an example).
word = ["w","o","r","d"]
while True:
guess = (str(input("Guess one letter!: ")))
for i in range(0, len(word)):
if word[i] == guess and i > 2:
print("Your letter is " + str(i + 1) + "th" + "!")
elif word[i] == guess and i == 2:
print("Your letter is " + str(i + 1) + "rd" + "!")
elif word[i] == guess and i == 1:
print("Your letter is " + str(i + 1) + "nd" + "!")
elif word[i] == guess and i == 0:
print("Your letter is the " + str(i + 1) + "st" + "!")
Related
I am making HangMan game in Python. It is almost ready but when I use print(chr(27) + "[2J") to clear the console every time while loop runs, it clears but then my guess = input("Guess a letter") is not working. And when I comment it out it works perfectly again. I don't understand what the problem is. I searched to find an answer to my problem, but I couldn't. And I would appreciate if somebody explained how this print(chr(27) + "[2J") works. Below is my code:
#columns 0 1 2 3 4 5 6 7 8 9 10 11
gallowList = [ #rows
[" "," "," "," "," "," "," "," "," ","|"," "," \n"], #0
[" "," "," "," "," "," "," "," "," ","|"," "," \n"], #1
[" "," "," "," "," "," "," "," "," ","|"," "," \n"], #2
[" "," "," "," "," "," "," "," "," ","|"," "," \n"], #3
[" "," "," "," "," "," "," "," "," ","|"," "," \n"], #4
]
def gallow(listVar):
print( " _____ " + "\n" +
" | | " )
for row in listVar:
for col in row:
print(col, end = "")
print( " ________|_ " + "\n" +
"| |" )
word = input("Think of a word: ")
while word.isspace() or len(word) == 0:
word = input("Think of a valid word: ")
print(chr(27) + "[2J") # here I should clear the screen after the player
# neters a word
rightGuesses = []
wrongGuesses = []
for letter in word:
if letter != " ":
rightGuesses.append("_")
else:
rightGuesses.append(" ")
while True:
gallow(gallowList)
print("Word you are guessing:")
for letter in rightGuesses:
if letter == " ":
print(letter, end = "")
else:
print(letter +".", end = "")
print("\nWrong guesses:", wrongGuesses)
if list(word) == rightGuesses:
print("Guessing Player has won!")
break
elif len(wrongGuesses) == 9:
print("Hanging player has won!")
break
guess = input("Geuss a letter: ")
while guess.isspace() or len(guess) != 1:
guess = input("Geuss a valid letter: ")
numOccurInWord = word.count(guess) # 2
numOccurInRightGuesses = rightGuesses.count(guess) #0
# hello 0 2
if numOccurInRightGuesses < numOccurInWord:
for index in range(len(word)): # hello
if word[index] == guess: # l == l
if rightGuesses[index] != guess:
rightGuesses[index] = guess
break
else:
wrongGuesses.append(guess)
if len(wrongGuesses) == 1:
gallowList[0][3] = "O"
elif len(wrongGuesses) == 2:
gallowList[1][2] = "/"
elif len(wrongGuesses) == 3:
gallowList[1][3] = "|"
elif len(wrongGuesses) == 4:
gallowList[1][4] = "\\"
elif len(wrongGuesses) == 5:
gallowList[2][3] = "O"
elif len(wrongGuesses) == 6:
gallowList[3][2] = "/"
elif len(wrongGuesses) == 7:
gallowList[3][4] = "\\"
elif len(wrongGuesses) == 8:
gallowList[4][1] = "/"
elif len(wrongGuesses) == 9:
gallowList[4][5] = "\\"
# here every time while loop runs, I want to clear the screen and redraw
# everything
print(chr(27) + "[2J")
I am trying to recreate the card game "War" in python and cant figure out how to loop the code under the comment until every value in the list is gone. So basically the code generates a shuffled deck of cards and pops the cards from the list. I want to have the code repeat until all the cards have been popped from the deck and I have no idea how to do that.
import random
def shuffled_deck():
deck = list(range(2, 15)) *4
random.shuffle(deck)
return deck
userdeck = shuffled_deck()
print("welcome to War!")
user1 = input("Player-1 name: ")
user2 = input("Player-2 name: ")
u1points = 0
u2points = 0
drawturns = 0
# - I want to loop the segment of code under this comment
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
else:
print("It's a draw, try again.")
while u1card == u2card:
drawturns +=1
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
u1points + drawturns
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
u1points + drawturns
else:
print("It's a draw, try again.")
if u1card == u2card == False:
drawturns = 0
break
You can do:
while len(userdeck)>0:
or, you can write smartly as:
while userdeck:
This is because an empty list is considered as False, whereas a non empty list is considered as True. So, when userdeck is empty, while loop will assume it to be False case, so the loop will stop. This same concept can also be applied for if statements.
My input in my if statement is not working. I am using Python3 and the problem is at the first if statement in the defined function.
import random
random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []
def ex():
proceed = input("Proceed?: ")
if proceed.lower == "yes":
ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
if int(ans) == correct:
print("Correct!")
list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
print(ex())
else:
print("Incorrect!")
list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
elif proceed.lower == "mfm":
print(list_of_correct)
print(list_of_wrong)
print(ex())
You compare a function proceed.lower against a string 'yes' - they are never the same.
You need to call the function:
if proceed.lower() == "yes":
to convert your input to lower case for your comparison.
print("".lower) # <built-in method lower of str object at 0x7fc134277508>
Fixed code
import random
random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []
def ex():
proceed = input("Proceed?: ")
if proceed.lower() == "yes":
ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
if int(ans) == correct:
print("Correct!")
list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
print(ex())
else:
print("Incorrect!")
list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
elif proceed.lower() == "mfm":
print(list_of_correct)
print(list_of_wrong)
print(ex())
I'm making a guessing game and i need to know how to stop it from putting my answers in lexicographical order as that makes a bug in my game.
I've tried instead of having elif Guess < str(value): making it elif Guess < int(value): but i get the error message "'<' not supported between instances of 'str' and 'int'" and i'm having no luck with anything else
Here is the code im working with
from random import *
from random import randint
import os
numbers = []
Guesses = []
dif = []
os.system('CLS')
print("I want you to guess my number")
print("\n \n \n \nIf you give up type 'give up' word for word")
f = open("Data.txt", "a")
print("Say 'yes' If You're Ready")
YN = input()
if YN == "yes":
os.system('cls')
print("Select a difficulty")
print('impossible 1 - 10000')
print('annoying 1 - 1000')
print('hard 1 - 500')
print('medium 1 - 200')
print('easy 1 - 99')
print('beginner 1 - 10')
diff = input()
if diff == 'easy':
os.system('CLS')
value = randint(1, 99)
numbers.append(value)
dif.append(diff)
elif diff == 'beginner':
os.system('CLS')
value = randint(1, 10)
numbers.append(value)
dif.append(diff)
elif diff == 'medium':
os.system('CLS')
value = randint(1, 199)
numbers.append(value)
dif.append(diff)
elif diff == 'hard':
os.system('CLS')
value = randint(1, 499)
numbers.append(value)
dif.append(diff)
elif diff == 'annoying':
os.system('CLS')
value = randint(1, 1000)
numbers.append(value)
dif.append(diff)
elif diff == 'impossible':
os.system('CLS')
value = randint(1, 10000)
numbers.append(value)
dif.append(diff)
os.system('cls')
while True:
Guess = input()
if Guess == "give up":
print("The Number Was " + str(numbers))
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("[USER GAVE UP] \n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
break
elif Guess < str(value):
print("Higher")
Guesses.append(Guess + " - Higher")
elif Guess > str(value):
print("Lower")
Guesses.append(Guess + " - Lower")
elif Guess == str(value):
os.system('CLS')
length = len(Guesses)
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("Number Of Guesses [" + str(length) + "]\n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
print("That Was Correct!")
for x in Guesses:
print(x)
break
input()
You may try to convert Guess from str to int, and compare in integer.
elif int(Guess) < value:
As maruchen notes you should be casting the Guess variable and not the value variable.
However, that alone is still going to leave you with problems. The user isn't forced to enter an integer and indeed string answers such as "give up" are expected. If you try an cast a string to an integer and the string contains non-numerics, then you will be faced with a ValueError. So best is to define a function like this:
def guess_less_than_value(guess, value):
try:
return int(guess) < int(value)
except ValueError:
return False
Then you can but in the body of your code:
if guess_less_than_value(Guess, value):
....
And likewise with greater than.
I've made a few programs in Python now, but I'm still pretty new. I've updated to 3.3, and most of my programs are broken. I've replaced all of the raw_inputs now with input, but this still isn't working, and I get no errors.
Could one of you fine programmers help?
a = 1
while a < 10:
StartQ = input("Would you like to Start the program, or Exit it?\n")
if StartQ == "Exit":
break
elif StartQ == "Start":
AMSoD = input("Would you like to Add, Multiply, Subtract or Divide?\nPlease enter A, M, S or D.\n")
if AMSoD == "A":
Add1 = input("Add this: ")
Add2 = input("By this: ")
AddAnswer = int(Add1) + int(Add2)
AAnswer = Add1 + " " + "+" + " " + Add2 + " " + "=",AddAnswer
print(AAnswer)
print("The answer is:"),AddAnswer
elif AMSoD == "M":
Mul1 = input("Multiply this: ")
Mul2 = input("By this: ")
MulAnswer = int(Mul1) * int(Mul2)
MAnswer = Mul1 + " " + "*" + " " + Mul2 + " " + "=",MulAnswer
print(MAnswer)
print("The answer is:"), (MulAnswer)
elif AMSoD == "S":
Sub1 = input("Subtract this: ")
Sub2 = input("From this: ")
SubAnswer = int(Sub2) - int(Sub1)
SAnswer = Sub2 + " " + "-" + " " + Sub1 + " " + "=",SubAnswer
print(SAnswer)
print("The answer is:"), (SubAnswer)
elif AMSoD == "D":
Div1 = input("Divide this: ")
Div2 = input("By this: ")
DivAnswer = int(Div1) / int(Div2)
DAnswer = Div1 + " " + "/" + " " + Div2 + " " + "=",DivAnswer
print(DAnswer)
print("The answer is:"), (DivAnswer)
DivQoR = input("Would you like to Quit or restart?\nAnswer Quit or Restart.\n")
if DivQoR == "Restart":
a = 1
elif DivQoR == "Quit":
DivQoRAyS = input("Are you sure you want to quit? Answer Yes or No.\n")
if DivQoRAyS == "Yes":
break
elif DivQoRAyS == "No":
a = 1
Put all items you want to print in the parenthesis of the print() function call:
print("The answer is:", AddAnswer)
and
print("The answer is:", MulAnswer)
etc.
Where you build your strings, it'd be easier to do so in the print() function. Instead of
AAnswer = Add1 + " " + "+" + " " + Add2 + " " + "=",AddAnswer
print(AAnswer)
(where you forgot to replace the last comma with +), do this:
print(Add1, '+', Add2, '=', AddAnswer)
and so on for the other options.