GUESSING GAME
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
get_user_guess()
if get_user_guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)
Here is the code. I made a running version in python 2, but translating it to python 3 has been a headache. I have defined that get_user_guess, where guess = an int. But further down in the roll_dice section, after I have called on the previous function and its answer I'm getting error messages.
That's not how you access the return value of a function. You should assign the return value to a new name, then use that in the following comparisons.
guess = get_user_guess()
if guess > 13:
print("invalid guess")
else:
...
if guess == total_roll:
print("Congratulations")
else:
print("sorry")
So, this seems like a small logic error and a syntax error as well. First the syntax error. You're not really initializing or calling the function in the comparison by doing:
if get_user_guess > 12
rather than doing:
if get_user_guess() > 12
So there is nothing for the ">" operator to compare against.
Second, seeing as you're trying to reuse the variable for the next comparison.You will need to store it as well otherwise it would prompt the user again for a new value again. Note the changes in lines 13,14 and 28 will fix it:
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
guess = get_user_guess()
if guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)
Related
I wrote a program, which keeps rolling a "num" sided die until it reaches the maximal roll which is the number you write as "num". However, if it happens that the first roll is the number, the program does not say "You landed on your number!" as it should. Here is the code
import random
num = () #put the number here#
i = random.randint(1,num)
while i != num:
print(i)
print("Not lucky")
i = random.randint(1,num)
if i == num:
print("You landed on your number!")
Again, if the roll equals the number choice, I get "Process finished with exit code 0", not the text I want. How do I fix this?
Put the final print, outside of the while loop, as you're always land there
num = 5 # put the number here#
i = random.randint(1, num)
while i != num:
print("Not lucky,", i, "isn't the one")
i = random.randint(1, num)
print("You landed on your number!")
what if something like that?
import random
num = int(input('Put your number: '))
i = random.randint(1, num)
while True:
if i == num:
print("You landed on your number!")
print(num)
break
else:
print(i)
print("Not lucky")
i = random.randint(1, num)
You can do it like this:
import random
num = (2) #put the number here#
i = random.randint(1,num)
while i != num:
i = random.randint(1,num)
if i != num:
print(i, "Not lucky")
print(i, "You landed on your number!")
import random
num = #put the number here#
while True:
i = random.randint(1,num)
print(i)
if i == num:
print("You landed on your number!")
break
print("Not lucky")
I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.
I would like to generate a number between 1 and 6 and have the user guess it. The check function, as in if input == variable: is not working.
global count
count = 0
def guess():
a = random.randint(1,6)
print (a)
ffs =input ("whats my nr?")
if ffs == (a):
print ("Correct")
sys.exit()
else:
global count
print ("guess again")
count +=1
print ("you have attempts remaining")
def mainz():
while count < 6:
guess()
mainz()
First of all your mainz() function and your mainz() call are in the guess() function but I guess that it's just a formatting error. The real error resides in the fact that input returns a string which you are trying to compare to an int. I would recommend simply doing this:
ffs = int(input("What's my nr? ") )
global count
count = 0
def guess():
a = random.randint(1,6)
print (a)
ffs =input ("whats my nr?")
if ffs == str(a):
print ("Correct")
sys.exit()
else:
global count
print ("guess again")
count +=1
print ("you have attempts remaining")
def mainz():
while count < 6:
guess()
mainz()
Needed str(a)
I am working on learning python and decided to write a small battle engine to use a few of the different items I have learned to make something a bit more complicated. The problem I am having is that I set a selection that the user makes that should cause one of either two parts to load, but instead it skips to my loop instead of performing the selection. Here is what I have so far:
import time
import random
import sys
player_health = 100
enemy_health = random.randint(50, 110)
def monster_damage():
mon_dmg = random.randint(5,25)
enemy_health - mon_dmg
print ('You hit the beast for ' + str(mon_dmg) + ' damage! Which brings its health to ' + str(enemy_health))
player_dmg()
def player_dmg():
pla_dmg = random.randint(5,15)
player_health - pla_dmg
print ('The beast strikes out for ' + str(pla_dmg) + ' damage to you. This leaves you with ' + str(player_health))
def run_away():
run_chance = random.randint(1,10)
if run_chance > 5:
print ('You escape the beast!')
time.sleep(10)
sys.exit
else:
print ('You try to run and fail!')
player_dmg()
def player_turn():
print ('Your Turn:')
print ('Your Health: ' + str(player_health) + ' Monsters Health: ' + str(enemy_health))
print ('What is your next action?')
print ('Please Select 1 to attack or 2 to run.')
action = input()
if action == 1:
monster_damage()
elif action == 2:
run_away()
while player_health > 0 and enemy_health > 0:
player_turn()
if player_health <= 0:
print ('The beast has vanquished you!')
time.sleep(10)
sys.exit
elif enemy_health <= 0:
print ('You have vanquished the beast and saved our Chimichongas')
time.sleep(10)
sys.exit
The function input returns a str not an int
action = input()
So this comparison will always return False
if action == 1:
For example
>>> '1' == 1
False
You can convert their input to an int as follows
action = int(input())
#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)