Python Heads Or Tails Program assistance - python

I am trying to make a Heads Or Tails program in Python. I am a newbie and I have just got into Python. What I try to achieve is to have the program pick either Heads or Tails without me knowing it (Yes, import random, etc.) and I would like to have a single try when guessing. This is what I have achieved so far, yet it is not very close to what i am looking for. Any thoughts? I have tried implementing the different random arguments I found on a Python website but they don't work (such as randint for integers)... Thanks!
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = "Heads" # For Debugging purposes to check if the program works
notCorrectAnswer = "Tails" # To eliminate the possibility of not being either tails or heads in case of mistaken answer
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"

You should try:
import random
ch = random.choice(["Heads","Tails"])
which will put into the variable ch either "Heads" or "Tails". Try to do something from that.

To make the whole thing continue until exited by user, and including #Baruchel's answer:
import random
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
cont = 1 #To force the game to run for one round without user input
while(cont == 1): #cont is used to take user choice, whether to run it again or not
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = random.choice(["Heads","Tails"])
if ourAnswer == "Heads":
notCorrectAnswer = "Tails"
else:
notCorrectAnswer = "Heads"
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
cont = input("Do you want to continue? Press 1 if yes, press 0 if no.: ") #Take user choice on whether to run it again or not
while (cont != 0 and cont != 1): # If user puts in a different number (neither 1 or 0), make them enter until they put a right choice
cont = input("Please try again. Press 1 if yes, press 0 if no.: ")

Related

How do I stop a while loop if something happens inside a function that should stop the itterations?

Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1

Why cant i sum up all of my values (user values) problem with while?

I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.

Trying to add my first score counter (Python) (Beginner)

This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.

Does somebody know if my beginner (dice game) code correct is and where to start to make a dice game?

Here is the code:
from random import randint
def random_number():
random_num = randint(range(1,7))
for i in random_num:
enter = int(raw_input("Enter a nunber: "))
if random_num == enter:
print "Congratulations, You Win!!!"
elif random_num != enter:
print "That's not the correct answer!"
else:
print "That's not a valid number!"
For some reason I can't test my code (it pops cmd out and that's it). Can somebody help me with that?
For some reason I can't test my code (it pops cmd out and that's it). Can somebody help me with that?
You create a function, random_number, but you never call that function. So, when you run your script, it just defines that function, then, with nothing else it do, it quits.
To fix that, just add a line to the end of the script that calls it:
random_number()
You also have this more general two-in-one question:
Does somebody know if my beginner (dice game) code correct is and where to start to make a dice game?
It's not correct. In fact, there are multiple things wrong with it, and more things that are technically OK but strange. Unfortunately, StackOverflow is not a debugging service. If you have a specific question, you can ask that and get an answer, but not just "make my code work".
As for where to start… well, you've already started in the right place. You're simulating the roll of a (7-sided) die, you're interacting with the user… that's a dice game, right? You just need to debug it now.
replace :
random_num = randint(range(1,7))
to:
random_num = randint(1,7)
and also:
for i in range(1,7):
from random import randint
def random_number():
random_num = randint(1,7)
for i in range(1,7):
enter = int(raw_input("Enter a nunber: "))
if type(enter) == int:
if random_num == enter:
print "Congratulations, You Win!!!"
break
else:print "wrong guess"
else:print "That's not a valid number!"
random_number()
range will give the list of number from start to end-1, if ony end is given, it will take '0' as starting point. randint will give you a random no between specified range
why your cmd pop and go out, you haven't called your function you defined random_number you need to call the function like i did in edited code
If you are on windows, simply use your terminal, cd to the directory and execute the code with "python filename.py" where filename is your python code's file name. This will work if python has been installed as in your system variables. (default when installing)
Else, you should change :
random_num = randint(range(1,7))
to
random_num = randint(1,7)
and also remove
for i in random_num:
your code should work, but the two other conditions are kind of useless.
you should use somthing like
enter.isdigit()
to know if the user entered a number.
plus,
enter < 7 and enter > 0
To make sure that the number the user entered is in the valid range.
You should use a IDE to work, it would be a lot easier!
Edit :
Here, I would have done something like this :
from random import randint
def random_number():
random_num = randint(1,7)
while True:
enter = raw_input("Enter a number: ")
if enter.isdigit():
if int(enter)<7 and int(enter)>0:
if random_num == int(enter):
print "Congratulations, You Win!!!"
break
elif random_num != int(enter):
print "That's not the correct answer!"
break
else:
print "That's not a valid number!"
else:
print "That's not even a number!"
random_number()

trying to loop to the beginning of a function(sort of) in python

I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this one":
score [0] = total
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")
#### Go back to score so it can let you choice somewhere else.
list = [this one, here]
I need to be able to go back so essentially it forgets you tried to use "here" again without wiping the memory. All though I know they are awful, I basically need a go to but they don't exist in python. Any ideas?
*Edit: Ah sorry, I forgot to mention that when it's already in use, I need to be able to pick somewhere else for it to go (I just didn't want to bog down the code). I added the score == "this one"- so if I tried to put it in "here", "here" was already taken, it would give me the option of redoing score = input("") and then I could take that value and plug it into "this one" instead of "here". Your loop statement will get back to the top, but doesn't let me take the value I just found and put it somewhere else. I hope this is making sense:p
What you are looking for is a while loop. You want to set up your loop to keep going until a place is found. Something like this:
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
found_place = True
elif used[1] == 1:
print("Already used")
That way, once you've found a place, you set found_place to True which stops the loop. If you haven't found a place, found_place remains False and you go through the loop again.
As Ashwini correctly points out, you should do a while loop
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")

Categories