Check whether a number lies between two other numbers - python

For some reason my code won't return False EVER and I cant figure it out?
I think the issue is with how my between function is written but it makes sense to me. Also I am struggling to get my restart function to work. If somebody could help me with those 2 areas I would be extremely grateful.
def between(a,b,c):
if a>b and b<c:
Rnum =True
else:
Rnum=False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if
the second number lies betweenthe first and the third")
print()
while True:
numone=input('Please enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
sprint()
number =between(numone,numtwo,numthree)
print('The statement ' + str(numone) + ' lies between ' + str(numtwo) + ' and ' + str(numthree) + ' is True.'"\n")
#Restart question
while True:
restart = input('Would you like to play again (Y/N)? ')
if restart == 'Y' or restart == 'y':
print('Restarting!' + ('\n' * 2))
break
if restart == 'N' or restart == 'n':
print('Thank you for playing.' + ('\n' *2))
break
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if restart == 'N' or restart == 'n':
break
else:
continue
if __name__ == '__main__' :
main() #excucte main function

The logic of your between function was slightly wrong (I've rename the variables to make it slightly clearer). In addition, you were not returning the value of the function so it was basically doing nothing. You were also always printing "True".
I have modified your code to return the result of the between function. I have made the result of this function a variable called true_or_false which is then printed at the end of each game.
In order to get your code to loop, all you need is another while loop which you can break out of if the user does not want to continue.
def between(low,test,high):
if low < test < high:
return True
else:
return False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if\nthe second number lies betweenthe first and the third")
while True:
while True:
numone=input('\nPlease enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
true_or_false =between(numone,numtwo,numthree)
print('The statement ' + str(numtwo) + ' lies between ' + str(numone) + ' and ' + str(numthree) + ' is ' + str(true_or_false) + "\n")
restart = ""
while restart.upper() != "Y":
restart = input('Would you like to play again (Y/N)? ')
if restart.upper() == "Y":
print('Restarting!')
elif restart.upper() == "N":
print ('Thank you for playing.')
sys.exit()
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if __name__ == '__main__' :
main() #excucte main function

You have small mistake, either in the problem definition or in the example code. Anyways if you modify it a bit:
def between(a,b,c): if b>a and b<c: return 'True'
else: return 'False'
print('The statement ' + str(numtwo) + ' lies between '
+ str(numone) + ' and ' + str(numthree) + ' is ' +
between(a,b,c) +"\n")

Related

strings are throwing errors

In this project I am checking the number is even or odd with the help of user input. The problem I am stuck on is that when the user types a str character the whole project blows up. I want to write a program where even if the user typed a string the program won't blow up would print("Please type a number") a message like that.
type num = int(input("Enter a number: "))
if num % 2 == 0:
print(str(num) + ' is an even number')
else:
print(str(num) + ' is an odd number')
I tried try and except and even functions but I couldn't provide a logic to run the program.
Not sure why you are using typeat the beginning, but this may help you:
while True:
try:
num = int(input('Enter a number: '))
break
except ValueError:
print('Please type a number.')
continue
if num % 2 == 0:
print(str(num) + ' is an even number')
else:
print(str(num) + ' is an odd number')

Running try and except in a function and re-running results in a NoneType return. How do I fix this?

I'm working on a simple program that allows the user to bet some virtual currency on a coin toss. Everything works fine, except for when the user inputs something incorrectly. For example: if a question asks for y/n response and the user puts 'd' or something as the response, the program will use the except ValueError and rerun the function. However, when the function is rerun and the user finally inputs something correctly, it will result in a further error.
Error:
> AttributeError: 'NoneType' object has no attribute 'lower'
Code:
import time
import random
money = 5000
last_interest_time = time.time()
def interest():
global money, last_interest_time
if time.time() - last_interest_time > 5:
prev_money = money
money *= 0.1
last_interest_time = time.time()
print("You now have " + str(money) + " monies (+" + str(money - prev_money) + ") from interest")
def game():
global money, last_interest_time
print("You have " + str(money) + " monies.")
choice = get_choice("Want to bet on a coin toss?", 'y','n')
if choice.lower() == 'y':
print("That's great!")
choice = get_choice("What side do you want to bet on?", 'h', 't')
bet_amount = get_bet()
print('Flipping the coin...')
time.sleep(1)
side = random.choice(['h', 't'])
if side == 'h':
print("The coin landed heads!")
elif side == 't':
print('The coin landed tails!')
if side == choice:
print("You won and received " + str(bet_amount) + " monies!")
money += bet_amount
else:
print("You lost the bet and " + str(bet_amount) + " monies!")
money -= bet_amount
game()
elif choice.lower() == 'n':
input('Oh well. Just type something if you want to bet again. ')
game()
def get_choice(question, response_1, response_2):
choice = input(question+" ("+response_1+'/'+response_2+'): ')
if choice != response_1 and choice != response_2:
print('Input is invalid. Must be '+response_1+'/'+response_2)
get_choice(question, response_1, response_2)
else:
return choice
def get_bet():
bet_amount = input("What amount do you want to bet?: ")
try:
if int(bet_amount) > money:
print("You don't have enough money!")
get_bet()
else:
return int(bet_amount)
except ValueError:
print('Invalid input. Must be a number')
get_bet()
game()
Debugging tip:
Print choice every time so you can see why it's crashing! You can take the print statement out later.
What I found was this:
get_choice() returned None.
In get_choice, if the input is invalid, it doesn't actually return anything. Oh no! So you're returning None, and calling .lower() on None throws the exception.
Solution:
You are on the right track when you run get_choice a second time if the input is invalid. One small tweak: instead of just running get_choice, return get_choice.
There is a similar bug in get_bet(), just a heads up, and you can solve it the same way.
Overall, great game.
.lower() runs on strings only and defining a variable with input() makes it not register as a string. Instead try something like this.
def set_choice():
choice = input("Want to bet on a coin toss?", 'y','n')
def choice():
choice = set_choice()
return choice
choice = choice.lower()

Calling another function error

This is supposed to be a test program on which I can practice python. I defined main and built up the code. When the answer is right, I press 'Y' and it is supposed to jump to the next function which is the next code block after this one ends. The error is get is this:
NameError: name 'logic_ques' is not defined.
How do I start the next function after I press 'y' and not get an error? Is the problem the order?
def main():
pts = 0
numberStr = input("Please enter the sum of 251 and 516: \n ")
num = int(numberStr)
print ('You have entered: ', num)
if (num == 767):
pts += 1
print ('The answer is correct!')
print ('You currently have ', pts, 'point(s).')
continue1 = input('Press any key to see the next question.')
logic_ques()
else:
print ('The answer is not correct.')
restart = input('The answer is wrong, type Y if you want to restart, and N if you want to exit. \n')
if (restart == 'y'):
main()
else:
exit()
main()
def logic_ques():
logicStr = input("Which animal sleeps on legs, not lying down?")
print ('You have entered the following animal:', logicStr)
if (logicStr == 'horse'):
pts += 1
print ('The asnwer is correct!')
print ('You currently have ', pts, 'points.')
continue1 = input('Press any ket to see the next question.\n')
else:
print ('The asnwer is not correct!')
restart1 = input('The answer is wrong, type Y if you want to restart, and N if you want to exit. \n')
if (restart1 == 'y'):
logic_ques()
else:
exit()
logic_ques()
Move the definition of logic_ques() before the definition of main()
Yes, the problem is the order. You are calling the logic_ques() function in main() before you define it. Simply move definition of logic_ques() above the point where you call main()

Python catch int or str

I've written a program that generates a random number for the user to guess. I'm working on trying to catch all the possible errors. The only one I can't seem to figure out is this. At the beginning I ask the user to hit enter to continue to the game. The program catches if they type a string or even special characters and punctuation. The only thing I can't seem to prevent is if they they type a number, the program terminates. This is what I have. The issue is in the first while loop in the try block. Any suggestions or help would be appreciated.
Thanks in advance.
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while True:
if cont != '':
try:
int(cont)
str(cont)
break
except ValueError:
print('Just hit enter')
cont = input()
continue
elif cont == '':
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()
What happens when you enter a number is that the program tries to convert the number to an int (which works), and then to a str (which also works), after which it breaks. Instead, try the following:
from random import randint #imports randint from random class
cont = input('Press enter to continue')
while cont != '':
cont = input('Press enter to continue')
while True:
randNum = randint(1, 100)
print('Try guesssing a number between 1 and 100')
num = input()
while True:
try:
int(num)
break
except ValueError:
print('Please enter a number')
num = input()
num = int(num)
if num == randNum:
print('Good job, ' + str(num) + ' is correct.')
else:
print('Sorry, the number was ' + str(randNum) + '.')
print('Would you like to try again?')
answer = input().lower()
if answer == 'yes':
continue
elif answer == 'no':
print('Thanks for playing')
exit()
else:
while True:
print('Please type yes or no')
answer = input()
if answer == 'yes':
break
elif answer == 'no':
print('Thanks for playing.')
exit()
while True:
if cont != '':
try:
int(cont)
str(cont)
break
What it does here is try and convert cont to an int, if it succeeds it tries to convert it to a string (which is virtually always possible). If that succeeds it breaks the while loop and ends the program.
In any other scenario other than an int when it tries to parse it int(cont) it raises an error and you continue to your program.
Once he pressed enter cont starts. there is no reason for you to verify he didn't write something before entering the text.

How to give a warning and ask for raw_input again - while inside a loop

I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").
The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.
If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.
Thanks a lot for your advice!
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
break
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
Generally, when you don't know how many times you want to run your loop the solution is a while loop.
for seat in range(1,5):
my_input = raw_input("Enter: ")
while not(my_input == 'q' or isnumeric(my_input)):
my_input = raw_imput("Please re-enter value")
if my_input == 'q':
break
else:
total += float(my_input)
As Patrick Haugh and SilentLupin suggested, a while loop is probably the best way. Another way is recursion- ie, calling the same function over and over until you get a valid input:
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
def is_q(value):
return value == 'q'
def is_valid(value, validators):
return any(validator(input) for validator in validators)
def get_valid_input(msg, validators):
value = raw_input(msg)
if not is_valid(value, validators):
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(value)
value = get_valid_input(msg, validators)
return value
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = get_valid_input("enter it here ['q' to quit]: ", [is_q, is_numeric])
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
In the above code, get_valid_input calls itself over and over again until one of the supplied validators produces something truthy.
total = 0
for seat in range(1,5):
incorrectInput = True
while(incorrectInput):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
print 'Goodbye'
quit()
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
incorrectInput = False
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"

Categories

Resources