Python Using RandInt to Generate 3-Digit Pattern: Syntax Error - python

I'm reading a beginners text on Python Programming. And I'm getting a syntax error that, seemingly, is a typo in the text. The code is:
class LaserWeaponArmory(Scene):
def enter(self):
print(dedent("""
You do a dive roll into the Weapon Armory, crouch and scan
the room for more GOthon that might be hiding. It's dead
quiet, too quiet. You stand up and run to the far side of
the room and find the neutron bomb in its container.
There's a keypad lock on the box and you need the code to
get the bomb out. If you get the code wrong 10 times then
the lock closes forever and you can't get the bomb. The
code is 3 digits.
"""))
code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
guess = input("[keypad]> ")
guesses = 0
while guess != code and guesses <10:
print("BZZZZEDDD!")
guesses += 1
guess = input("[keypad]> ")
if guess == code:
print(dedent("""
The container clicks open and the seal breaks, letting
gas out. You grab the neutron bomb and run as fast as
you can to the bridge where you must place it in the
right spot.
"""))
return 'the_bridge'
else:
print(dedent("""
The lock buzzes one last time and then you hear a
sickening melting sound as the mechanism is fused
together. You decide to sit there, and finally the
Gothons blow up the ship from their ship and you die.
"""))
return 'death'
I'm getting the following error:
File "ex43.py", line 121
code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
^ SyntaxError: invalid syntax
So it seems to be trying to create a 3 digit pattern of random numbers?

f strings are supported from python 3.6+
try:
code = "".join([str(randint(1,9)) for _ in range(3)])
And you might want to use randint(0,9) to get also zeros

"randint" module is not imported. Add the following statement
from random import randint

Related

How to make a Dungeons and Dragons-esque skill check in Python?

I am trying to make a small text-based adventure game in Python IDLE, but I am running into some issues with having the game give a different response if the player rolls above or below the DC of a DND style preception check. I am very new to this so it's probably an easy fix. Here's the code.
I have no idea how to input the code into the question correctly so here is a picture.
BTW I did import random at the beginning of the code its just too far back to include in the screencap.
Your problem is you are not specifying what numbers the random module to choose from, in the line if random.randint > 10:. To fix this, put the numbers you want it to choose between. For example, if you want it to choose a random number between 1 and 20, your line would become if random.randint(1,20) > 10:.
You will also want to do this for the other line, which reads if random.randint < 10:.
welcome to SO,
Please read the minimal reproducible example guide posted in the comments by D.L. First thing I would do is to post the actual code, because if the link expires, then others viewing this post with a similar issue cannot figure out what was the given example, and how it was solved.
With logistics out of the way, to fix the error you are specifically receiving is to put what is rolled in a variable.
Here are a few things I would change to make your code clear
# Some string that receives yes or no
room_2_input = ("...")
# if condition is yes
if room_2_input == 'yes':
# Put it in a variable
roll = random.randint(1,20)
# You do not have to format a string this way, but I think it makes it easier
print('You rolled {}'.format(roll)
# Put this condition within the first if, because you don't
# need to execute it if they do not choose to roll
# Neither of your original condition has inclusivity, so if 10 is rolled,
# your program will do nothing, because neither condition would be met
if roll >= 10:
'''do stuff'''
# I would only include elif < 10 if you are specifically looking for > 2
# outcomes, but your outcome appears to be binary, either above or below 10
else:
'''do stuff'''
The reason you would not do a random.randint(1,20) > 10: check in your second if statement is because you would be executing a different roll than your first one.

How to make a while loop throughout entire code. (Python)

I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.
I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions
health = 20 #variable
while ( health < 0):
print("You died to [insert event here]\n")
break
Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.
First off, the global keyword is only to give a function write access to a variable. They can always read variables which have been declared outside the scope of any other class/function.
What I think you want is the following:
check health
run the rest of the code
check health
run the rest of the code
ad infinitum...
What you are currently doing, as described, is:
check health
run the rest of the code
How you're going to do this is:
while(health > lower_limit):
[the rest of the code]
print("you died") # game over
In this way, "while the health is above the lower limit, [the rest of the code] will run".
You may write it as:
health = 20
while health > 0:
print("You died to XYZ")
health -= 1
This will print "You died to XYZ" 20 times as loop will run for 20 times from health = 20 to health = 0.
But, while health < 0 would consider it to be zero outcome because python understand loop to run till health reaches zero.
I don't think this is a good place to explain in detail why that code doesn't work. Instead, consider the following game as an example:
def adventure_around(pit_limit = 5, initial_position = 0):
position = initial_position
lived = False
print("Try not to die, noob!")
while position < pit_limit:
direction = input("Which way would you like to go? [n,s,e,w, or q]:")
if direction not in ['n', 's', 'e', 'w', 'q']:
print("Please choose a direction.")
continue
if direction == "n":
position += 1
if direction == 's':
position -= 1
if direction == "q":
print("Coward! (You lived, though.)")
lived = True
break
if not lived:
print("You fell into a pit and died while bravely wandering about! RIP")
adventure_around()
Feed that to your python interpreter and play around with it. (Minutes of fun!) Then study the code. (Googling isn't cheating, either!) What does the while keyword do? How is information from the outside code conveyed to the function? Why are there two ways to exit the while loop? Was that a good idea? Is there a better way to update the position? Did lived need to be initialized? Why or why not? Go ahead and modify it to suit your purpose, if you can. While I don't think a global health variable is the best way to go, try to change the code so that it uses the global keyword to reference a global health variable. What error messages did you get while getting that to work? How would you manage that in a much larger game with tens, hundreds, or thousands of files?
Good hunting!

Exiting a python application for 'GAME OVER'

I would like to know why this code does not work; it should exit at the "GAME OVER" point, but it continues to my next defined function.
I have tried other variations on exit() such as: sys.exit(), quit() and SystemExit.
run_attack = input("What do you do: Run/Attack\n")
run = ['run', 'Run', 'RUN']
attack = ['attack', 'Attack', 'ATTACK']
run_attack = 1
while run_attack < 10:
if run_attack == ("run") or ("Run") or ("RUN"):
print ("You turn to run from the wolf but he quickly pounces
you...")
time.sleep(2)
print("You are quickly ripped apart and just about get to see
yourself be eaten.")
print("GAME OVER")
break
exit() #This is where the game should exit, yet after input it
continues to the next function
elif run_attack == ("attack") or ("Attack") or ("ATTACK"):
print("You brace yourself for a bite and have no time to reach"
"for any kind of weapon form your backpack.")
time.sleep("2")
input("You clock the dog hard, twice on the muzzle.")
print("The dog recoils in pain and retreats back to the woods.")
print("You quickly start running as you assume there will be a den in the woods.")
break
else:
input("Type Run or Attack...")
You have several problems in your code; why did you write this much without testing it?
First, you read the user's input, immediately replace is with 1, and then try to test it (incorrectly) as if it were still a string. Your posted code has several syntax errors, so I have some trouble reproducing the problem. However, the immediately obvious problem is here:
break
exit() # This is where ...
You can't get to the exit statement, as you break from the loop just before you can get there.
I strongly recommend that you back up to a few lines and use incremental programming: write a few lines at a time, debug those, and don't continue until they do what you want.
Also look up how to test a variable against various values. Your if statement is incorrect. Instead, try the list inclusion you're trying to set up:
if run_attack in run:
...
elif run_attack in attack:
...
I took the liberty of rewriting your whole program to show you a few things wrong with it and a few tricks. I've done it without the loop, since you never use it anyway... you can add the while loop later once you've mastered it, but you should really go back to basics on some things here:
run_attack = input("What do you do: Run/Attack\n")
if run_attack.lower() == "run":
print("""some
stuff
with
multiple
lines and GAME OVER""")
exit()
elif run_attack in ("attack", "Attack", "ATTACK"):
print("""some
stuff
with
multiple
lines""")
else:
input("Type Run or Attack...")
Some notes:
Using """ for strings enables you to write multiple lines without multiple print statements
Using str.lower() on strings makes everything easy to compare because you only have to compare it to the lowercase version of each string. However for attack you can notice I used a different inclusion test, without multiple conditions. Either way works here.
Like the other answer here (and many comments), you should use only exit() to leave the program entirely, or only break to exit the loop and continue to other code that's beneath the entire loop.
When you rewrite your loop, with a condition like while number_of_turns < 10 don't forget to add 1 to the number of turns on each loop, otherwise that condition is always True and you'll have an infinite loop...
I'm actually quite surprised this code had any resemblance to the behavior you expected from it, my suggestion is to go back over to the basics of python, learn loops, string methods, basic commands. The rest is already said in the other answer here (which is better than mine, frankly) just wanted to add some ideas.

Script stops printing output when input changes

I'm making a coin flip game that asks the user "Heads or Tails", and after the user chooses one of the two, it will respond back saying either "correct" or "wrong". When I run my code, it works perfectly fine if I keep repeating either heads or tails. But if I switch it up like something like heads, heads, tails . It won't ask me the question "Heads or Tails" anymore. And what's weird is sometimes after switching it up it will ask but then eventually it stops. This is my code:
import random
coin=["CORRECT!", "WRONG!"]
hot=raw_input("Heads or Tails? \n")
while hot == "heads":
if hot=="heads":
for i in range(1):
print random.choice(coin)
hot=raw_input("Heads or Tails? \n")
while hot =="tails":
if hot=="tails":
for i in range(1):
print random.choice(coin)
hot=raw_input("Heads or Tails? \n")
And then this right here is the problem I'm talking about when I run it
Heads or Tails?
heads
CORRECT!
Heads or Tails?
tails
CORRECT!
Heads or Tails?
tails
WRONG!
Heads or Tails?
heads
After that last heads I put it doesn't say correct or wrong, and sometimes it doesn't show it even earlier when I run it.
You can try implementing the same using:
hot = raw_input('Heads or Tails?\n')
while hot != 'quit':
if hot == random.choice(['heads', 'tails']):
print 'Correct!'
hot = raw_input('Heads or Tails?\n')
else:
print 'Wrong!'
hot = raw_input('Heads or Tails?\n')
This allows the user to continue flipping the coin until the user enters 'quit'.
It isn't strange that your program stops after you stop responding "tails". This is because of basic control flow. You've used five types of control flow in your program.
First, unless told otherwise, control will flow from one statement to the next. So import random happens first, then the assignment of coin, and so on.
Second, you've used function calls such as raw_input() and random.choice(). These run other subprograms, which we don't need to consider very deeply here since all of them return to your main program.
Third came two while loop constructs. These contain some section of code they repeat as long as their condition is satisfied; crucially, they therefore end when it is not. So the first loop actually ends when you respond something other than "heads".
Fourth, you have an if statement within each loop. This runs its contents if a condition is satisfied, just like while, but doesn't repeat. Since the condition you used is exactly the same as the surrounding while, these checks are redundant; we wouldn't be executing this part of the program if the condition wasn't met.
Fifth you used a for statement; these make loops, like while, but process every entry of some iterable. In this case, that served no purpose because there is only one entry in range(1) and you never actually used it. Like the if, it is redundant.
Having deciphered these, we see the control flow moves from "heads" loop to "tails" loop then simply ends, having run out of program. To keep the program running we must have a loop that does not end, for instance:
while True:
if hot=="heads":
for i in range(1):
print random.choice(coin)
hot=raw_input("Heads or Tails? \n")
if hot=="tails":
for i in range(1):
print random.choice(coin)
hot=raw_input("Heads or Tails? \n")
This loop exhibits another issue, namely that nothing checks that the answer entered was either heads or tails. It will therefore get stuck running nothing if we give another answer. You can solve this by ensuring we ask for a guess in every iteration, and for some extra flair, even respond to invalid guesses using else:
while True:
hot=raw_input("Heads or Tails? \n")
if hot=="heads":
for i in range(1):
print random.choice(coin)
elif hot=="tails":
for i in range(1):
print random.choice(coin)
else:
print "I don't know what side of a coin that is."
Note that I moved the raw_input call outside of the conditional sections. Since it was equal for all branches, it doesn't need duplication. I also used elif and else to tie together the conditional sections, ensuring only one of them will run for any iteration (each time through the loop). And about duplication, your two conditionals perform the exact same operation! You've taken a shortcut and not actually calculated which side the coin landed on - only used its odds of success. Let's fix that too.
sides = ("heads", "tails")
while True:
hot = raw_input("Heads or Tails? \n")
if hot in sides:
toss = random.choice(sides)
if hot == toss:
print "Correct"
else:
print "Incorrect"
else:
print "I don't know what side of a coin that is."
Note that there are two if statements on different levels this time, each with their own else. These are independent, aside from the fact that the inner one only runs if the outer condition was true. All sorts of control flow statements (ending in :) can be nested this way.

Learn Python the Hard Way - Exercise 36 - if else die function

The second rule for If-Statements here, which has me confused states that:
If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
Here's the code from the last exercise:
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
choice = raw_input("> ")
if choice == ‘left’:
bear_room()
else:
dead(‘You stumble around the room until you starve.’)
Is it essentially saying that you must successfully terminate the program if a condition is not met?
Yes, the idea is:
import sys
def die(msg):
print msg
sys.exit(1)
if condition:
# do stuff
else:
die('This cannot happen!')
You could also use an assert instead, or raise an exception, or anything else that would fail catastrophically. This helps you validate at runtime that the clause you didn't expect to execute, really didn't run.
IMHO you shouldn't get too hung up on how this die is done, exactly. The important point the referred text tries to make is that when you're sure some condition is true, you might as well assert it forcefully so that you can catch runtime bugs.
The guide is trying to show you that you can see the choice that a user gives when it's something that you don't check for in your if statement. If your else looks like:
else:
dead(choice)
You will be able to see what the user input that you didn't expect.
The problem is that the syntax only allows for "Left", when the prompt allows entry of anything. In other words, if I enter "Bob", I will starve. I should be trapping for anything that isn't appropriate and "die"ing at that point (or helping the user make an appropriate decision).
This is an attempt at teaching error handling and die. You would rewrite it such that you allow accurate entry or die (no exit). If you don't choose left, there is no other choice even though the prompt states there are two choices.
If you truly expect only 'left' to be added, a better way of checking for unexpeted input would be
if choice != ‘left’:
dead(‘You stumble around the room until you starve.’)
bear_room()
That way you still validate that the input is what you expected, but it saves indentation and space for the main logic.

Categories

Resources