how to convert str to int - python

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.

Related

Simple coinflip terminal game won't update variable

I am trying to code a simple coinflip game with a gambling function. My issue is, whenever it runs, it doesn't update the balance variable. Any suggestions?
import random
balance = 10
win = "Congrats! You have won "
lose = "That's too bad, you lost this time! You now have "
start_game = False
while True:
choice = input("Please use one of these commands 'flip', 'balance', or 'end game'. ")
if choice == "flip":
start_game = True
break
elif choice == "balance":
print(balance)
elif choice == "end game":
break
else:
print("Please use one of the listed commands!")
if start_game == True:
while True:
result = random.randint(1,2)
if result == 1:
result = True
elif result == 2:
result = False
gamble_amount = input("How much would you like to flip? You have " + str(balance) + " coins. ")
if str(gamble_amount) == "balance":
print(balance)
elif int(gamble_amount) <= int(balance) and result == True:
int(gamble_amount) * 2
int(balance) + int(gamble_amount)
print(win + str(gamble_amount) + "!" + " You now have " + str(balance) + "!")
elif int(gamble_amount) <= int(balance) and result == False:
int(balance) - int(gamble_amount)
print(lose + str(balance) + " coins!")

Python guessing game code keeps crashing after 1 guess. How would i fix this?

My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.

How to add a won or loss variable

Hey I'm trying to add a variable for "won" or "loss", I already have a variable for players name and guesses allowed.
Any help would be kind thanks. This is the code I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?: ")
number_of_guesses = 0
print("Okay! "+ player_name+ " I am guessing a number between 1 and 100:")
max_guesses = random.randint(1, 6)
print("You have " + str(max_guesses) + " guesses. ")
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
f = open("statistics.txt", "a")
f.write =(player_name) (max_guesses)
f.close()
f = open("statistics.txt", "r")
print(f.read())
Maybe add befor you loop the variable won = False
And in the loop
if guess == number:
won = True
break
After the loop if the player don't find the nulber won will be false.
In the oter case it will be True
For saving
f.write( str(won) ) # convert to string

Dice game not working with multiple players

I am trying to create a game where you choose how many players there will be, name those players, and then one player is chosen at random.
From there, that chosen player would pick a number in between 1 and 10 that they DON'T want to land on.
Then, the dice rolls and if they land on that number, everyone else gets to pick a dare for him/her. If it doesn't, the game just randomly picks another player and the process begins again.
The problem is though, the program doesn't get past the part where it asks you which number you don't want to land on. This is weird, as it works fine with one person.
Here is the full code, you are looking for line 23:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else:
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
Here is a fast review of the algorithm, the problem was that the break you used while checking if the darenumber was between the desired range, causing to loop back again and never getting out of there.
Also, it's recommended that you check your control structure because it´s what made the problem.
Lastly, I strongly recommend an exit feature of your game because in some point in has to end. Hope it helps:
from random import randint
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
playercount = 0
while playercount < 1:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
print("Press 0 while it's your turn to finish the game")
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
darenum = -1
while (darenum > 10 or darenum < 0):
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
except ValueError:
print("Please enter a number.")
if darenum == 0:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
print("Game Over")
Your original code, with errors sinalization (read the code's comments):
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else: #there is no if for this else
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break #this break would break the while True above
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
#there should be a break in here, otherwise the function would be stuck in the second while True
The fixed code, changing what I mentioned in the comments above:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
break

Iteration counter Python3x

So I've built a simple calculator in Python where the user inputs two numbers and an operator and the answer is given. They also have the option to run the calculator again. I want to number the answers so each answer reads "Answer 1 equals x", "Answer 2 equals x", etc. depending on how many times the calculator is run. Everytime I try to format the counter to count iterations, it won't work and is stuck just labeling them "Answer 1" over and over. Any help would be greatly appreciated. I'm super new to Python.
answer = "y"
while ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
numones = input ("Give me a number: ")
numtwos = input ("Give me another number: ")
numone = float(numones)
numtwo = float(numtwos)
operation = input ("Give me an operation (+,-,*,/): ")
counter = 0
for y in answer:
counter += 1
if (operation == "+"):
calc = numone + numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "-"):
calc = numone - numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "*"):
calc = numone * numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "/"):
calc = numone / numtwo
if (numtwo != 0):
print ("Answer " + str(counter) + " is " + str(calc))
else:
print ("You can't divide by zero.")
else:
print ("Operator not recognized.")
answer = input ("Do you want to keep going? ")
if ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
print ()
else:
print ("Goodbye.")
break
Remove assigning counter = 0 in your while loop. And move this declaration above your while loop.
also lines:
for y in answer:
counter += 1
are really confusing and sure are wrong, because if you got 'yes' as an answer you would get +3 increase. Just increment(counter += 1) counter without any for-loop.

Categories

Resources