Python Dice Game Issue - python-3.x

I am trying to learn more python, and am trying to created a dice game. My issue, is that when running it in IDLE, it loops after the initial yes to the input. Can anyone give me some tips/help?
If I change
roll = input('Would you like to play a game?')
To
roll = "yes"
All it does start, and end the script immediately.
Here is my full code
import random
min = 0
max = 20
i = random.randint(min,max)
roll = input('Would you like to play a game?')
while roll == "yes":
print ('''
======================================
You run into a deadly demonic intity.
You must role to save your life.
You must role higher than a 10 to win.
======================================
''')
for i in range(1):
print (random.randint(min,max))
if i >= 10:
print ('''Your staff begins to hum as you say your incantation.
The demonic intitiy, begins to shreak with a blood curtling sound.
You stand your ground, and banish it!''')
elif i <= 10:
print ('''You watch in dispair, as the intity devours your friends.
You stand their, with no where to run, knowing that this is the end...''')
if roll == "no":
print ('Guess you could run too...')
I am wanting it to grab the random.randint, and output the responding statement. I also noticed that even though it loops, it completes skips
if i >=10:
And just loops the reply for
elif i <=10:
Even if the random.randint is 20.

A few problems:
You are conditioning on I which is always 0 or 1:
for i in range(1):
This will always be 0 or 1.
Instead you should check the Actual dice roll for example:
dice_value=(random.randint(min,max))
Use raw input instead of input to grab a string and solve the nave error with you yes input.
This code works if you have any other question let me know:
import random
min = 0
max = 20
i = random.randint(min,max)
roll = raw_input('Would you like to play a game? ')
print (roll)
while roll == 'yes':
print ('''
======================================
You run into a deadly demonic intity.
You must role to save your life.
You must role higher than a 10 to win.
======================================
''')
dice_value=(random.randint(min,max))
print ("You Rolled " + str(dice_value))
if dice_value >= 10:
print ('''Your staff begins to hum as you say your incantation.
The demonic intitiy, begins to shreak with a blood curtling sound.
You stand your ground, and banish it!''')
elif dice_value <= 10:
print ('''You watch in dispair, as the intity devours your friends.
You stand their, with no where to run, knowing that this is the end...''')
roll=raw_input('Roll Again?')
if roll == "no":
print ('Guess you could run too...')

Related

Why does this print one input 7 times once executed, rather than get input 7 times?

Earlier when I tested a little bit I could input each time, but now it won't. It's purpose is to see who gets the highest score per round, and decide a winner at the end.
I've gone through my coursework and done a lot googling but can't find the answer. I've been at it for a good few hours now and can't figure it out. I've tried ranges, lists etc, I keep getting infinite loops and can't iterate, get input and repeat.
I even done some single line loops (wouldn't make a difference, just trying anything!) but found it easier to have it line by line while I'm figuring it out. Just set this account up to get some help please.
Where am I going wrong?
Edit: I'm not concerned about strings or floats being added and bugs from that. This is purely integers so it's assumed that's what will be entered.
player_one = 0
player_two = 0
#ask player-one for input
score_one = input("Player one, what is your score?")
#ask player_2 for input
score_two = input("Player two, what is your score?")
#compare who has the highest score and add to counter
while player_one != 7 or player_two != 7 is True:
if score_one > score_two:
print("Player 1 wins the round with ", score_one, "beating Player 2 with", score_two)
player_one += 1
elif score_two > score_one:
print("Player 2 wins the round with ", score_two, "beating Player 1 with", score_one)
player_two += 1
else:
score_one == score_two
print("This round has ended in a draw.")
player_one += 1
player_two += 1
#print winner, loser, scores and also if draw
if player_one == 7:
print("The game has ended with Player 1 winning by ", player_one, "to Player 2's", player-two)
break
elif player_two == 7:
print("The game has ended with Player 2 winning by ", player_two, "to Player 1's", player_one)
break
while player_one == 7 and player_two == 7:
print("DING DING it's a draw.")
break

Issue with checking ranges in if statement

I'm new to python and doing a cyber sec. course, one of the modules is Python.
I am playing around trying to code a number guesser game without a tutorial. Can someone look at this code and tell me why the code doesn't seem to be following the if statements.
Thanks.
EDIT: ERROR: I am trying to create code that will judge which "difficulty" the player has selected by checking which of the ranges it fits into. The issue is, it is printing each of the "difficulty" options, not just the one it fits in to.
EDIT 2: Changed title to be more specific so it may help others.
print("Welcome to the number guesser game!")
tutorial = input("Would you like a tutorial? (Y/N): ")
while tutorial != "Y" or "y" or "N" or "n":
input("Input not recognised, would you like a tutorial? Y (for yes) or N (for no)")
if tutorial == "N" or "n":
print("Let's get right into it!")
if tutorial == "Y" or "y":
print("In this game you will pick a number, the number you pick will be added to a random number between 1 and 20 /nYou will then attempt to guess the number generated, with a hint given every guess")
break
difficulty = input("Please choose a random number \nGuide:\nEasy 1-10\nMedium 1-100\nHard 1-1,000\nExtreme Numbers above 1,000-10,000")
if difficulty >="1" <="10":
print("You have chosen easy! You must be a noob!")
if difficulty >"10" <="100":
print("You have chosen medium! Good choice!")
if difficulty >"100" <="1000":
print("You have chosen hard! Pfft, good luck")
if difficulty >"1000" <="10000":
print("You have chosen extreme! You must be nuts")
if difficulty <="0" >"10000":
difficulty = input("Nice try, pick again: ")
else:
difficulty = input("Input not recognised, please input a number greater than 0: ")```
Explanation
That's because first, if the input is not y, then it will say not recognized.
And it's because, if it's y, it checks the no statement, then it breaks.
That means, It will say both.
Then, it goes strange because you are doing >= with str and str. It will react strange. so you should compare int with int.
Solution
First, use and in the first statement. then, use elif. and use break in the if statement too. and do int(input()) to convert to int. then, you can use elif again. and remove the quotes.
Try this:
print("Welcome to the number guesser game!")
tutorial = input("Would you like a tutorial? (Y/N): ")
while True:
if tutorial != "Y" and tutorial !="y" and tutorial !="N" and tutorial !="n":
tutorial = input("Input not recognised, would you like a tutorial? Y (for yes) or N (for no)")
if tutorial == "N" or tutorial =="n":
print("Let's get right into it!")
break
elif tutorial == "Y" or tutorial == "y":
print("In this game you will pick a number, the number you pick will be added to a random number between 1 and 20 /nYou will then attempt to guess the number generated, with a hint given every guess")
break
difficulty = int(input("Please choose a random number \nGuide:\nEasy 1-10\nMedium 1-100\nHard 1-1,000\nExtreme Numbers above 1,000-10,000"))
if difficulty >=1 and difficulty <=10:
print("You have chosen easy! You must be a noob!")
elif difficulty >10 and difficulty<=100:
print("You have chosen medium! Good choice!")
elif difficulty >100 and difficulty<=1000:
print("You have chosen hard! Pfft, good luck")
elif difficulty >1000 and difficulty<=10000:
print("You have chosen extreme! You must be nuts")
elif difficulty <=0 and difficulty >10000:
difficulty = input("Nice try, pick again: ")
else:
difficulty = input("Input not recognised, please input a number greater than 0: ")
And for the while loop, turn it to while True: then check it with a if statement. then you can check y or n.
First off in the while loop to check if the variable tutorial is "Y" or "y" or "n" or "N" you're doing tutorial != "Y" or "y" or "N" or "n", which is incorrect because it's saying if (tutorial != "Y") or ("y") or ("n") or ("N") and the latter 3 conditions return true because it is a non empty string.
with the if conditions there are 3 problems, first one is the one I just described, second is you're not converting the input to integer before checking, third is that you're nesting the conditions unnecessarily.
Simplify your checking, and do it in a loop so they cannot progress if they enter invalid input:
difficulty = -1
while difficulty < 1 or difficulty > 10000
try
difficulty = int(input("Please choose a difficulty.\nGuide:\nEasy 1-10\nMedium 1-100\nHard 1-1000\nExtreme 1000-10000\n: "))
except ValueError:
print("not a number")
if difficulty > 0 and difficulty <=10:
print("You have chosen easy! You must be a noob!")
elif difficulty<=100:
print("You have chosen medium! Good choice!")
elif difficulty<=1000:
print("You have chosen hard! Pfft, good luck")
elif difficulty<=10000:
print("You have chosen extreme! You must be nuts")
You don't need each elif to make sure the number is greater than the end of the range of the check before; if it wasnt then that elif would have been true, not this one. In other words, if youre playing a guessing game with another human and you say "is the number less than or equal to 10" and they say no, you don't need to say "is it greater than 10 and less than.. " because the "greater than" is implied - it has to be greater than because it isn't less than or equal to

How can I not allow letters, and only allow numbers in an input on python 3?

I am a beginner. I'm making a survey, and one of the questions asks the users age. How can I make it so that if the user enters a letter or symbol, it shows a print() message?
The issue seems to be that the computer reads the first if statement of "if age < 10:" and then sends an error message in the terminal if I enter a string.
This is the code right now, I want it so that if the user inputs a letter(s) or symbol(s), it sends a print() message, and asks for the input again, is that possible?
c = 3
while c == 3:
age = int(input('How old are you (enter a number)? '))
if age < 10:
print("Wow, you're quite young!")
break
elif age > 60 and age <= 122:
print("Wow, you're quite old!")
break
elif age > 122:
print('Amazing! You are the oldest person in history! Congrats!')
break
elif age >= 14 and age <= 18:
print('Really? You look like a college student!')
break
elif age >= 10 and age <= 13:
print('Really? You look like a 10th grader!')
break
elif age > 18 and age <= 60:
print('Really? No way! You look younger than that, could have fooled me!')
break
Define each operation in your survey as a different function. Then you can use a statement like this one:
try:
int(input_variable)
except ValueError:
function()
To check if they gave you an integer, and if they didn't they have to input again. You seem to be a beginner so I can answer questions if you have any.
for simple solution, simply loop until integers are received.
while True:
try:
age = int(input('How old are you (enter a number)? '))
except ValueError:
print('input should be integer!')
continue
break

My randomNumber generator play again acts weird

Now this is pretty beginner version of randomNumber guessing quiz code in Python. Many of you can look at it and make it 4 times shorter and I get it. However the point of this question is that I am unsure of the logic behind this problem.
If you execute this code, it will work just fine - till you get to Play again part.
When you type No - the program as intended quits. Yes starts again.
However if you type Yes first and the game goes one more time and you decide that it is for now I want to quit - this time you have to enter No twice.
And then it quits. I have no idea why. Ideas?
import random
def game(x,y):
con = True
count = 0
ranNum = random.randint(x,y)
while con:
userInput = int(input("Take a guess between these numbers {} and {}: ".format(x,y)))
count +=1
if userInput == ranNum:
print("You got it!")
print("Number of tries: {}.".format(count))
print("Play again?")
while True:
again = input("> ")
if again.lower() == "yes":
game(x,y)
elif again.lower() == "no":
con = False
break
elif userInput < ranNum:
print("Wrong! Try higher!")
elif userInput > ranNum:
print("Wrong! Try lower!")
game(5,10)
The simplest solution: You need a break or return after calling game() when the user answers 'yes'.
This has an unfortunate side effect where each successive game adds another call to the stack. A better design would move the 'play again?' question out of the game function.
The problem is you are running game(x, y) inside itself. Therefore, con is a local variable. Think of it this way: when you type no the first time, it exits out of the game(x, y) that is running inside game(x, y) Therefore, the number of times you have played is the number of times you need to type no. An easier way to do this would be, like #xulfir says, put the "Play again?" loop outside of the function, or you could put exit() instead of using break to just kill the program.

Option to save output printed on screen as a text file (Python)

Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break

Resources