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
Related
i would like to know how to put limit on how many character can player put
thinking to limit it by one letter per answer.
it's a guessing game but the computer can only answer yes or no.
five chances to guess a letter.
then need to guess the right word after 5 tries.
import random
words = dict(
helium = "type of element",
korea="a country in asia",
peugeot="brand of a car",
bournemouth="a good place for holiday")
word=list(words)
choice=random.choice(word)
x=list(choice)
score=0
chance=5
print("\n\n\t\t\t WELCOME TO GUESSING GAME")
print("\t\t\tYOU HAVE 5 CHANCES TO GUESS THE WORD")
print("\nit has a", len(choice),"letters word")
print("and this is a clue", (words[choice]))
while word:
guess = input("is there a letter :")
if guess in choice:
print("yes")
else:
print("no")
score +=1
if score == chance:
print("time to guess the right word")
guess = input("and the word is :")
if guess == choice:
print("well done you guess the right word which is ", choice.upper())
break
else:
print("better luck next time the right word is ", choice.upper())
break
Hope this is what you want:
First you should make a new function:
def own_input(text=""):
user_input = ""
# While the length of the input string is not 1
while len(user_input) != 1:
# Ask user for input with message
user_input = input(text)
Now you can use it like this:
a = own_input("Character: ")
Here's the code I seek to understand. It receives user input, and my concern is that it only works when I type "No", not "no".
houseprice = int(input("please enter the house cost: $"))
while houseprice <= 0:
print("please enter a valid number try again")
houseprice = int(input("please enter the house cost: $"))
familyincome = int(input("please enter your family income: $"))
houseowened = input("have you owened a house before? ('Yes' or 'No')")
while not houseowened == 'Yes' and houseowened == 'No':
print("please enter a valid answer")
houseowened = input("have you owened a house before? ('Yes' or 'No')")
if houseprice > 500000 or familyincome > 100000 or houseowened == 'Yes':
print("eligeble")
else:
if houseowened == 'No' or familyincome < 100000 or houseprice < 500000 :
print("not eligible")
Look at the comparisons in your code. They're comparing against the string "No". If you want it to accept the lowercase form, perhaps you should do something like this everywhere you have houseowned == 'No':
(houseowened.lower() == 'no')
This variation will accept any capitalization. Be sure to make the corresponding change for all yeses.
When comparing strings in pretty much all languages, it is a literal comparison.
So the following code:
if(MyString == "No")
Will only pass if the string is "No" and exactly that. "no", "No ", " no" and other such examples will all not pass the check as they are different.
Most languages offer several tools that can make your life a lot easier on this.
For Python this is called lower(), which will convert all uppercase letters of a string to lowercase.
So "Foo".lower(); will give you "foo"
Second is strip(). This one removes leading and trailing 'whitespace' characters off the ends of the string, so " Foo " will become "Foo"
Using both combined makes checking string values a lot simpler.
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
#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!
while True: #code should only allow integers to be inputed
try:
rolls = int(input("Enter the number of rolls: "))
break
except:
print("You did not enter a valid Integer")
output works for characters like "b" and "d"
but when I put a zero in, I still get the ZeroDivisionError
I want the code to only allow an integer.
later on in the code I tried this
if rolls <= 0:
print("You must enter at least one roll")
print()
but it doesnt stop the code from running and the error still pops up.
There is no division in the posted code and it will not throw a ZeroDivisionError.
The exception is likely thrown when xyz / rolls is done later (outside that try/catch), when rolls evaluates to 0.
Fix the logic so as to not even allow such invalid division to occur! Maybe "0" means to exit the game? Or maybe "0" means that the user should be asked for another roll?
FWIW, here is modified code to read input that won't accept "0":
while True: #code should only allow integers to be inputed
try:
rolls = int(input("Enter the number of rolls: "))
if rolls > 0:
break
except:
pass # don't do anything here, because we print below for
# exceptions and when the if guarding the break failed.
print("You must enter a valid roll (> 0)")