Checking whether user has input a number or not? - python

I made a simple script which finds the Square root of a number. The user inputs a number and it finds the square root and shows the result. I want it to check whether the input was a number or not. If it was a number it'll continue else it'll show a message, and reset.
I tried using:
while num != int(x):
print "That is not a valid number"
return self.page()
But that only shows an error.
Can someone help me out on this?
Here is the code:
import math
import sys
class SqRoot(object):
def __init__(self):
super(SqRoot, self).__init__()
self.page()
def page(self):
z = 'Enter a number to find its square root: '
num = int(raw_input(z))
sqroot = math.sqrt(num)
print 'The square root of \'%s\' is \'%s\'' % (num, sqroot)
choose = raw_input('To use again press Y, to quit Press N: ')
if choose == 'Y' or choose == 'y':
return self.page()
elif choose == 'N' or choose == 'n':
sys.exit(0)
print "SqRoot Finder v1.0"
print "Copyright(c) 2013 - Ahnaf Tahmid"
print "For non-commercial uses only."
print "--------------------------------"
def main():
app = SqRoot()
app()
if __name__ == '__main__':
main()

One of the python principles is EAFP:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.
x = raw_input('Number?')
try:
x = float(x)
except ValueError:
print "This doesn't look like a number!"

If you don't want to use the ask forgiveness method, here is a simple function which should work on any valid float number.
def isnumber(s):
numberchars = ['0','1','2','3','4','5','6','7','8','9']
dotcount=0
for i in range(len(s)):
if (i==0 and s[i]=='-'):
pass
elif s[i]=='.' and dotcount==0:
dotcount+=1
elif s[i] not in numberchars:
return False
return True
Note: You can add base 16 easy by changing numberchars to:
numberchars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']

Related

Why do 2 equivalent variables not equal each other?

So I have the following code where chalnum (short for challenge number) is a randomly generated number. You have to try to get that number through a sequence of inputs (finalnum2). But for some reason, it always thinks the numbers aren't equal even when they are.
chal = input('Would you like a challenge number? (y/n) ')
if 'ye' in chal or chal == 'y':
str = 'Try to get %s \n'
chalnum = round(uniform(5, 5000))
print(str % colored(chalnum, attrs=['underline']))
else:
chalnum = 0
print('\n')
some more code where you make your number, then:
finalnum2 = round(num/ex_num2)
(chalnum, finalnum2)
if finalnum2 == chalnum:
chalcomp = (colored('Congrats! You completed the challenge!', 'green'))
for i in range(chalcomp):
print(chalcomp[i], sep='', end='', flush=True); sleep(0.14)
elif chalnum == 0:
pass
elif finalnum2 > chalnum or finalnum2 < chalnum:
chalfail = (colored('Oh no! It looks like you failed the challenge!', 'red'))
for i in range(chalfail):
print(chalfail[i], sep='', end='', flush=True); sleep(0.14)
else:
raise Exception
Please keep in mind that I am a beginner so if it's a stupid mistake please don't be harsh.
possible that they both in different types like 24!='24'
Use typecasting and convert into say
if int(finalnum2) == int(chalnum):
Comparison would go well in this case.

Using var() to instantiate object from user input. Syntax error

I've made these classes and now I'm trying to make a function that allows you to instantiate a new object from data a user inputs. But I'm getting syntax errors with using var()
The class structure is that there is one main with two sub-classes. The main, "Gokemon" is:
class Gokemon:
def __init__(self,NAME,TYPE,HEALTH,POWER): #Contructor #Mayb think about using dict key words
self._Name = str(NAME)
self._Type = str(TYPE) #Water, Earth, Fire or Flying. Used in Battle() to allow adders
self._HP = int(HEALTH) #Health Points
self._DP = int(POWER) #Power Points - attacking power
and the two sub-classes are named "Tame" and "Wild".
class Tame(Gokemon):
def __init__(self,NAME,TYPE,HEALTH,POWER):
Gokemon.__init__(self,NAME,TYPE,HEALTH,POWER)
self._Owner = ""
self._Time = 0 #How long have they owned it
class Wild(Gokemon):
def __init__(self,NAME,TYPE,HEALTH,POWER):
Gokemon.__init__(self,NAME,TYPE,HEALTH,POWER)
The function for making the new object by user input is as follows:
def NewGokemon():
n = input("What's its name?: ")
while True:
t = input("what's its type?: ")
if t == "Water" or t == "Fire" or t=="Earth" or t =="Flying":
break
else:
print("please try again, the types include:\nFire\nWater\nEarth\nFlying")
while True:
h = input("How many Health Points(HP) does it have")
try:
int(h)/2
except ValueError:
print("Sorry please input a numerical value")
else:
break
while True:
p = input("How many Health Points(HP) does it have")
try:
int(p)/2
except ValueError:
print("Sorry please input a numerical value")
else:
break
while True:
dom = input("Is the Gokemon tame(input t) or wild(input w)?")
if dom =="t":
return var()[n] = Tame(n,t,h,p)
if dom == 'w':
return var()[n] = Wild(n,t,h,p)
The function is fine until at the bottom, when im compiling to execute my Editor (VS code) says.
File "c:\Users\rufar\Desktop\python\little projects\Gokemon - learning class\Gokemon.py", line 38
return var()[n] = Tame(n,t,h,p)
^
SyntaxError: invalid syntax
What am i doing wrong? Is there a better way of doing this?
replaced the whole bit with vars() with this:
while True:
dom = input("Is the Gokemon tame(input t) or wild(input w)?")
if dom =="t":
globals()[n] = Tame(n,t,h,p)
return n
elif dom == 'w':
globals()[n] = Wild(n,t,h,p)
return n
else:
print("Did not understand input")
And now it works fine.

Working on a basic python calculator and can't get my menu to loop properly

Thanks to this site I was able to get this far, being the python novice I am, however I'm kind of stuck. I'm trying to loop 'selection', so after a user does some math, rather than just ending it will give them the option to do something else until they select 0 to quit. I tried a bunch of other try and conditional statements but just end up getting answers and such stuck in an infinite loop.
Also, I'm pretty here, but any help is appreciated, also I'm a python nub. I'm writing this with python 2.7, if that matters.
def sum ( arg1, arg2):
total = a + b
return total;
def subtract ( arg1 , arg2):
total = a - b
return total;
def mult ( arg1, arg2):
total = a * b
return total;
def division ( arg1, arg2):
total = (a / b)
return total;
options = ["1", "2", "3", "4", "5", "0"]
print ("Please choose an option for mathing")
print ("1 for addition")
print ("2 for division")
print ("3 for subtraction")
print ("4 for multiplication")
print ("5 ")
print ("0 to exit")
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break
else:
print("Please choose a valid option")
#user input for mathing
#input will be validated as follows
a = None
while a is None:
try:
a = int(input("please provide a number for A"))
except ValueError:
print "please use a valid integer"
pass
b = None
while b is None:
try:
b = int(input("please provide a number for B"))
except ValueError:
print "please use a valid integer"
pass
#performing the operations
if selection == '1':
print "The sum is", str(sum(a, b))
elif selection == '2':
print "The quotient is", str(division(a, b))
elif selection == '3':
print "The difference is", str(subtract(a, b))
elif selection == '4':
print "The product is", str(mult(a, b))
elif selection == '0':
exit()
heres a few things I would do to make this more efficient..
options should be a dictionary... your in is a lot more efficient on a dictionary than on a list. the beauty of this is the value for each key can be function methods.
ex. options = {1: 'sum', 2: 'subtract' ..... }
then make a class with your math operations in it
class Calculator(object):
def sum(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
#add more operations here
#staticmethod
def start():
while True:
#prompt for input and the operator
whats nice about this is in your checks for the selection you can dynamically call the class method to clean the code up a lot
if selection in options:
getattr(options[selection], Calculator)(a, b)
if you want me to explain more I can finish the example.
for your loop, you can add a method that starts the action and continues looping and doing more operations each time
here is a basic class you can use using those methods I described
class Calculator(object):
loop = None
calculations = 1
current_value = 0
selection = 0
options = {1: 'add', 2: 'subtract', 3: 'multiply', 4: 'divide'}
def __init__(self, loop=True):
self.loop = loop
print 'Welcome to my basic calculator!'
if not self.loop: # dont loop just execute once
self.run()
else:
while True:
self.run()
#staticmethod
def add(x, y):
return x + y
#staticmethod
def subtract(x, y):
return x - y
#staticmethod
def multiply(x, y):
return x * y
#staticmethod
def divide(x, y):
if y != 0: #cant divide by 0
return x / y
#staticmethod
def quit():
exit(0)
def run(self):
if self.calculations == 1:
self.current_value = self.prompt_user_input('please provide a number: ')
self.prompt_operator('Please choose an operator to continue\n1 for addition\n2 for subtraction\n3 for multiplication \n4 for division\n0 to quit\n')
y = self.prompt_user_input('please provide a number: ')
self.current_value = getattr(Calculator, self.options[self.selection])(self.current_value,y)
self.calculations += 1
print 'New value is: ' + str(self.current_value)
def prompt_operator(self, prompt_message):
while True:
self.selection = input(prompt_message)
if self.selection in self.options:
break
elif self.selection == 0:
self.quit()
else:
print("Please choose a valid option")
def prompt_user_input(self, prompt_message):
val = None
while val is None:
try:
val = int(input(prompt_message))
except ValueError:
print "please use a valid integer"
pass
return val
finally to start your calculator off you can just call it and either pass true to continue loops or pass false to only do one calculation
Calculator(loop=True)
Just put a loop around the prompting and calculation. If they enter 0, break from the outer-most loop:
while True:
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break
else:
print("Please choose a valid option")
if selection == '0':
break
...
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
if selection == 1:
sum()
if selection == 2:
subtract()
.....
if selection == 'q'
break
Change the logic to what I did above, for option,take some action and do break on the quit character/
Firstly, your code should not work as it is now:
if selection == '1': #should return false
That's because using input you are taking a numeric quantity and then comparing it to a string.
change the input of selection to raw_input
Or change the conditional statements like below:
if selection == 1:
Then add a while True over the entire execution block to go through the execution again and again, until 0 is selected.

What is wrong with my defintion of the function prompt_int?

I have been trying to program a maths quiz that both works and is as efficient as possible. Looking over my code I saw I had a lot of integer inputs and that lead to me having the program to ask the question/exit the system if the criteria isn't met, so to help me I thought that it would be useful to create a new function. Here is my attempt:
def prompt_int(prompt=''):
while True:
if status == prompt_int(prompt=''):
val = input(prompt)
if val in (1,2):
return int(val)
return true
elif status != prompt_int(prompt=''):
val = input(prompt)
if val in (1,2,3):
return int(val)
return true
else:
print("Not a valid number, please try again")
However, when I try to implement this function around my code it doesn't work properly as it says that status isn't defined however, when I do define status it goes into a recursion loop. How can I fix this problem?
Here is my original code before i try to implement this function:
import sys
import random
def get_bool_input(prompt=''):
while True:
val = input(prompt).lower()
if val == 'yes':
return True
elif val == 'no':
return False
else:
sys.exit("Not a valid input (yes/no is expected) please try again")
status = input("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")# Im tring to apply the new function here and other places that require integer inputs
if status == "1":
score=0
name=input("What is your name?")
print ("Alright",name,"welcome to your maths quiz."
"Remember to round all answer to 5 decimal places.")
level_of_difficulty = int(input(("What level of difficulty are you working at?\n"
"Press 1 for low, 2 for intermediate "
"or 3 for high\n")))
if level_of_difficulty not in (1,2,3):
sys.exit("That is not a valid level of difficulty, please try again")
if level_of_difficulty == 3:
ops = ['+', '-', '*', '/']
else:
ops = ['+', '-', '*']
for question_num in range(1, 11):
if level_of_difficulty == 1:
number_1 = random.randrange(1, 10)
number_2 = random.randrange(1, 10)
else:
number_1 = random.randrange(1, 20)
number_2 = random.randrange(1, 20)
operation = random.choice(ops)
maths = round(eval(str(number_1) + operation + str(number_2)),5)
print('\nQuestion number: {}'.format(question_num))
print ("The question is",number_1,operation,number_2)
answer = float(input("What is your answer: "))
if answer == maths:
print("Correct")
score = score + 1
else:
print ("Incorrect. The actual answer is",maths)
if score >5:
print("Well done you scored",score,"out of 10")
else:
print("Unfortunately you only scored",score,"out of 10. Better luck next time")
class_number = input("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
while class_number not in ("1","2","3"):
print("That is not a valid class, unfortunately your score cannot be saved, please try again")
class_number = input("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
else:
filename = (class_number + "txt")
with open(filename, 'a') as f:
f.write("\n" + str(name) + " scored " + str(score) + " on difficulty level " + str(level_of_difficulty))
with open(filename, 'a') as f:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
if get_bool_input("Do you wish to view previous results for your class"):
for line in lines:
print (line)
else:
sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
if status == "2":
class_number = input("Which classes scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
if class_number not in (1,2,3):
sys.exit("That is not a valid class")
filename = (class_number + "txt")
with open(filename, 'a') as f:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
for line in lines:
print (line)
Well, just a part:
def prompt_int(prompt=""):
while True:
val = input(prompt)
if val in ("1", "2"):
return int(val), True
Will ask again and again. And return when the user enter "1" or "2"!
But better: "if val in "12":
def prompt_int(prompt=""):
while True:
val = input(prompt)
if val.isdigit():
return int(val)
Hi if you dont want to have valid values send to your you could change your code as the function above.
But you could also change it to do the system exits:
def prompt_int(prompt="", authorized=()):
while True:
val = raw_input(prompt)
if val.isdigit():
if int(val) in authorized:
return int(val)
else:
sys.exit("Bla bla bla too bad")
def prompt_int(prompt=''):
while True:
if status == prompt_int(prompt=''):
This line will look for the name "status" in the global namespace (module's namespace), and raise a NameError if there's no global variable named 'status'.
If there's one, it will then recursively calls prompt_int without any possible termination, resulting theoretically in an endless recursion, but practically (in CPython at least) in a RuntimeError when it will hit the maximum recursion depth.
There are also quite a few other things that won't work as you expect:
val = input(prompt)
if val in (1,2):
In Python 3.x, val will be a string, so it will never compare equal to an int. In Python 2.x, input() is a shortcut for eval(raw_input()), which might return an int, but is also a huge security flaw since it unconditionnally execute untrusted code.
return int(val)
return true
The second return statement will never be executed, obviously, since the function will exit at the first one.
A simpler implementation might look like this:
# rebinds raw_input to input for python < 3
import sys
if sys.version_info.major < 3:
input = raw_input
def prompt_int(prompt='', choices=None):
while True:
val = input(prompt)
try:
val = int(val)
if choices and val not in choices:
raise ValueError("{} is not in {}".format(val, choices))
return val
except (TypeError, ValueError) as e:
print(
"Not a valid number ({}), please try again".format(e)
)
While we're at it, there's room for improvement in other parts of your code. Let's start with this:
def get_bool_input(prompt=''):
while True:
val = input(prompt).lower()
if val == 'yes':
return True
elif val == 'no':
return False
else:
sys.exit("Not a valid input (yes/no is expected) please try again")
First point: your naming is not consistent. If your other function is named prompt_int, this one should be named prompt_bool. Also, you have one function (prompt_int) looping forever and the other one exiting the whole program on invalid input, which is another inconsistency. If you want to allow the user to exit on any prompt, provide an explicit option for it, ie:
def prompt_bool(prompt, quit='Q'):
prompt += " (hit '{}' to exit) : ".format(quit)
while True:
val = input(prompt).strip().upper()
if val == quit:
sys.exit("Goodbye")
elif val == 'yes':
return True
elif val == 'no':
return False
else:
print "Invalid input '{}', please try again".format(val)
Of course you then want to provide the same option in prompt_int(), which leads to a more generic function:
def get_input_or_quit(prompt, quit="Q"):
prompt += " (hit '{}' to exit) : ".format(quit)
val = input(prompt).strip()
if val.upper() == quit:
sys.exit("Goodbye")
return val
def prompt_bool(prompt):
while True:
val = get_input_or_quit(prompt).lower()
if val == 'yes':
return True
elif val == 'no':
return False
else:
print "Invalid input '{}', please try again".format(val)
And of course you also replace the call to input by a call to get_input_or_quit in prompt_int.
We could go on for long - splitting all your code in distinct, self-contained function, writing a "main()" function to drive them (instead of having the "main" part at the top level), and obviously using the operator module instead of eval().

Syntax error in python, need help for a project

I'm trying to find a way to fix this syntax error. I can't seem to find it to make the program run correctly.
This is my code below
wrong = 0
test = raw_input("Please enter a 4 digit integer:")
def start(test):
if test.isdigit():
if wrong(test)==True:
print 'Invalid input. Four integers must be entered.'
else:
numbers = []
for a in test:
digits.append(a)
a=calc(int(digits[0]))
b=calc(int(digits[1]))
c=calc(int(digits[2]))
d=calc(int(digits[3]))
code = str(c)+str(d)+str(a)+str(b)
print 'The encrypted integer is:',code
else:
print 'You input wrong. Use numbers only.'
def calc(num):
num+=7
num%=10
return num
def error(test):
if len(test)<4 or len(test)>4:
return True
else:
return False
start(test)
AND the fixed is ...
digits = 0
wrong = 0
test = raw_input("Please enter a 4 digit integer:")
def start(test):
if test.isdigit():
if wrong(test)==True:
print 'Invalid input. Four integers must be entered.'
else:
numbers = []
for a in test:
digits.append(a)
a=calc(int(digits[0]))
b=calc(int(digits[1]))
c=calc(int(digits[2]))
d=calc(int(digits[3]))
code = str(c)+str(d)+str(a)+str(b)
print 'The encrypted integer is:',code
else:
print 'You input wrong. Use numbers only.'
def calc(num):
num+=7
num%=10
return num
def wrong(test):
if len(test)<4 or len(test)>4:
return True
else:
return False
start(test)
You've called a function named wrong() but defined a function named error(). Is that the problem you're seeing?
Don't you mean if error(test)? 'wrong' is not a function.

Categories

Resources