how to get python 3 to use ENTER as an input? - python

How do i get the enter key to work in this situation? I tried searching for it, but maybe i'm wording it wrong.
also, how would i get the else statement to work in this particular situation?
thank you
import random
def roll_dice():
roll = random.randint(1,6)
print("You rolled a %n " % roll)
def main():
input("Hit ENTER to roll a single dice: ")
roll_dice()
else:
print("exiting program.")
main()

You have to store input in a variable. Let it be enter.
User will hit enter and you will check if it was enter or not.
If input was an empty string then it is okay!
import random
def roll_dice():
roll = random.randint(1,6)
print("You rolled a %d " % roll)
def main():
enter = input("Hit ENTER to roll a single dice: ")
if enter == '': # hitting enter == '' empty string
roll_dice()
else:
print("exiting program.")
exit()
main()

In a case like this, would I usually do, is something like this:
if input == "":
roll_dice()
I'm not sure if thats what you are looking for, though :3

Just use:
if not input("Hit ENTER to roll a single dice: "):
roll_dice()
else:
print("exiting program.")
Also use a while loop instead, to ask user multiple times:
import random
def roll_dice():
roll = random.randint(1,6)
print("You rolled a {} ".format(roll))
def main():
while True:
if not input("Hit ENTER to roll a single dice: "):
roll_dice()
else:
print("exiting program.")
break
main()
If input() is non empty it will exit the program.

Related

Is there something wrong with the try and except statements that caused the error?

I'm trying to make a basic coin flipping simulator. And ask the user for their name and greet them. Then ask if they want to play the game. But when they enter something other than "Y", it gives this error message: UnboundLocalError: local variable 'time_flip' referenced before assignment how can I fix that and instead it prints a goodbye message. And ask them again if they want to keep playing.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
There is more code, but I shortened it to the part with errors
here's the full program: https://replit.com/#Blosssoom/coinpy?v=1#main.py
The assignment of time_flip may not complete if there is an error transforming the input to an integer.
To resolve, assign to time_flip before the try block:
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = None
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
If people don't type y or Y, the while loop will never run. This cause that every variables in the while loop will never ba created. You want to return time_flip, but because it supposes to be made in the while loop (), it won't be created -> local variable 'time_flip' referenced before assignment (self-explained).
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = 0 #None or anything
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
return time_flip

What's the reason why second parameter of a function is always being treated as 1?

My goal is to create a dice roller which lets the user choose both the number of dice and number of sides.
The problem started when I made it possible for the user to go through the process again (select number of dice and of sides). Now it doesn't display the result of anything besides the first die and, when the user types "n" and function breaks, sometimes it does, and sometimes it keeps going. This last part makes sense because the function "start" comes next. I haven't figured a way to truly finish running the script.
from random import randint
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
# variable "roll" generates random number between 1 and user input
roll = randint(1, n_sides)
# variable "roll" is appended to the previously created empty list "rolls"
rolls.append(roll)
# enumerates however many results there was
i += 1
# prints the end result to the user
print("Result", i, ":", roll)
choice = input("Do you want to roll the dice again? (y/n)")
# if user input is "y", start over by running function "start"
if choice.lower() == 'y':
start()
# uses lower() so that lower case is allowed
elif choice.lower() == 'n':
# break terminates function
break
def start():
print()
try:
print("How many sides your dice has?")
n_sides = int(input().lower())
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
try:
print("How many dice do you want to use?")
n_dice = int(input().lower())
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
dice(n_sides, n_dice)
start()
Here's a better way to organize this. Have each function do one thing. When it has done its one thing, let someone else make the decisions.
Also, it's pointless to call lower() when all you want is integers.
from random import randint
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
# variable "roll" generates random number between 1 and user input
roll = randint(1, n_sides)
# variable "roll" is appended to the previously created empty list "rolls"
rolls.append(roll)
# prints the end result to the user
print("Result", i+1, ":", roll)
return rolls
def round():
print()
try:
n_sides = int(input("How many sides your dice has?"))
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
continue
try:
n_dice = int(input("How many dice do you want to use?"))
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
continue
print(dice(n_sides, n_dice))
while True:
round()
choice = input("Do you want to roll the dice again? (y/n)")
if choice.lower() == 'n':
break
What I understood is, you have n dices each having m sides and the user will roll all the dices per input.
Your code has the bug inside dice(n_sides, n_dice): function as you are executing all the statements in the for loop which is running same times the number of dices. Remember, indentation is important in python
Also, while you're taking input, you can use a while loop to force the user to input a valid number like this:
isNumeric = False
while(isNumeric == False):
try:
print("How many sides your dice has?")
n_sides = int(input().lower())
isNumeric = True
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
isNumeric = False
while(isNumeric == False):
try:
print("How many dice do you want to use?")
n_dice = int(input().lower())
isNumeric = True
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
To remove the bug in your dice function, you can do as follows:
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
# variable "roll" generates random number between 1 and user input
roll = randint(1, n_sides)
# variable "roll" is appended to the previously created empty list "rolls"
rolls.append(roll)
# prints the end result to the user
print("Result of Dice Number", i+1, ":", roll)
choice = input("Do you want to roll the dice again? (y/n)")
# if user input is "y", start over by running function "start"
if choice.lower() == 'y':
start()
# uses lower() so that lower case is allowed
This will smoothly solve all of your problems!
First of all, I would use exit() instead of break. Break can be used in loops (see here: https://www.programiz.com/python-programming/break-continue)
Secondly, use a while loop for the yes or no question, like:
while True:
a = input("Do you want to roll the dice again? (y/n)")
if a == "y":
start()
continue
elif a == "n":
exit()
else:
print("Enter either y/n")
So if you don't want to change the logic of the code:
from random import randint
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
roll = randint(1, n_sides)
rolls.append(roll)
i += 1
print("Result", i, ":", roll)
while True:
a = input("Do you want to roll the dice again? (y/n)")
if a == "y":
start()
continue
elif a == "n":
exit()
else:
print("Enter either y/n")
def start():
while True:
try:
print("How many sides your dice has?")
n_sides = int(input())
break
except ValueError:
print("This is not a whole number.")
while True:
try:
print("How many dice do you want to use?")
n_dice = int(input())
break
except ValueError:
print("This is not a whole number.")
dice(n_sides, n_dice)
if __name__ == '__main__':
start()
Edit:
you need to import exit to do this: from sys import exit

Python 3 Y/N Loop Issue

I'm very new to Python, and I'm just having a play with making some very simple little programs to get a feel for it, so probably best to keep any explanations really simple haha!
I'm currently making a little program that asks if you want to roll a dice, rolls it, gives you the answer and asks if you want to roll again.
The issue I'm having trouble figuring out is the following (copied from console):
What is your name: Nasicus
Greetings Nasicus!
Would you like to roll the dice? [Y/N]? : Y
Let's do this!
Rolling...
You rolled a 3!
Do you want to roll again? [Y/N]?: Y
Yahoo!
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Process finished with exit code 0
As you can see, it prompts twice when you select N before it closes.
I'm probably missing something incredibly simple, so could anyone advise how I can either A. Stop it prompting twice or (preferably for the sake of simplicity) B. Stop it asking if You want to roll the dice after you have already selected Y to roll again, and just go straight from the Let's do this! line.
Here is my code, any pointers on how to keep things tidier/more pythonic always appreciated too! I appreciated the time.sleep() probably look a little messy, but I do like the way it paces things when I run it:
import random
import time
def diceroll():
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Thank you for your time, and I look forward to learning more :D
The problem is in this section of code:
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
You're recursively calling the diceroll() function, so when that recursive call finally finishes, the iteration of the current call still continues.
You're already in a while True loop, so you don't even need the recursive call. Just take it out, and let the loop continue.
You are calling diceroll recursively.
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
So you call diceroll() and then whenever the user is asked
Do you want to roll again
You call diceroll() again.
Here is what is happening. You have a top level diceroll().
diceroll()
Then you have another diceroll() under it like this:
diceroll()
-- diceroll()
And then you have yet another diceroll() inside it.
diceroll()
-- diceroll()
---- diceroll()
When you call the break statement, all you are doing is breaking out of that inner diceroll() loop, not the loop where you called it.
A break in the third row sends you to
diceroll()
-- diceroll()
I would just break out your actual rolling into a separate function in your diceroll() function, that way you won't confuse the paths.
import random
import time
def diceroll():
def rollIt():
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
rollIt()
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
rollIt()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Here is the Object Oriented approach:
import random
import time
class Rolling_Dice_Game () :
def startup (self) :
prompt = ("Would you like to roll the dice? [Y/N]? : ")
if self.query_user (prompt) == 'Y' :
self.run_the_game ()
return True
else : return False
def run_the_game (self) :
print ("Let's do this")
print ('Rolling...')
time.sleep (1)
rand = random.randint (1, 6)
print ('You rolled a ', rand, '!')
time.sleep (0.5)
return True
def query_user (self, prompt) :
return input (prompt) [0].upper ()
def continue_the_game (self) :
prompt = ("Do you want to roll again? [Y/N]?: ")
if self.query_user (prompt) != 'Y' :
print ('Oh, Okay. Maybe next time.')
return False
else : return True
my_dice = Rolling_Dice_Game ()
if my_dice.startup () == True :
while my_dice.continue_the_game () == True :
my_dice.run_the_game ()

Computer Generates a Number, User Guesses Number, No Matter What it is Always Incorrect

I made a simple program where a user guesses a randomly generated computer number. To test if the program is working, I changed the generated computer value to 5. However, when I "guess" 5, I am somehow still incorrect.
Can someone please tell me what is wrong with this code?
I tried messing about with returning variables but I don't understand how the return command works so I was not successful.
def computer_roll():
global comproll
comproll = random.randint(1,3)
# comproll = 5
user_guess()
def user_guess():
global user
user = input("Input a number: ")
guess_evaluation()
def guess_evaluation():
if user != comproll:
print("You are incorrect.")
again = input("Would you like to try again? ")
if again in("y"):
user_guess()
elif again in ("n"):
print("Thanks for playing.")
elif user == comproll:
print("You are correct.")
again = input("Would you like to play again? ")
if again in("y"):
user_guess()
elif again in ("n"):
print("Thanks for playing.")
computer_roll() # Start```
# Expected Results:
# When I enter 5 it should say "You are correct." and then "Would you like to play again?"
# Actual Results:
# When I enter 5 it says "You are incorrect" and then "Would you like to play again?"
You are comparing integer with string which is why it will never be correct.
Try, user = int(input("Input a number: "))
On a sidenote, you really shouldn't be using global variables. Learn to use returns especially since you are using functions, otherwise there is no point using functions at all.
Below is a sample code:
import numpy as np
import random
def computer_roll():
return random.randint(4,6)
def user_guess():
return int(input("Input a number: "))
def guess_evaluation():
if user_guess() != computer_roll():
print("You are incorrect.")
else:
print("You are correct.")
again = input("Would you like to play again? ")
if again in ("n"):
print("Thanks for playing.")
else:
guess_evaluation()
guess_evaluation()
For me it works, except for the syntax error at the input field:
def guess_evaluation():
if user != comproll:
print("You are incorrect.")
again = input("Would you like to try again? ")
if again in("y"): # syntax error here, enter space between "in" and "('y')".
user_guess()
elif again in ("n"):
print("Thanks for playing.")
user input curently a string when comproll is a int. You can change this with:
user = int(input("Input a number: "))

Why does it roll the dice even though I say "no" when it asks if I want to do it again?

I was writing a Roll the dice game but when I get the question "Would you like to roll the dice again?" and I say "no" it rolls anyway. I'm guessing it has something to do with the answer variable. However, I would like it to print "maybe next time" instead. Can you help me? Here's my code:
import random
def response():
if answer == "yes" or answer == "Yes" :
rolldice()
else:
print("Maybe next time!")
def rolldice():
randomnumb = random.randrange(1,7)
print("You got number " + str(randomnumb) + "!")
answer = input("Would you like to roll the dice again? \n ")
response()
answer = input("Would you like to roll the dice? \n")
response()
Try this. You have to pass answer as argument to the function response:
import random
def response(answer):
if answer == "yes" or answer == "Yes" :
rolldice()
else:
print("Maybe next time!")
def rolldice():
randomnumb = random.randrange(1,7)
print("You got number " + str(randomnumb) + "!")
response(input("Would you like to roll the dice again? \n "))
response(input("Would you like to roll the dice? \n"))

Categories

Resources