Does this Dice rolling Code have good style - python

Hi guys I just recently started doing my own projects and I'm hoping that as I work through these things that I can make sure to make the code as neat and polished as possible since I am mostly teaching myself.
So I was wondering if this was the best way to do this Dice rolling code:
Game = input("Hello there! Would you like to bet your luck on a dice roll?\n")
if Game == "yes"or"Yes":
print("Well great! Here we go!");
import random;
print(random.randint(1, 6));
else:
print("I guess next time then...");
specifically around the "if statement" and trying to account for people using capitalization or non-capitalization. Or just how to create a better way for people to put in a variety of answers.
Thank you

So I was wondering if this was the best way to do this Dice rolling
code:
To be short: No.
Game = input("Hello there! Would you like to bet your luck on a dice roll?\n")
This will work, but it you should use lowercase for your 'Game' variable, as this style (called 'CapWords' in PEP 8) are reserved for class names.
if Game == "yes"or"Yes":
This is basicly executed as:
if (Game == "yes") or "Yes":
You see what will go wrong here? You probably want something like:
if Game == "yes" or Game == "Yes":
But even better would be to this:
if Game.lower() == "yes":
This converts the input to lower case first, so basicly ignoring any capitalization used by the user.
print("Well great! Here we go!");
Nothing wrong with this line, except the ';' are not needed in Python.
import random;
Imports should be at the top of the file.
print(random.randint(1, 6));
Again, the ';' should not be used.
else:
print("I guess next time then...");
Again, the ';' should not be used.
If I were to write this program, it would look as follows:
import random
answer = input("Hello there! Would you like to bet your luck on a dice roll?\n")
if answer.lower() == "yes":
print("Well great! Here we go!")
print(random.randint(1, 6))
else:
print("I guess next time then...")

Or just how to create a better way for people to put in a variety of answers.
If you were to expand the possible answers, your if statement would get pretty long and ugly:
if game.lower() == "yes" or game.lower() == "y" or game.lower() == "uh huh" # and so on...
So, it would be best to put these in a tuple, and then check if their answer is in the tuple:
if game.lower() in ("yes", "y", "uh huh"):
# the rest of your code here...

Related

What command do I do to make someone loop back to a specific place in my code? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I am making a text based game. I am moving along, but I am stumped on how to make specific choices bring you back to where you need to make the choice. Currently, the current plan I am doing is to make the right answers bring you to the rest of the game, while the incorrect questions bring you nowhere, and you have to restart the program entirely, but it isn't very fun to have to slog through the parts I have already done every single time I get a wrong choice.
ruintalk = input ()
if ruintalk == '1':
print ('"Rude!" the old man shouts, "I knew you were just like the rest of them." The old man storms out as fast as his frail legs can take him. You never hear from him again and later die of lumbago and are buried in a paupers grave. Dont insult the old man or ask stupid questions. Hes kind of a dick so just roll with it and restart the game.')
What command should I put to bring me back to input()?
Loops are what can you help you with that. "while" loops particularly in this case. "while" loops keep iterating through a block of code till the condition is true.
Here is an example demonstrating their use -
while True:
ruintalk = input()
if ruintalk == correct_answer:
break # This will break the iteration
This block of code will keep iterating until break statement is called. Alternatively, what you can do is have a variable set as True and set it to false once the correct answer is entered. Here is an example showing this -
run = True
while run:
ruintalk = input()
if ruintalk == correct_answer:
run = False
If I understand what you're trying to build, you might want to make your input a function to be called. You can then build loops for different scenarios and your input will happen in a statement:
def userInput():
r = input()
r = r.lower() #I like doing this to simplify how I handle user input in the code
return(r)
while sceneComplete is False:
print("Something to setup the scene. What do you want to do, user??? (X/Y/Z)?")
action = userInput()
if action == "x":
do the x thing
elif action == "y":
do the y thing
elif action == "z":
sceneComplete = True
else:
print("You broke the rules and an ogre kills you ....")

Why is this script repeating itself?

I'm trying to teach myself python, I recently learned how to use raw input in an if statement (yes or no). However, when I answer yes, the program asks me the same if question.
Can anyone help? I'm not really good at programming but love doing it.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
# this is where it goes wrong
# below is what is supposed to follow
word = "kaasblok"
guesses = ''
turns = 6
while turns > 0:
If you use a while true loop, your program will keep on running.
In Python, the tabs or whitespace tell the interpreter when a loop ends.
So what happens in your code is this:
While True is running,
It asks if you want to play
If you write no it works as intended
If you write yes, it sees that the loop is over so it restarts.
Also your code has several errors, like syntax from both Python 3 and Python 2 and a while loop that doesn't terminate.
I wrote some updates to make the code sort of work but it is not "good" code because I tried to keep it as similar as possible. Also I chose a syntax (python 3) so make sure to change that if you're using Python 2.
I recommend you modularize your code and look at other people's code, it'll make your code better. Avoid using a while True loop, at least at the beginning. The code I wrote sort of tries to address it, but it probably doesn't do such a great job.
Maybe try editing the code a bit and updating with an answer later? I think you meant to write input, not raw_input but it could be that's the way you do it in Python 2. You should really learn Python 3 if you're trying to pick up Python btw as Python 2 is at its end of life cycle.
Place your game in the loop and it'll run. Try something like this:
import time
name = input("what is your name? ")
word = "kaasblok"
turns = 6
print("Hello " + name)
#yes no statement with raw input
trueorfalse = True
while trueorfalse:
yesno = input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
#trueorfalse = False
break
elif yesno.lower().startswith("y"):
print("cool, let me prep...")
time.sleep(1)
# Place your code in the elif block
while turns > 0:
guess = input("what is the word")
if guess == word:
print('win')
#trueorfalse = False
break
else:
turns -=1
print("you have these many turns left", turns)
print("you lost")
break
All that's missing is a way to break out of the while loop. So, use the break command.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
break # <-- break out of of the current loop
print "made it!"

how to fix "<function choice at 0x105303320>" in visual studio code?

I wanted to make an adventure game sort of thing and it consists mostly of print and time. sleep statements. but the only if statement with a def statement is messing it up, to a point that is. everything works perfectly fine until that end.
I have no clue what is causing this to happen. I mean with some certainty I can say that the if statement is the issue but I don't know how/why.
def choice():
input("so whats for breakfast, salad, eggs, or fish")
#many lines or print and sleep statements later
if str(choice) == "salad":
#insert if code
else:
print("try again")
expected - "hey what's for breakfast?" ans = salad. "then you have three options for salads
actual - < function choice at 0x10de89560 >
the above is what gets printed in the debug console and I have no idea why. there are no warnings or errors that VS code had told me about. I am too much of a beginner to already be getting these sorts of things, please help me.
It must be.. str(choice()).
choice is a function.
fixed code, choice is a function and requires a return
# Functions
def choice():
return input("so whats for breakfast, salad, eggs, or fish")
# Entry Point
decision = str(choice())
if decision == "salad":
#insert if code
pass
else:
print("try again")
screenshot of code running

Code that consistently asks a question until proper input that can be repeated many times + the ability to accept multiple inputs? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Firstly, sorry for the long title.
So... I am making a text adventure game in Python for learning purposes. I spent most of last night trying to squash a bug in my game where no matter what you typed it would take you 'north'. I could input "sadjbfl" and it would just take me "north" instead of giving an error. (But I could also put "south" and it would take me south...)
I figured out a "while True" loop by searching for how to do this online but then I ran into another couple of problems with it, the first being that I could not make it accept multiple inputs. I could not allow it to accept "'north' OR 'n'"; it would then just accept literally anything as the first choice. The second problem is that I believe I would need a "while True" loop for every choice in the game.
The other way I have tried to accomplish this is a simple "ask for 'north' or 'n' and if it's none of that then print 'error'" but when it prints an error the program stops running when I need it to re-ask the question.
"Solution" 1:
# this code works perfectly fine
# if you don't type what it wants
# it keeps asking the question again
while True:
user_input = input("Enter 'test': ")
if user_input.lower() == "test":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 1b (problem):
while True:
user_input = input("Enter 'test': ")
# With '"test" or "t"', it allows ANY input;
# it does not give an error and just prints
# 'Correct!'.
if user_input.lower() == "test" or "t":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 2:
# "ch" means "choice".
# (naming scheme for less space)
ch_1 = input("\nGo north or south? ")
if ch_1.lower() in ["north", "n"]:
print("\nYou went north!")
elif ch_1.lower() in ["south", "s"]:
print("\nYou went south!")
# if this 'else' prints it ends the program instead of re-asking
# the question of 'which way to go?'
else:
print("I don't know what that means.")
EDIT: Nothing I've read on this site has actually helped me concerning this problem, not even the "duplicate" of this one (which I read before posting this).
My problem:
When I use the "while True" loop, my code becomes incredibly restrictive.
Every single choice using this method needs to be wrapped in an "while True" statement and it limits my options severely. It works perfectly if I only have one choice/path in that block BUT as soon as I add another choice/path, the new path experiences the same exact problem that I made this post for to begin with.
If there's some way to just always spit out a predefined message saying "ERROR! Check for misspellings!" or whatever every time the user does not put in what I want them to then that would be fantastic. (The "duplicate" of this post had something like this (I think) but it didn't work. /shrug)
But in the meantime I just cannot figure this out. Maybe I should just go back to the basics for a while.
In solution 2 only the loop is missing:
while True:
# name your variables correctly and no comment is needed.
choice = input("\nGo north or south? ")
if choice.lower() in ["north", "n"]:
print("\nYou went north!")
break
elif choice.lower() in ["south", "s"]:
print("\nYou went south!")
break
else:
print("I don't know what that means.")
You can write a function to reuse the loop:
def ask(question, answers):
while True:
choice = input(question).lower()
if choice in answers:
break
print("I don't know what that means.")
return choice
choice = ask("\nGo north or south? ", ["north", "n", "south", "s"])
if choice[0] == "n":
print("\nYou went north!")
else: # the only other choice is "south"
print("\nYou went south!")

Best way to get a python game to continue to run

Beginner project review.
I made a simple guess the random number game and set it up so it should run continuously until you say you don't want to play again. I used some code I found online for the base of the game. So i was wondering if you guys could look at the end of the code and tell me if i did this the best way possible. I've tested it a bunch and it does. Just wondering if im doing it the most efficient way.
def playAgainfunc():
print("You won't play again. To play again press 'Y'. To exit press anything else.")
playAgainresponse = input()
if playAgainresponse == 'Y':
baseGamefunction()
playAgainfunc()
if playAgainresponse == 'y':
baseGamefunction()
playAgainfunc()
else:
print("Ok, I didn't want to play again anyway")
baseGamefunction()
playAgainfunc()
Thanks!
def baseGamefunction():
....
while True:
baseGamefunction()
if input("Do you want to play again? (y/N) ").lower() not in ["y", "yes"]:
break
Use a while loop and quit if the user inputs anything other than y or yes.
If using python2, use raw_input() instead of input().
Although I have no experience with Python myself, I do have a little bit with Java. I think it would be more efficient to use a while loop instead, if you have learned them. As a general rule of thumb, if you are repeating code, you will be losing a bit of efficiency.
while playAgain.lower() == 'y':
baseGamefunction()
playAgainfunc()
else:
print("Ok, I didn't want to play again anyway")
It's not efficient in terms of code volume as you do a separate tests for the upper and lower case Y. Instead convert the input to lower (or upper) case and test against that case.
See the below code, which defines your functionality in less code, with no repetition.
def baseGameFunction():
print('placeholder for actual game.')
while True:
baseGameFunction()
resp = input('play again? ')
if resp.lower() != 'y':
break
print('thanks for playing')

Categories