Get rid of some output - python-3.x

#The program is as below.
The program allows user to try two times to guess two lottery numbers.
If user guesses i number correctly,user gets $100 and one more chance to play. If in the second chance the user guesses one number again, user gets nothing more.
import random
guessed=False
attempts=2
while attempts > 0 and not guessed:
lottery1= random.randint(0, 99)
lottery2= random.randint(45,109)
guess1 = int(input("Enter your first lottery pick : "))
guess2 = int(input("Enter your second lottery pick : "))
print("The lottery numbers are", lottery1, ',', lottery2)
if guess2==lottery2 or guess1==lottery1:
print("You recieve $100!, and a chance to play again")
attempts-=1
if (guess1 == lottery1 and guess2 == lottery2):
guessed=True
print("You got both numbers correct: you win $3,000")
else:
print("Sorry, no match")
the output is as below:
Enter your first lottery pick : 35
Enter your second lottery pick : 45
The lottery numbers are 35 , 78
You recieve $100!, and a chance to play again
Sorry, no match
Enter your first lottery pick : 35
Enter your second lottery pick : 45
The lottery numbers are 35 , 45
You recieve $100!, and a chance to play again
You got both numbers correct: you win $3,000
Sorry, no match
I want to get rid of the line " You recieve $100!, and a chance to play again" when user guesses both numbers correctly and in the second attempt if user guesses one number correct. I hope that makes sense

I assume that indentation of the code snippet you have here is the same you have in your IDE. As you can see your else statement is not indented correctly. So first you have to check how many matches do you have, I would suggest you to use a list of your lottery numbers and then check against user guesses to see how many matches, this way your code will be more flexible. If both numbers matches, if not test if at least one matches, if none of them show them the Sorry, no match message.
So the code should look like :
matches = 0
lottery = [random.randint(0, 99), random.randint(45,109)]
guesses = [guess1, guess2]
for guess in guesses:
if guess in lottery:
matches+=1
# so now we know how many matches we have
# matches might be more than length of numbers in case you have the the same numbers in lottery
if matches >= len(lottery):
guessed=True
print("You got both numbers correct: you win $3,000")
elif matches == 1:
print("You receive $100!, and a chance to play again")
else:
print("Sorry, no match")
attempts-=1
Hope it was helpful!

Related

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

Creating a continues loop with try | Python3

I'm trying to receive user input that has to be between 2 and 10 and then return a message if the input is in fact between 2 and 10.
What I'm struggling with:
if the user inputs something other than a number, I get a ValueError
How I'm trying to resolve it:
I use the try except finally method.
Issue I'm unable to resolve:
When the user inputs a letter, the first time around, it will bring up the try: but if the user then inputs a letter a second time, it will give an error once again.
How can I make this loop so the user can give as many wrong answers as he wants and get it to it's final destination once he inputs a value between 2 and 10?
My code so far
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
except ValueError:
print(f"That wasn\'t a number! Try again.")
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
finally:
print("Good, welcome to the dark side.")
Would appreciate the help!
Thanks.
This example works, while making minimal changes to your code:
while True:
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
break
except ValueError:
print(f"That wasn\'t a number! Try again.")
print("Good, welcome to the dark side.")
The main differences are removing the while loop from within the except and the finally portion, and using a while True loop to continue asking the question until the conditions are met that lead to the break (i.e. user enters a value between 2 and 10, inclusive). My test of this code works.

How to re-ask a user for input when they input wrong data the first time

I am checking to make sure that the zoo can let a ship travel with animals, in order to do this the closest person to the zoo must be at least 60 meters away due to safety reasons. I am using the code below
#Ask them how far away the closest person is from the ship
while True:
try:
Distance = int(input("How far away is the closest person
from the ship? (in meters) "))
except ValueError:
print("Please enter a number")
continue
else:
break
if Distance <=60:
print("Please ask them to move away")
else:
print("People are at a safe distance")
I want to make it so that the question re-asks when they put in a distance that is too low, so then they can check again and put in the new distance
I want it to look like :
How far away is the closest person from the ship (in meters)? 8
Please ask them to move away
How far away is the closest person from the ship (in meters)? 789
People are at a safe distance
make ask() into a function. call it from an infinite loop. The loop would only break (stop calling ask()) if the Distance is > 60.
def ask():
while True:
try:
Distance = int(input("How far away is the closest person from the ship? (in meters) "))
except ValueError:
print("Please enter a number")
continue
else:
break
return Distance
while True:
if ask() <=60:
print("Please ask them to move away")
else:
print("People are at a safe distance")
break

Python Dice Game Issue

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...')

Resources