Problems simulating a dice in Python - python

I'm new to python and I'm trying to create a simple program to allow the user to choose to use an 8, 12 or 24 sided dice and then display the result from rolling it.
This is my code but I am unsure why when I enter whether I wish to roll again it produces an error.
import random
def dice4():
min=1
max=4
print random.randint(min, max);
return;
def dice6():
min=1
max=6
print random.randint(min, max);
return;
def dice12():
min=1
max=12
print random.randint(min, max);
return;
roll = "yes"
y = 1
while roll == "yes" or roll == "y":
x = input("What dice do you want to use? 4/6/12?");
if x ==8:
dice4();
elif x==12:
dice6();
elif x==16:
dice12();
else:
print "You have not entered a valid dice number";
roll = input("Do you want to roll again? y/n");
print "Thanks for rolling!";
input("Press <Enter> to quit");
Thanks for any help, I realise it is probably a trivial error.

I am unsure why when I enter whether I wish to roll again it produces an error.
So the problem is in that part of the code. Let's look at it:
roll = input("Do you want to roll again? y/n");
You're using the input function. That will try to evaluate whatever you type as a Python expression.
So, if you type yes, it will try to find the value of yes, and raise a NameError. The same for n or no.
If you type y, the same thing should happen… except because you happen to have an extraneous variable named y lying around, it will actually find a value, 1. So, when you check that later, in while roll == "yes" or roll == "y":, obviously 1 is not equal to either of those strings, so it will just exit.
The only thing you could type that would work is "y" or "yes" (or the same with single quotes). Which obviously you don't want your users to have to type.
The solution is to use raw_input instead of input, which just gives you the input as a string, instead of trying to evaluate it.
roll = raw_input("Do you want to roll again? y/n");
This is one reason using input is usually a bad idea. Even in the earlier case, where you want an integer, the errors for typos are going to be ugly.
For an even better reason, see what happens when you type __import__('os').system('dir C:\\') (substitute ls / if you're on Unix instead of Windows), and imagine how much mischief your user could cause with other inputs.
So, I would recommend always using raw_input. If you want to convert the input to an integer, pass it to int. If you want to treat it as a literal value of any type, use ast.literal_eval. If you really want to evaluate it as arbitrary Python code, use eval (which is no safer than input, but at least it's more explicit).

Let me just add other problems with your code. You overwrite the builtins minand max in your functions and you use semicolons which are not needed. You use empty return statements.
Then you repeat too much code with dice4, dice6 and dice12. You should use one function with a parameter. Now you will be able to throw a lot of different dice.
def dice(value):
print random.randint(1, value)
dice(4)
dice(6)
dice(8)

Related

Im trying to get an if statement to reply to a random number in python and display and print a message

I'm trying to get an if statement to recognize a randomly generated number but I don't know what is going wrong, it just ends the program as soon as i hit start and does not print anything, so far I have this.
import random
random.randint(1,3)
if random.randint == ('1'):
print('message')
I have tried changing the random.randint(1,3) into a variable by making it "a == ('random.randint(1,3)" but that did not work either. Does anyone know whats going wrong with it?
P.S: Sorry if the question is asked badly, I don't use this site much.
There are several problem with your code.
randint() creates a number like 1. It will never make a string like '1'. Additionally random.randint is a function. random.randint == ('1') will never be true, because a function is never never be equal to a number or a string. You want to compare the result of calling the function to an integer.
import random
num = random.randint(1,3)
if num == 1:
print('message')
random.randint() is a function - therefore, you have to save its output in a variable, or else the value will be lost. For instance:
import random
rand_num = random.randint(1,3)
if rand_num == 1:
print('message')

Trying to end a script based on users answer (at a particular point) within a multiple choice scenario

I've created a basic, multiple choice, interactive calculator in Python. I want the user to be able to have the option to stop the programme running by answering "No" when asked whether they want to test out my calculator.
I want to be able to print("Ok, no problem") which you can see is already there but I need something extra to stop the programme running if this is the answer that the user picks.
Code is below. See lines 12-13.
name = input("Hi There. What is your name? ")
print("Well Hi " + name + ", it sure is nice to meet you")
age = input("So how old are you anyway? ")
print("Wow, you're " + age + " huh? ")
print(name + " I would like you to try out the companies new calculator. Would you be
happy to do that? ")
answer = input("Please answer Yes or No ")
if answer == "Yes":
print("Thank you, I appreciated that. Let's begin")
elif answer == "No":
print("Ok, no problem")
else:
print("Sorry I didn't quite get that. Please answer yes or no")
import math
number_1 = int(input("Please pick a number "))
order = (input("Ok, now please pick either: +, -, / or * "))
number_2 = int(input("Great, now please pick a second number "))
if order == "+":
print(number_1 + number_2)
elif order == "-":
print(number_1 - number_2)
elif order == "/":
print(number_1 / number_2)
elif order == "*":
print(number_1 * number_2)
else:
print("Sorry that is not +, -, / or *. Please enter a relevant order")
Any help that you can give me would be much appreciated.
You can use sys.exit to terminate the program:
import sys
#...
elif answer == "No":
print("Ok, no problem")
sys.exit()
Here is an answer for you which helped me out:
Let me give some information on them:
quit() raises the SystemExit exception behind the scenes.
Furthermore, if you print it, it will give a message:
>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>
This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.
Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.
exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.
Furthermore, it too gives a message when printed:
>>> print (exit)
Use exit() or Ctrl-Z plus Return to exit
>>>
However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.
sys.exit() raises the SystemExit exception in the background. This means that it is the same as quit and exit in that respect.
Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.
os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.
Note that, of the four methods given, only this one is unique in what it does.
Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.
Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:
raise SystemExit
This way, you do not need to import sys first.
However, this choice is simply one on style and is purely up to you.

"Local variable 'name_variable' value is not used" error in Python 3.x

So, I'm new to programming and I'm currently learning Python.
While trying to make a simple game, I got stuck when I tried to change the variable, named user_answer to input("Please, answer with yes or no.").
Basically this is my line of code else: user_answer = input("Please, answer with yes or no.").
But for some reason I get an error, called "Local variable 'user_answer' value is not used".
Could anyone help me with this?
Thanks in advance!
Here's my full code:
def my_function():
user_answer = input("Would you like to play a game?")
if user_answer == "yes":
print("Great! I have a number in my head from 1 to 10. Make a guess!")
elif user_answer == "no":
print("Oh, okay! Maybe next time?")
else: user_answer = input("Please, answer with yes or no.")
my_function()
I'm guessing you're talking about an IDE inspection, not an actual runtime error? Are you using an IDE like PyCharm? If so, local variable ... value not used means that you are storing a value (input(...)) in a variable (user_answer) and then you're never using that value. But that is just as it should be, because it seems your program ends there; nothing is using the new value of user_answer.
Just ignore the warning and continue writing your program, making sure to use the new value of the variable, and the warning should disappear.
For context, the purpose of this warning is to catch programming mistakes early on. Suppose that I wanted to write a function that takes a list and appends the element in the middle to either end (front and back), and I wrote this:
def wrap_with_middle_element(sequence):
mid = sequence[len(sequence)//2]
sequence.append(element)
sequence.insert(0, element)
return sequence
You'll notice I didn't actually use the variable mid after defining it, but rather I used element. This could be because, for example, there is a global variable named element which the IDE suggested as code completion and I accepted absentmindedly, or because mid was previously named element, and in manually renaming it to mid (instead of using the IDE's functionality), I forgot to rename the other two appearances of the variable. (I know this seems kind of unlikely, but it's just to illustrate.) In this case the IDE will show the warning: Local variable 'mid': value is not used, since I'm defining mid but never using it. I'd quickly realise what was wrong and fix that (instead of finding out later when running the program).
Working example of OP's code
def my_function():
user_answer = input("Would you like to play a game? ")
while user answer not in ('yes', 'no'):
user_answer = input("Please, answer with yes or no. ")
if user_answer == "yes":
print("Great! I have a number in my head from 1 to 10. Make a guess!")
elif user_answer == "no":
print("Oh, okay! Maybe next time? ")
my_function()
In this example, first we get the user input with user_answer = input("Would you like to play a game? ") and then we make sure that it's either "yes" or "no" with the loop
while user_answer not in ('yes', 'no'):
user_answer = input("Please, answer with yes or no. ")
which terminates only when user_answer in ('yes', 'no') (or, equivalently user_answer == 'yes' or user_answer == 'no') evaluates to True.
Then you can continue with the rest of the program!
# if user_input...
Why it didn't work
With your previous code, the else statement executed when the user didn't input a valid answer (yes or no). But the problem was that, once the user inputted a new value (which could have also been invalid!), the program had nowhere to go (it had already "left behind" the if user_answer == "yes": print(...) code!).

Python game; Why can't I re-call my input and if/else function?

I'm still kind of learning Python, but my friend who has programmed in Python before says this should work fine, but it wont?
All code before this was the beginning story for this basic "escape the room" game I'm making. The code up until here works, (basic print functions describing the game).
I give the player the scenario that they're in a room and they can do one of two things:
def intro_room_input():
intro_action = input("What would you like to do? (Please enter either: 1 or 2) ")
return intro_action;
These two functions are for when they choose 1 or 2, the next if/elif function runs these functions
If they choose 1:
def intro_room_result1():
print(
"""
(Story stuff for the result of option 1. Not important to the code)
""")
return;
This function will play out if they choose 2
def intro_room_result2():
print(
"""
(Story stuff for the result of option 2. Not important to the code)
""")
return;
This will be the function for taking the player's input and continuing the story from there.
def intro_action_if(string):
if string == "1":
intro_room_result1()
elif string == "2":
intro_room_result2()
else:
print("I'm sorry, that wasn't one of the options that was available..."+'\n'+
"For this action, the options must be either '1' or '2'"+'\n'+
"Let me ask again...")
intro_room_input()
intro_action_if(string)
return;
that last intro_room_input runs fine, it re-runs the previous input, but when you actually enter 1 or 2, it doesn't do anything with them. It doesn't want to re-run the if/elif/else function to give the results.
finally I have a main that runs everything:
def main():
string = intro_room_input()
intro_action_if(string)
return;
main()
Please help, I have no idea what's wrong with this code!?
The problem is in your intro_action_if(). When you are calling the function to get values again, you forgot to change the string value.
ie,
#intro_room_input() #wrong
string = intro_room_input() #right
intro_action_if(string)
As you can see, even though in your code you asked for the user input and returned it, you forgot to reassign string with the returned value. Hence it kept the same input you had given previously and passed that old value to intro_action_if().

The efficiency of a specific while loop

I'm making a program for a school project and within the program, the user makes a decision. to make sure the user inputs a valid input. i want to know if using a while loop like this is efficient. it is be contained within a function that would be used multiple times. i did this as this function will be called and the returned value will be stored in a variable. this is for a command line programme:
def user_choice():
while True:
choice = input("choose \'a\' or '\b\':")
if choice == "a" or choice == "b":
return choice
else:
print("not a valid input")
In terms of raw machine efficiency, your algorithm is perfectly acceptable. The bottleneck is the user's input. It only goes through the loop once per input, so the actual execution of that code is basically instantaneous. Some programs will use a loop to continuously check some condition as fast as the computer can manage, and that is indeed suboptimal (eats up a CPU core).
In terms of good coding style, your algorithm is perfectly acceptable as well. Using a while True (or while 1) with a return on a valid input is very common and easily understood to any reader.
I would suggest some slight modifications like if choice.lower().strip() in ('a', 'b'): instead of if choice == "a" or choice == "b": as noted in a comment, but that's just to make it a bit more robust in the face of messy user input. Also, you don't need to escape quotes unless they're of the type that encloses the string, so you can do input("choose 'a' or 'b':") instead of input("choose \'a\' or '\b\':").

Categories