I'm pretty new to programming and trying to make a dice roll simulator in Python. My code is sort of a combination of two other dice programs I saw. I'm having trouble trying to get quit and re-roll working. I'm using Python 2.7.9 Any tips?
import random
def rollDice():
return random.randint(1,6)
closeProgram = 0
print "Welcome to dice simulator."
print " "
while closeProgram != "q":
numTimes = input("Enter number of dice rolls: ")
for i in range(numTimes):
print rollDice()
print "Press 'q' to quit or 'enter' to roll again."
closeProgram = input()
You need to use raw_input:
closeProgram = raw_input()
input in python 2 is basically eval(raw_input()) which apart from the fact it is not going to work is also a security risk.
You can cast the input to an int instead of using input:
while closeProgram != "q":
numTimes = int(raw_input("Enter number of dice rolls: "))
for i in range(numTimes):
print rollDice()
closeProgram = raw_input("Press 'q' to quit or 'enter' to roll again.")
You should also use a try/except to catch user input that cannot be cast:
while closeProgram != "q":
try:
numTimes = int(raw_input("Enter number of dice rolls: "))
except ValueError:
print("Integer values only allowed")
continue
for i in range(numTimes):
print rollDice()
closeProgram = raw_input("Press 'q' to quit or 'enter' to roll again.")
Related
I'm trying to make a lottery program that can output results after a user inputs their numbers. But I want the option to allow the user to also be able to pick "how many weeks they play for", that being, how many times the program outputs results that are randomized. Basically use the numbers they inputted to play multiple games of lottery with the same numbers x amount of times they wish. I want to know how to make my function repeat based on how many times they wish to play.
Here's my incomplete code.
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
MONEY_WON = 10000
OFFSETT = 4
USER = input("Please enter your name:")
print("Hi " + USER + " good luck ")
WEEKS_PLAYED = input("How many weeks do you want to play: ")
def verify(playerNumbers, winningNumbers):
if playerNumbers == winningNumbers:
print("Congratulations! You Win ${}!".format(MONEY_WON))
print("Your numbers: ", playerNumbers, )
print("The winning lottery numbers were: ", winningNumbers)
else:
print("Sorry, you lose...")
print("Your numbers: ", playerNumbers)
print("The winning lottery numbers were: ", winningNumbers)
# 'get_user_nums', gets user numbers and puts into a sorted list for x in WEEKS_PLAYED:
def get_user_nums():
user_nums = []
while len(user_nums) < NUMBER_OF_PICKS:
nums = input("Pick a number {} through {}: ".format(MINIMUM_SELECTION, MAXIMUM_SELECTION))
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continue
if MINIMUM_SELECTION <= nums <= MAXIMUM_SELECTION:
if nums not in user_nums:
user_nums.append(nums)
else:
print("Sorry, you have already inputted that number")
else:
print("Sorry, Your number was not in range")
return sorted(user_nums)
# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
return sorted(random.sample(range(MINIMUM_SELECTION, MAXIMUM_SELECTION), NUMBER_OF_PICKS))
# 'menu', creates the main menu to choose game or exit program
def play_pick_n():
user_nums = get_user_nums()
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
# 'main', calls the other functions
def main():
# lottery_menu()
while True:
choice = input("\nPlay?: Yes or No: ")
if choice == 'Yes':
string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
dotted = '\n' + len(string) * "-"
print(dotted, string, dotted)
play_pick_n()
break
elif choice == 'No':
print("Thanks for playing!\n")
break
print("Sorry, that is not a valid input. \nPlease enter either Yes or No")
if __name__ == '__main__':
main()
Thanks for any help.
if you ant to use the same numbers for all weeks, use:
user_nums = get_user_nums()
for week in range(0, WEEKS_PLAYED):
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
You might want to move the question for the number of weeks inside your play_pick_n function, so the player can decide per bunch of numbers who long they should run.
I am trying to restart this program if what the user gets from picking the two numbers from the dice roll is already gone from the overall list. It will ask them to roll again and everything that just happened will go back like they never clicked 'e'.
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid ----- Please enter 'e' to roll the dice")
# Add in the invalid input error
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
while True:
sum1 = dice_choose + dice_choose1
if sum1 in lst_player:
break
else:
print("You have made an invalid choice")
sum1 = dice_choose + dice_choose1
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
If you want to repeat code until some conditions are met, you can use a while True loop or while <condition> loop, using continue (continue to the next iteration) to "reset" when some invalid situation is reached:
while True:
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid input")
continue # Go back to asking the player to roll
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
sum1 = dice_choose + dice_choose1
if sum1 not in lst_player:
print("You have made an invalid choice")
continue # Go back to asking the player to roll
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
break # Break out of the loop
I'm not entirely sure how this code is intended to work, but you may need to move blocks around and/or reset dice before continue.
So I've remade part of my dicegame's code and it's works somewhat decently, however after ROLL'ing the dice and attempting to display the users score, I run in to an error where is says 'name p1_score is not defined'. It says the same thing for the variable p2_score aswell. However I defined p1_score as ran_num+ran_num so I don't get why I'm getting an error.
import random
import time
player_1 = input("")
player_2 = input("")
def rollDice(player_1):
ran_num = random.randint(1,6)
if ran_num == 1:
print("You rolled a",ran_num)
else:
print("You rolled a",ran_num)
p1_score = ran_num+ran_num
def rollDice(player_2):
ran_num = random.randint(1,6)
if ran_num == 1:
print("You rolled a",ran_num)
else:
print("You rolled a",ran_num)
p2_score = ran_num+ran_num
print("Please press ENTER to roll the dice")
input()
rollDice(player_1)
print("Good job",player_1,)
print("Your score is now",p1_score)
time.sleep(5)
print(player_2,"Press ENTER to roll the dice")
input()
rollDice(player_2)
print("Nice work",player_2)
print("Your score is now",p2_score)
def main():
rollDice(player1, player2)
main()
This is a variable scoping issue, you either need to use a global (globals can be dangerous if used incorrectly) the same way you have with player_1 and player_2, OR return from that function and use the returned value for the output.
http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html
"Not affiliated with that website, just did a quick google to see if I could find a resource for you to read so you can understand"
import random
import time
def rollDice():
ran_num = random.randint(1,6)
print("You rolled a " + str(ran_num))
raw_input()
resolved_score = ran_num+ran_num
return str(resolved_score)
player_1 = raw_input("Enter player one name: ")
player_2 = raw_input("Enter player two name: ")
print("Please press ENTER to roll the dice")
raw_input()
p1_result = rollDice()
print("Good job "+player_1)
print("Your score is now "+p1_result)
time.sleep(5)
print(player_2+" Press ENTER to roll the dice")
raw_input()
p2_result = rollDice()
print("Nice work "+player_2)
print("Your score is now "+p2_result)
I've rationalised your code a bit, there were some logic errors. Notice in the def I have a return statement, the return statement adds two numbers together, converts it to a string using str() and I use RETURN to spit the value back out to the calling code. In this case the calling code is first encountered where we see:
p1_result = rollDice()
Now p1_result will equal whatever the ran_num+ran_num resolved to inside the function.
#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)
Alright, I'm doing this for a project and whenever I attempt to have it divide by zero or square root a negative number that program closes out. I've attempted to find something I can insert into the code to make it display a message and then prompt for the value again, but everything that I've tried inserting causes the program to close out instantly when I start it up.
Here's the calculator without anything inserted to fix the crashes.
import math
def convertString(str):
try:
returnValue = int(str)
except ValueError:
returnValue = float(str)
return returnValue
def addition(a, B):
return convertString(a) + convertString(B)
def subtraction(a, B):
return convertString(a) - convertString(B)
def multiplication(a, B):
return convertString(a) * convertString(B)
def division(a, B):
return convertString(a) / convertString(B)
def sqrt(a):
return math.sqrt(convertString(a))
keepProgramRunning = True
print "Welcome to [Removed]'s 2011 4-H Project! This is a simple calculator coded in Python, which is a high-level programming language. Java, C, C++, and Perl are other high-level programming languages that you may have heard of."
while keepProgramRunning:
print ""
print "Please choose what you would like to do:"
print ""
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Square Root"
print "6) Quit Program"
choice = raw_input()
if choice == "1":
numberA = raw_input("Enter your first addend: ")
numberB = raw_input("Enter your second addend: ")
print "The sum of those numbers is:"
print addition(numberA, numberB)
elif choice == "2":
numberA = raw_input("Enter your first term: ")
numberB = raw_input("Enter your second term: ")
print "The difference of those numbers is:"
print subtraction(numberA, numberB)
elif choice == "3":
numberA = raw_input("Enter your first factor: ")
numberB = raw_input("Enter your second factor: ")
print "The product of those numbers is:"
print multiplication(numberA, numberB)
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
print "Your result is:"
print sqrt(numberA)
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
keepProgramRunning = False
else:
print "Please choose a valid option."
print "\n"
I'm not real sure what to insert and where to solve the crashes, but I think the problem lies with my placement.
I've been attempting to insert something like this:
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
Would that work? Where would I insert it? If it wouldn't work, what would and where would it go?
I've been attempting to put it after
numberB = raw_input("Enter your divisor: ")
So that section would read
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
But as I said, the program will close as soon as it opens when I do try that. Also, I know that if they inputted 0 again the program would crash. Is there any way to make it return to the line that it's under?
Also, for closing the program, the message it is supposed to display can't be read as the program is closing immediately after it's displayed, or the commands are being executed at the same time. Either way, the message can't be read. Is there any way to make the message appear in a separate dialog window that will cause the program to close when the window is closed? Or at least a way to make it delay before closing?
Please correct me if I got any terminology wrong. I'm still somewhat new to this.
And, as always, (constructive) feedback for any part of the program is always appreciated.
The problem is that you are trying to catch an exception before it is thrown. Instead, try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
while float(numberB) == 0:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
Here's your answer without exception handling.
Essentially you just make this questionable input at the beginning of an infinite loop, but break out when you find that the input is all good.
For your square root:
elif choice == "5":
while True:
numberA = raw_input("Enter the number you wish to find the square root of: ")
if float(numberA) >= 0:
break
print "Cannot take the square root of a negative number."
print "Your result is:", sqrt(numberA)
and for division:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
while True:
numberB = raw_input("Enter your divisor: ")
if numberB != "0":
break
print "You cannot divide by zero. Please choose another divisor."
print "The quotient of those numbers is:", division(numberA, numberB)
And to make your program stall before it closes:
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
raw_input('')
keepProgramRunning = False
Cheers!
You should use exceptions, like you're already doing in convertString.
try:
result = division(numberA, numberB)
print "The quotient of those numbers is:"
print result
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."
Your format of the try:...except: statement is wrong. Try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
try:
print division(numberA, numberB)
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."
This does not answer your coding question, but I think it is worth to comment.
sqrt: The square root of a negative number is an imaginary number. Python supports complex numbers with complex(real_part, imaginary_part).
so your sqrt calculation could be written as:
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
numberA = float(numberA)
if numberA < 0:
sqrt_numberA = complex(0, sqrt(abs(numberA)))
else:
sqrt_numberA = sqrt(numberA)
print "Your result is:", sqrt_numberA
division: A division by 0 is infinite. Python indicates infinite with 'inf'. In fact, it returns 'inf' with numbers higher than 1E309:
>>> 1E309
inf
and the division of two of these numbers produces 'nan'
>>> 1E309/1E309
nan
so that you could write:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
try:
div = division(numberA, numberB)
except ZeroDivisionError:
div = 'inf'
print "The quotient of those numbers is:", div
this code should be additionally extended to return -inf, when numberA is negative, and to take into account situations such as 0/0