I'm new to python so I decided to make a simple dice game using a while loop just to do a simple test of myself. In the game, I use the module random and the method random.randint(1, 6) to print a random integer of any value from "1 to 6", which is evidently how a dice works in real life. But to make this a game, if the integer that is printed is even (random.randint(1, 6) % 2 ==0) then 'you win' is printed. If the integer is odd, then 'you lose' is printed. After this, the console asks if you want to roll the dice again, and if you say yes (not case sensitive hence .lower()) then it rolls again and the loop continues, but if you say anything else the loop breaks.
I thought this is was how it would work, but every now and then, when an even number is rolled, 'you lose' is printed, and the opposite for odd numbers, which is not what I thought I had coded my loop to do. Obviously I'm doing something wrong. Can anyone help?
This is my code:
import random
min = 1
max = 6
roll_again = True
while roll_again:
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
Those are two separate calls to randint(), likely producing two different numbers.
Instead, call randint() once and save the result, then use that one result in both places:
roll = random.randint(min, max)
print(roll)
if roll % 2 == 0:
print('you win')
You are generating a random number twice, the number printed isn't the same the number as the one you are checking in the if condition.
You can save the number generated in a variable like this to check if your code is working fine :
import random
min = 1
max = 6
roll_again = True
while roll_again:
number = random.randint(min, max)
print(number)
if number % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
You need to assign random number to a variable, right now printed and the other one are different numbers.
import random
min = 1
max = 6
dice = 0
while True:
dice = random.randint(min, max)
print(dice)
if dice % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
random.randint(min,max) returns different value every time it is executed. So, the best thing you can do is store the value at the very first execution and check on that stored value for Win or Loss.
You can try this version of code:
import random
while(True):
value = random.randint(1,6)
print(value)
if(value % 2 == 0):
print("You Win!")
else:
print("You Lose!")
again = input("Want to roll Again? Type 'Yes' or 'No'")
if(again.lower() != 'yes'):
break
Related
I am trying to insert code at the end of my game to either restart or end the game. I'm not quite sure what I'm missing here.
This is where I'm at:
print("NIM: The Python Game")
print("Hello! My name is AI (the clever computer). \nIn this game, 2 other players will play against me and each other. \nThe player to go first will randomly choose between 30 and 50 stones in a pile to start the game.")
print("She\He will also be the first to remove the first stones. \nPlayers will then take turns at removing between 1 and 3 stones from the pile until a player removes the final stone. \nThe player to remove the final stone is the winner.")
player1=str(input("\nPlayer 1, what is your name and MIT ID? "))
print("Hello, " + player1.capitalize())
player2=str(input("\nPlayer 2, what is your name and MIT ID? "))
print("Hello, " + player2.capitalize())
player3="The computer"
howMany=0
stonesNumber=0
while True:
stonesNumber=int(input("\nNEW GAME \nHow many stones do you want to start with (between 30 and 50), " + player1.capitalize() + "? "))
if stonesNumber <30:
print("The number must be between 30 and 50!")
elif stonesNumber >50:
print("The number must be between 30 and 50!")
else:
print("The number of stones is ", stonesNumber)
while True:
print("\nIt's your turn, ",player1.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
print("Numbers of stones left: " + str(stonesNumber))
if stonesNumber==0:
print(player1.capitalize()," wins.")
break
print("\nIt's your turn, ",player2.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
if stonesNumber==0:
print(player2.capitalize()," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nIt's my turn!")
if stonesNumber % 3==0:
howMany=2
else:
howMany=1
stonesNumber=stonesNumber-(howMany)
if howMany == 1:
print("The computer has taken 1 counter")
if howMany == 2:
print("The computer has taken 2 counters")
if stonesNumber==0:
print(player3," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nThe game is over!")
answer=str(input("\nDo you want to play again?(y/n)"))
if answer == "y" or "yes":
print("\nRestarting the game")
else:
break
print("\nThanks for playing the game!")
The condition if answer == "y" or "yes": does NOT check if answer equals "y" or equals "yes". Due to semantics of OR-Operator it "transposes" to a piece of code like if "yes":, which is always true. Therefore it will always restart your game.
You will need to change it to that:
if answer == "y" or answer == "yes":
I am assuming the problem you are having now is that you cannot escape the loop regardless of what you answer at the end of the game.
The reason your game can never escape the while loop is because of this line
if answer == "y" or "yes":
Your above if statement is made up of two parts:
if answer == "y" (Evaluates to true or false depending on answer)
if "yes" (Evaluates to true every time)
Since its an OR case, where either the result will be true/false OR true, you will always end up with if answer == "y" or "yes" as true.
Therefore, you will always be stuck in the loop.
As per felix's answer, your solution would be to evaluate if answer == "y" OR answer == "yes" instead
I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break
I am having this annoying problem with if/elif statements. I'm a newbie, sorry for dumb question. I tried finding a fix but no one had it for Python.
So, I want the program to execute the code in the if clause if both conditions are True. As far as I know the code in the clause will only execute if both the conditions are True, am I right? That doesn't seem to happen in my code, though.
result = userNumber + randomNumber
if not result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is even, so you lost :(')
So, the userNumber and the randomNumber variables were set before. In this game, what happens is: the user chooses even or odd, and inputs a number from 0 to 5. Then, the computer randomly chooses a number from 0 to 5, using random.randint().
After that, the variable result is set to the sum of userNumber + randomNumber. If the result of that sum is odd and the user chose odd, the user wins, and if the user chose even, the user loses. If the sum is even it's exactly the opposite: if the result of the previous sum result is even and the user chose even, the user wins, and if the user chose odd, the user loses.
I hope you understand!
So, the problem with my code right now is that it executes all four IF statements for some reason, so the final output looks like this:
Welcome to the Even or Odd game!
Type letter 'o' if you want odd and the letter 'e' if you want even.
Your choice: o
Now, type in a number from 0 to 5: 2
Your number: 2
Computer's number: 5
Adding these two numbers together, we get 7
That number is odd, so you lost :(
That number is even, so you won :)
That number is odd, so you won :)
That number is even, so you lost :(
The code for that is:
import random
import time
print ('Welcome to the Even or Odd game!')
print ('Type letter \'o\' if you want odd and the letter \'e\' if you want even.')
userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = int(input('Now, type in a number from 0 to 5: '))
randomNumber = random.randint(0,5)
time.sleep(2)
print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)
result = userNumber + randomNumber
print (str(result))
print ('Adding these two numbers together, we get ' + str(result))
if not result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is even, so you lost :(')
Any ideas? Sorry for long post, and sorry if duplicate! I just didn't find any answers around the internet :/ Thank you so much!
EDIT: I also tried using elif statements instead of all if, didn't work either.
>>> if False or 'even':
... print('This shouldn\'t work')
...
This shouldn't work
The truth value of a non-empty string is True. Although your other conditions are False, you're still executing those statements because of the way you've written your condition.
As it stands, this is how your condition is evaluated:
if (not result % 2 == 0) and ((userChoice == 'e') or ('even')):
# __________1________________________2_________________3_____
(1) is True. (2) is False. But (3) is True (because of the truthiness of strings). So you execute the first if.
What's more, you only want one of these conditions to execute. Not all of them. You'll need to replace your second if and onwards with elif. So, if one condition is True, all the other conditions are skipped.
You'll need to make a small change:
if not result % 2 == 0 and userChoice in ['e', 'even']:
...
elif result % 2 == 0 and userChoice in ['e', 'even']:
...
elif not result % 2 == 0 and userChoice in ['o', 'odd']:
...
elif result % 2 == 0 and userChoice ['o', 'odd']:
...
print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?
First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.
The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM
first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU
Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.
Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.
This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")
This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()