I'm a fairly new programmer and I'm trying to do a type of BlackJack were when you get 21 or over 21 the code "break". Or the code do not keep on running.
I have tried exit() and sys.exit() but at the end this keeps popping up "An exception has occurred, use %tb to see the full traceback.
SystemExit" and I wonder if there is another type of command to break the code from running but without an error message.
Player = input()
if Player == "Hit me":
print("You have",x+y,)
if x+y == 21:
print("You win")
sys.exit()
elif x+y > 21:
print("You loose")
sys.exit()
this is a part of it or more so the part that I want to change with the "sys.exit()".
BTW the x and y you see is variables that are assigned random numbers in the beginning.
You shouldn't rely on a forced exit from the program - instead, build-in the exit case to your code. Without seeing your code it's difficult to be specific, but an example structure would be:
score = 0
while score < 21:
score = black_jack(score)
print("You scored {}!".format(score))
Where the black_jack() function contains your code to simulate a round of the card game.
Related
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
Title.
I'm currently writing a choose your own adventure python script for my computer science class and need to give the player 5 lives and when they run out have a line of text appear. Any ideas?
(I'm not sure if I need to post the script or not but I can later today if needed.)
script:
# Name: Drew Dilley
**# Date: 12/7/20
# 1 REMOVED IMPORT MATH BECAUSE IT IS NOT NEEDED FOR THIS SCRIPT.
# 2
import random
answer: str = input("Do you want to go on an adventure? (Yes/No)")
# hint: the program should convert player's input to lowercase and get rid of any space player enters
# hint: check out what .upper(), .lower(), .strip() do on a string, reference: https://www.w3schools.com/python/python_ref_string.asp
# 3
if answer.upper().strip() == "yes":
# hint: pay attention to the variable name
# 4
ANSWER= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
# 5 UNNECESSARY INDENT
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack": #(HAD TO FIX UNEXPECTED INDENT)
print("She turned you into a green one-legged chicken, you lost!")
# 6 HAD TO ADD PARENTHESES AND FIX THE SEMICOLON AFTER "ANSWER"
elif answer := "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
# 7 SEMICOLON NEEDED AFTER "ELSE" PLANE/ANSWER + CAR/ANSWER NEEDED TO BE FLIPPED. NO INDENTATION NEEDED FOR "ELSE". == INSTEAD OF !=
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
elif "right" != answer:
else:
print("You are frozen and can't talk for 100 years...")
# hint: the program should randomly generate a number in between 1 and 3 (including 1 and 3)
# hint: remember random module? reference: https://www.w3schools.com/python/module_random.asp
# 8 HAD TO IMPORT "RANDOM"
num: int = random.randint(0,3)
# 9
answer = input("Pick a number from 1 to 3: ")
# hint: will the following if statement ever be executed even when the values of answer and num are the same? If not, can you fix the problem?
# hint: the error is not necessarily in the line below.
if answer == num:
print("I'm also thinking about {}".format(num))
print("You woke up from this dream.")
else:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print('You can\'t run away...')
# 10 NEEDED A SEMICOLON FOLLOWING THE ELSE STATEMENT, SO THAT IT KNOWS WHAT TO READ AND PERFORM NEXT IN THE SCRIPT.
else:
print ("That's too bad!")** ```
you can use a for loop with a counter variable which you can decriment at every time player looses and when it goes from 5 to zero you can use break to exit the loop or a print before break to display a message.
optionone = 0 #DEFINING BOTH VARIABLES
optiontwo = 0
class first_day_morning: #WORKING
optionone = input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input()))
I am trying to make it so that the user input decides the outcome of the if statement, if user inputs 1, then something happens, if user inputs 2 then something else happens, if user inputs anything else, than the if statement runs again as only 1 or 2 are valid inputs. However, the problem is that no matter what the user inputs, the if statement does not run, and no error is shown either. I tried a try/except in case an error just isn't showing for some reason (try except ValueError:) and nothing seemed to work I have also tried to specify the input as str, int, float, no specification, raw_input etc. and nothing really works, can someone help?
ps. I am using Visual Studio Code
As you can see, the if statement does not run as no error is shown even after user input.
When the program runs, the class body will be evaluated, meaning the input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ") will prompt for input. That value will then be kept in first_day_morning.optionone, however first_choice's optionone is different. It is equal to the parameter supplied on the final line, int(input()), which will silently prompt for another input, and then convert it to an integer. From what I think you're trying to achieve, I'd recommend you remove the class and change the final line to:
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
def first_choice():
print('')
print("You have chosen to get out of the house for once")
def second_choice():
print('')
print("DO LATER")
def third_choice():
print('')
print("please choose a valid option")
while True:
print("""Select a choice""")
c = int(input('enter your choice:'))
if c == 1:
first_choice()
elif c == 2:
second_choice()
elif c == 3:
third_choice()
elif c == 4:
break
i dont really understand what u r trying to acomplish here, but the code works for me, some tips from a beginer:
-you define optiontwo and never use it
-you you are filling optionone with input inside a class, dont know why, cause is never used
not sure what do u want, but try this:
import time
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
although, test it in console, not sure about vscode but running inside sublime does not ask for input
Despite importing the variable 'health' from a different module, the function below provides the error shown in the title. 'Health' is also globalised and I have removed both the globalisation and the importation of the variable and I still receive the same error.
Below is the function that is causing the issue.
def combat():
enemy_health = (random.choice(random_enemy_Health))
enemy_attack = (random.choice(random_enemy_Attack))
print("\nYou are fighting a" ,random.choice(enemies), "with an attack amount of" ,enemy_attack, "and a health amount of" ,enemy_health,".")
while health > 0 and enemy_health > 0:
if turn == 1:
while loop == False:
response=input()
try:
move = response("Do you want to attack or flee? Type '1' to attack and '2' to flee.")
move = int(move)
if move == 1:
enemy_health = enemy_health - attack
print("You attacked!")
loop = True
elif move == 2:
hub_travel()
print("You fled the battle, come back once you are stronger!")
loop = True
else:
print("Invalid number, try again")
continue
except:
print("Invalid number, try again")
continue
turn = 2
if turn == 2:
AImove = randint(1,2)
if AImove == 1:
print ("Enemy attacked!")
health = health - enemy_attack
turn = 1
continue
print ("game over!")
if enemy_health == 0:
print("The enemy has been defeated!")
gold += random.choice(gold_dropped)
The error occurs on this line in particular:
while health > 0 and enemy_health > 0:
If I were you, instead of relying on globals, I would use parameters. This advice may help you to track some errors.
Globals variables is a possibility in programs that have a few lines of code. But, when you application grows, it is a bit hard to track the current value of some variable, because it can be used in several functions or methods (probably, you need a mental mapping to find out the current value). So, this is one of the reasons why you must prefer to use local variables or parameters instead of globals.
This change would allow your function to work the way you want:
def combat(health):
...
Of course, you'd have to find the places where you call the function and pass in the value for health. I don't know if the code at that point has access to that information.
This is probably the simplest fix that could possibly address this issue. It is certainly not the best fix, but this is not a good place for an architecture tutorial.
The major problem I'm having is what occurs when I choose stay on hand_one, and then hit on hand_two.
Instead of asking me to hit or stay on hand_two again, it brings me back to hit or stay on hand_one, when I already chose stay on hand_one, so hand_one should have no more options. This causes issues with multiple print statements occurring and incorrect game play.
What is wrong with my code that it is like causing it to loop back to hand_one.
The full code is here: http://labs.codecademy.com/Bjaf/2#:workspace
Here is the part likely causing the issue.
def hit_or_stay(person):
hit_or_stay = raw_input("Do you want to hit or stay? You can type h or s.")
if hit_or_stay == 'h' or hit_or_stay == 'hit':
deal_one_card(person)
value_of_current_cards(person)
number_value_of_hand()
elif hit_or_stay == 's'or hit_or_stay == 'stay':
print "You stayed"
return
else:
hit_or_stay(person)
def number_value_of_hand():
if number_of_hands > 0:
value_of_hand_one = value_of_current_cards(hand_one)
if value_of_hand_one < 18:
print "\n" "You have %i" % (value_of_hand_one)
hit_or_stay(hand_one)
elif value_of_hand_one > 18:
print "You Lose"
return
elif value_of_hand_one == 18:
print "You hit HOT 18!!!"
return
if number_of_hands > 1:
value_of_hand_two = value_of_current_cards(hand_two)
if value_of_hand_two < 18:
print "\n" "Your second hand has %i" % (value_of_hand_two)
hit_or_stay(hand_two)
elif value_of_hand_two > 18:
print "You Lose"
return
elif value_of_hand_two == 18:
print "You hit HOT 18!!!"
return
number_value_of_hand()
Can anyone see why it loops back to give hand_one another option? And possibly how I can fix it? Thanks so much!
Your problem occurs on this step:
hit_or_stay(hand_two)
When you hit on hand_two, your code does this:
deal_one_card(person)
value_of_current_cards(person)
number_value_of_hand()
The problem is right there, because number_value_of_hand() brings you back to the beginning of that function, and goes through the hand_one options again.
You will probably have to rewrite your number_value_of_hand() function to include an argument that tells it where to begin (hand_one, hand_two, etc.)
I would probably make a list of hands, and iterate through the list. Then, you could call number_of_hands(hands[i]) to being at the ith hand.