Display Variable value in Python using print Statement? - python

I have created a Python program that guesses the number programmer thinks in mind. Everything is working file but i don't know how to use guess in print statement in a way that print statement display number as well. I tried adding word "guess" but it is not working. I am C programmer and working with Python for the first time, so i am unable to figure it out.
hi = 100
lo = 0
guessed = False
print ("Please think of a number between 0 and 100!")
while not guessed:
guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too"
"low. Enter 'c' to indicate I guessed correctly: ")
if user_inp == 'c':
guessed = True
elif user_inp == 'h':
hi = guess
elif user_inp == 'l':
lo = guess
else:
print ("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)

Just convert it to string.
print ("Game over. Your secret number was: " + str(guess))
You could also use string formatting.
print("Game over. Your secret number was {}".format(guess))
Or, since you come from a C background, old style string formatting.
print("Game over. Your secret number was %d." % guess)

Try this in your print statement and let me know if it works.
str(guess)

Python has very nice string formatting, which comes in handy when you need to insert multiple variables:
message = "Game over after {n} guesses. Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)

Related

Making a game like Mastermind in Python

I'm trying to make a game like Mastermind in Python but by using numbers [1-9] instead of colours. The game needs to be a little complex however and that is where I am struggling. I want to be able to randomly generate a password of 5 digits between [0-9] and make the user have 10 tries to get it right. If they guess a number correctly, I want to tell them where it is in their list and ask them to keep going as well. So far, I have this:
import random
random_password = [random.randint(0,9) for i in range (5)]
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess != random_password :
print ("Guess again ")
#Here I am trying to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
elif guess
else print ("Sorry, you lose :( ")
if guess == random_password :
print ("Congrats, you win! ")
Any help is appreciated overflow bros, I am lost. I know that I need it to access items from a list. Would using a function like append work?
EDIT: This is my new code. Sorta works however my output is now showing it is wrong even when I guess the number correctly. It wants me to input with '' and , to separate the list but I shouldn't have to have the user do that to make the game function.
import random
random_password = [str (random.randint(0,9)) for i in range (5)]
for counter in range (10):
guess = input(str ("Crack the Mastermind code ") )
if guess != random_password :
print ("Guess again ")
#Here I am tryin to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
for i in random_password:
if(i in guess):
print (i)
if guess == random_password :
print ("Congrats, you win! ")
else :
print ("Sorry, you lose :( the correct answer was.... ")
print (random_password)
One way to do it quickly is to create a small function that will check if any of your string answer (from input) match with any characters of the password list
Also I change the order of your condition statement to make it more clear and efficient.
Finally I change your random_password from LIST to STRING because then you will be able to do guess == random_password properly.
Hope it helps!
PS:
IF you use Python2.X you should change input to raw_input (to get string value) else if you use Python3.X just keep it this way
import random
def any_digits(guess,password):
for character in guess:
if character in password:
return True
return False
random_password = ''.join([str(elem) for elem in [random.randint(0,9) for i in range (5)]])
print(random_password)
print(type(random_password))
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess == random_password :
print ("Congrats you win! ")
elif any_digits(guess, random_password):
print ("Some numbers are correct! ")
else:
print ("Guess again ")
print("No more chances, you lose...")
print("The code was ", random_password)

Why isn't my program noticing the equivalency between letters?

I am working on making a simple game of Hangman in Python 2. The code I have so far is the ground work I have for it, but it doesn't seem to be working. If I could have a simple wake-up call as to what about what code I made isn't working I would appreciate it.
Code:
secret_word = 'tracy'
secret_word_list = []
for letter in secret_word:
secret_word_list += letter
print secret_word_list
def get_guess(guess = input("Guess: ")):
while len(guess) != 1:
print "Your guess must be exactly one character!"
guess = input("Guess: ")
while guess.isalpha() == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
while guess.islower == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
else:
return guess
while True:
if str(get_guess) in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
get_guess(guess = input("Guess: "))
Output:
Output of the Code
You've got several problems here, but the big one is that you're not calling functions, so you compare the function itself to the secret.
Code with fixes:
secret_word = 'tracy' # Don't make secret_word_list, there's no point; just use the str itself since you only test len 1 strings against it anyway
print secret_word
def get_guess(guess): # Don't make the default call input, that'll prompt once for an input and store it as the permanent default
while True:
# Test each condition and break loop only if all past; original code would never
# recheck length if new value entered after testing isalpha
if len(guess) != 1:
print "Your guess must be exactly one character!"
elif not guess.islower(): # Add missing call parens on islower; use not, never compare to False; islower implicitly verifies isalpha, so avoid testing isalpha
print "Your guess must be a lowercase letter!"
else:
break # Passed all tests, break loop
# Get new guess if any test failed
guess = raw_input("Guess: ") # Use raw_input on Python 2, never input (which eval's the result of raw_input)
# Removed else (loop always ends by breaking, using else nonsensical but harmless in original code too
return guess
while True:
# Move guess getting to if, because having it in else case never actually checked it
if get_guess(raw_input("Guess: ")) in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
Try it online!
Note: I kept the kinda odd behavior of having get_guess take an argument, but then reprompt for guesses on failure. A saner solution would be to remove the guess argument entirely, and move the guess = raw_input("Guess: ") to the top of the while loop (removing the else block at the end).
get_guess is a function, you need to put () after it to call the function.
You shouldn't put the call to input() as a default argument. The default value is evaluated once, when the function is defined, not every time the function is called. You should assign guess inside the function.
You should test for all the invalid inputs in a single loop.
def get_guess():
while True:
guess = input("Guess:")
if len(guess) != 1:
print "Your guess must be exactly one character!"
continue
if not guess.isalpha() or not guess.islower():
print "Your guess must be a lowercase letter!"
continue
break
return guess
while True:
guess = get_guess()
if guess in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"

Show me the way to calling my function

So I'm learning to code and I started with Python.
I've learned the very basics of programming in python, like what are variables, operators, some functions etc.
I have this code:
def guessGame():
import random
guesses = 0
randomNo = random.randint(0, 100)
print "I think of a number between 0 and 100, you have 10 guesses to get it right!"
while guesses < 10:
guess = input("Take a guess ")
guess = int(guess)
guesses += 1
if guess < randomNo:
print "The number is higher than your guess"
if guess > randomNo:
print "The number is lower than your guess"
if guess == randomNo:
break
if guess == randomNo:
guesses = str(guesses)
print "You got it in %s guesses!" % guesses
if guess != randomNo:
print "You failed to guess!"
guessGame()
when I run the code in cmd it just ends before the function gets "recalled".
cmd output
You called the game only once in your main program -- which consists of the last line only. It runs the game once and quits. There is no second call in your code. Perhaps you want a classic "play again?" loop:
play = True
while play:
guessGame()
play = lower(raw_input("Play again?")[0]) == 'y'
after each game, you ask the player for input. If that input begins with the letter 'y' (upper or lower case), then you continue playing; otherwise, play becomes False and you drop out of the loop.
Is that what you wanted?

How to accumulate within a loop python

I am new to programming and I am having difficulty accumulating within a loop
wrong_guesses=0
formSoFar=''
game_over=False
while (game_over==False and wrong_guesses<max_guesses):
guess1= raw_input("Please enter an operation symbol or digit: ")
if (guess1 in formula):
print "Your guess is correct!"
for i in range (len(formula)):
if (randomFormula[i] == guess1):
formSoFar += formula[i]
else:
formSoFar+= "-"
print "The formula you have guessed so far is: ",formSoFar
Supposed the equation the user is trying to guess is 1+2+3 and their first guess is 2 the formSoFar is --2-- but the second time they guess it should show the first guess as well so if they guess 1 it should be 1-2-- but this code is printing--2--1-2--
please help :(
In each loop, you are appending characters to formSoFar. What you want to do instead is have it start with some value and edit it as you go:
formSoFar = ['-'] * len(formula)
while not game_over and wrong_guesses < max_guesses:
guess = raw_input(...)
if guess in formula:
for i, c in enumerate(formula):
if c == guess:
formSoFar[i] = c
print 'The formula you have guessed so far is:', ''.join(formSoFar)
Also note that you don't need ()s in an if statement. That's a C/C++/Java thing.

Python While Loop woes

I am a brand new programmer, and I have been trying to learn Python (2.7). I found a few exercise online to attempt, and one involves the creation of a simple guessing game.
Try as i might, I cannot figure out what is wrong with my code. The while loop within it executes correctly if the number is guessed correctly the first time. Also, if a lower number is guessed on first try, the correct code block executes - but then all subsequent "guesses" yield the code block for the "higher" number, regardless of the inputs. I have printed out the variables throughout the code to try and see what is going on - but it has not helped. Any insight would be greatly appreciated. Thanks! Here is my code:
from random import randint
answer = randint(1, 100)
print answer
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print "Top of Loop"
print guess
print answer
i = i + 1
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
else:
print "else statement"
print "Congratulations! You got it in %r guesses." % i
print "Time to play a guessing game!"
print "Enter a number between 1 and 100:"
guess = raw_input()
guess = int(guess)
logic(guess, answer, i)
I'm sure it is something obvious, and I apoloogize in advance if I am just being stupid.
You've noticed that raw_input() returns a string (as I have noticed at the bottom of your code). But you forgot to change the input to an integer inside the while loop.
Because it is a string, it will always be greater than a number ("hi" > n), thus that is why "Too high. Try again:" is always being called.
So, just change guess = raw_input() to guess = int(raw_input())
Try this:
guess = int(raw_input())
As raw_input.__doc__ describes, the return type is a string (and you want an int). This means you're comparing an int against a string, which results in the seemingly wrong result you're obtaining. See this answer for more info.
Ok, I found your problem. The problem is in this Code:
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
In the code above you are getting your input as string, but you try to compare it with integer. All you need to do is to convert the input to integer, like this:
guess = raw_input()
guess = int(guess)
This should solve your problem :)
I updated the program. You came out of the while loop because after you get guesss as input inside elif group, you forget to convert that to int, so it throwed back error. Now, corrected but you can also optimise it.
import sys
from random import randint
answer = randint(1, 100)
'''randint(1, 100)'''
print (answer)
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print ("Top of Loop")
print (guess)
print (answer)
i = i + 1
if guess < answer:
print ("Too low. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
elif guess > answer:
print ("Too high. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
else:
print ("else statement")
print ("Congratulations! You got it in %r guesses." % i)
print ("Time to play a guessing game!")
print ("Enter a number between 1 and 100:")
guess = input()
guess = int(guess)
logic(guess, answer, i)

Categories

Resources