How to re-run through loop when exception happens in Python? - 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!")

Related

Determinate loop and Indeterminate Loops in Python

I need to show "Determinate loop" and "Indeterminate Loops" on this code. (nested)
This is a simple code, pick a random number, and gives you 2 opportunities to guess the number, if you can't, it will let you know what the magic number was and start the game again.
questions:
is there any other way to make the game start over? like a while or nested loop.
can I get an opinion if it is enough?
the problem with the code is, every time you make a guess, it prints
"Can you guess the magic number?"
how can it print that only at the beginning of the code and then only prints:
"try a lower number"
"try a higher number"
I feel like the code is not nested enough, anyway I can make it more professional?
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
while trying < limit:
guess = int(input("can you guess the magic number?"))
trying += 1
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
Move the text out of the loop to a print statement. Then you can still keep fetching the input inside the loop:
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
print("can you guess the magic number?")
while trying < limit:
trying += 1
guess = int(input())
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
However, if the second guess is still wrong you probably don't want to print "try a lower/higher number". If you guess it right the second time you do want to print "wow, you're right". I'd put the "try a lower/higher number" after an additional check of whether all tries have been used up already. You can move the "wow, you're right" part before that check:
while trying < limit:
guess = int(input())
trying += 1
if guess == magic_number:
print("wow, you are right")
break
if trying == limit:
continue
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
else:
print("sorry, the magic number was", magic_number)

Python - When number is equal to or above question

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.

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

Python: How to check if a signed number is positive or negative or none?

Simply, I am entering a value, I want to determine whether the value is alpha or not. If it is not alpha, I want to check if it is a number or not. If it is a number I want to check if it is positive or negative.
I read a lot about checking a signed number like -50. There are two ways, we can use something like this:
try:
val = int(x)
except ValueError:
print("That's not an int!")
Which I think I do not need it here and I do not know where to put it in my code.
The other way is to use .lstrip("-+"), but it is not working.
amount = 0
while True:
amount = input("Enter your amount ===> ")
if amount.isalpha() or amount.isspace() or amount == "":
print("Please enter only a number without spaces")
elif amount.lstrip("-+").isdigit():
if int(amount) < 0:
print("You entered a negative number")
elif int(amount) > 6:
print("You entered a very large number")
else:
print(" Why I am always being printed ?? ")
else:
print("Do not enter alnum data")
What am I doing wrong ?
This is how you would integrate a try/except block:
amount = 0
while True:
amount = input("Hit me with your best num!")
try:
amount = int(amount)
if amount < 0:
print("That number is too tiny!")
elif amount > 6:
print("That number is yuge!")
else:
print("what a boring number, but I'll take it")
break # How you exit this loop
except ValueError:
print("Wow dude, that's like not even a number")
It does all the heavy lifting for you, as int() can process numbers with +/- automatically.
>>> amount = '-6'
>>> '-' in amount
True
>>> amount = amount.strip('-')
>>> amount.isdigit()
True
Check if the number is less than 0 or greater than 0 with < >

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