Python - When number is equal to or above question - python

I am trying to write a simple script that will give a random number between 1 and 100 and print out either "you win" or "you lose" based on the result. When testing for the specific number like == 1 it works fine, but when replacing it with <= it gives me this error: TypeError: '<' not supported between instances of 'NoneType' and 'int'
Here is my code:
import random
number = print(random.randint(1, 100))
if number <= 20:
print("you win")
else:
print("you lose")

print always returns None, so don't assign the return value of print to number. Do it in two steps:
import random
number = random.randint(1, 100)
print(number)
if number <= 20:
print("you win")
else:
print("you lose")

You have to first store the variable you get from the random:
number = random.randint(1, 100)
You can they print it, and compare it in your "if":
print(number)
if number <= 20:
...
The print function does not return the variable you want.

Related

How to re-run through loop when exception happens in Python?

When executing this it only runs through the initial if elif statement. If I reach 0 it returns the proper print statement along with when I'm subtracting numbers. However if I try to subtract to reach a negative number and therefore reach the exception, it doesn't print the statement below and reloop through like I want it to.
number = 15
print("Subtract the number", number, "until it has reached 0")
while number != 0:
try:
x = int(input())
number = number-x
if number > 0:
print("You have", number, "points to spend!")
elif number == 0:
print("You have used all your points!")
break
except number < 0:
print("You don't have enough points for that!")
continue
except is used for catching errors. You want this:
while number != 0:
x = int(input())
if number - x > 0:
number -= x
print("You have", number, "points to spend!")
elif number == x:
number = 0
print("You have used all your points!")
break
else:
print("You don't have enough points for that!")

How do I keep track of a user's guesses in Python? attempts= attempts + 1 is not working

I need to keep track of the number of guesses a user inputs in a simple guessing game.
I have tried using attempts= 0 and then setting attempts to = attempts + 1. Even when I do this, the code will print "You have guessed in 1 attempts" even when the user has guessed in more attempts than one.
Code:
attempts = 0;
print("Hello, welcome to the game. You will be choosing a number
between 1 and 100. You can only guess up to 10 times.")
for tries in range(tries_allowed):
print("You only get 10 tries.")
break
while attempts < 10:
guess = int(input("Please guess a number"));
attempts_used= attempts + 1;
if guess > random_number:
print("Guess is too high, try a smaller number");
elif guess < random_number:
print("Guess is too low, try a higher number");
elif guess == random_number:
attempts_used=str(attempts_used)
print("Correct- you win in", attempts_used, "guesses");
exit();
else:
if tries_allowed == 10:
print("You failed to guess in time")
my_list= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.append(attempts_used)
print(my_list)
You never update the attempts variable, you've created a new one called attempts_used, you don't need to do this.
Just use attempts everywhere you're using attempts_used
Note: Whilst you're at it you should get rid of what is known as a "magic number", or a hard coded limit in your while loop
while attempts < tries_allowed:
Cleaned up your code a bit, shows the += counting method working for your script.
As others have said, the original code is creating an entirely new variable attempts_used that is simply attempts + 1, and attempts remains 0.
It could also be attempts = attempts + 1, += means the same thing.
To make a int a str in python for printing purposes, it does not need to be stored to a separate variable, just call str() around it, unless you plan to use the string separately.
import random
random_number = random.randint(1,100)
attempts = 0
tries_allowed = 10
print("Hello, welcome to the game. You will be choosing a number between 1 and 100")
print("You only get " + str(tries_allowed) + " tries.")
my_list = []
while attempts < tries_allowed:
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You have already guessed " + str(guess))
continue
attempts += 1
my_list.append(guess)
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
elif guess == random_number:
print("Correct- you win in", str(attempts), "guesses")
break
else:
if attempts == 10:
print("You failed to guess in time")
for item in my_list:
print(item)
Your "attemps" variable stays on 0, so attemps_used(attempts + 1) will always be 1. You have to merge both of the variables in only one in order to control it (attempts=attempts+1)
Code which also checks previous input and prints a message.
import random
# Hello World program in Python
attempts = 0
print("Hello, welcome to the game. You will be choosing a number between 1 and 100. You can only guess up to 10 times.")
random_number = random.randint(1, 101)
#print(random_number)
my_list= []
for tries in range(10):
print("You only get 10 tries.")
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You already guessed this number!!")
my_list.append(guess)
attempts += 1
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
else:
print("Correct- you win in", tries + 1, "guesses")
attempts = -1
break
if attempts is 10 and attempts is not -1:
print("You failed to guess in time")
print("Attempts : ", my_list)

Incorrect if-else statements

I've been trying to write a function that will ask for a number between 1-11 and will randomly choose a number and will compare between them.
I can't figure out why no matter what number I type in (equals or smaller or bigger) it will always type the "Your number is less" message.
def loto():
_number = int(input("Enter any number between 1-10: "))
import random
for x in range(1):
print ("Python chose: " + str(random.randint(1,11)))
if ("_number" == "random"):
print ("You Won! :)")
if ("_number" < "random"):
print ("Your number is less")
if ("_number" > "random"):
print ("Your number is more")
else:
print ("You Lost :(")
loto()
I'm using Python 3.
Thanks:)
Your first problem is that you're comparing the strings "_number" and "random". ASCIIbetically (or, rather, Unicoderifically), "_number" < "random", because the _ character is #95 and the r character is #114.
If you want to compare two variables, you just refer to the variables, not strings that happen to be the same as the names of those variables.
Your second problem is that random isn't your random number, it's the module you used to create that number. And, more seriously, you aren't storing that number anywhere—you're just converting it to a string to print it out and then throwing it away.
Your third problem is that you need to change those ifs to elifs. Otherwise, the You Lost message gets printed whenever _number > random is not true, instead of only whenever all of the three comparisons are not true.
Putting that all together:
choice = random.randint(1,11)
for x in range(1):
print ("Python chose: " + str(choice))
if (_number == choice):
print ("You Won! :)")
elif (_number < choice):
print ("Your number is less")
elif (_number > choice):
print ("Your number is more")
else:
print ("You Lost :(")
Of course there's no way to actually lose your game—one of the three conditions is always going to be true. (If you were using complex numbers, or floats including NaN, you could input a number that wasn't comparable in any way to the selected one, but you're not.)
While we're at it:
There's no reason to name your variable _number instead of number.
That for x in range(1): loop doesn't do anything useful—it loops exactly once, setting x to 0, which you never use.
You don't need parentheses around your conditions.
You shouldn't import modules in the middle of a function like that except in special cases where you need unusual things like lazy loading.
You should follow PEP 8 style, or at least pick a consistent style to follow.
It's simpler to just pass multiple arguments to print, or to use string formatting, than to manually convert things to strings and concatenate them.
So:
import random
def loto():
number = int(input("Enter any number between 1-10: "))
choice = random.randint(1, 11)
print("Python chose:", choice)
if number == choice:
print("You Won! :)")
elif number < choice:
print("Your number is less")
elif number > choice:
print("Your number is more")
else:
print("You Lost :(")
loto()
You were comparing strings not variables, you need to remove quotes, and you not saved random number into a variable. The for loop is making one repetition only, you can remove it.
Update your cod like this:
import random
def loto():
_number = int(input("Enter any number between 1-10: "))
rand_number = random.randint(1,11) # can't had the same name as random
if (_number == rand_number):
print ("You Won! :)")
elif (_number < rand_number):
print ("Your number is less")
elif (_number > rand_number):
print ("Your number is more")
else:
print ("You Lost :(")
loto()

Guess Random Number Why i m not able to enter input - python

Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).

How do I make my program check whether user input is within 5,10,15,20, etc of the random integer?

import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if userInput > randomNumber:
print("Guess lower.")
elif userInput < randomNumber:
print("Guess Higher.")
else:
print("You got it!")
break
So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer.
So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher."
Any advice? I'm extremely new to python, so please respond with more simple methods if possible.
Thanks.
PS: Oh, preferably without the use of modules, mainly because I'm still learning.
I think this does what you want, and it cuts down on the if chains a little:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
break # We use break b/c changing correct would still run rest of loop
acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
guess_error = userInput - randomNumber
i = 0
while abs(guess_error) > acceptable_ranges[i]: # see how close they are
i += 1
if guess_error < 0: # let's figure out where they need to go
next_guess_direction = "higher"
else:
next_guess_direction = "lower"
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
Let's look. at the last if statement a little further and the final print line. We are checking to see if guess_error, defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative). If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one (randomNumber was larger than userInput. If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using:
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower." Finally, we print out everything that we have found:
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively. I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction), which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string. Keep in mind, we found i in acceptable_ranges[i] right above the if statement.
I know that is all long, but I did not know how much detail you needed!
Update: I see you ask to do it without modules. Here's a solution:
def ceil(xx):
if int(xx) < xx:
return int(xx) + 1
else:
return int(xx)
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / float(interval)
within = ceil(abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
-- original answer:
You can do this with numpy's ceil function.
For instance:
import numpy as np
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / np.float(interval)
within = np.ceil(np.abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
A solution using the modulo operator:
import random
randomNumber = random.randint(0,100)
def guess(divisor = 5):
while 1:
try:
print("Pick a number from 0-100")
userInput = int(input("Insert your number here: "))
except ValueError:
print("That is not a Number!")
continue
delta = randomNumber - userInput
if delta == 0:
print("You got it!")
return
remainder = delta % divisor
# this takes advantage of python truncating non-floating point numbers
rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)
high_or_low = 'higher' if delta > 0 else 'lower'
print("You are within %s. Guess %s." % (rounded_delta, high_or_low))

Categories

Resources