Python-Testing user-defined function but not running properly - python

Below is my program...
var = raw_input('Please enter a value: ')
def is_positive(var):
if var > 0:
return True
if var <= 0:
return False
if is_positive(var) == True:
print "%s is greater than zero." %var
else:
print "%s is NOT greater than zero." %var
When I run the program, the output is...
Please enter a value: -2
-2 is greater than zero.
Which makes no sense in terms of what I want the function to print. I'm VERY new to programming and cannot understand what I'm missing. Any assistance would be grateful. Thanks!

Try doing
def is_positive(var):
print type(var)
if var > 0:
return True
if var <= 0:
return False

You have to cast it as an int and in the method, you have to check a not var. Furthermore, you can simply is_positive(a) as follows. Here is the correct code:
var = int(raw_input('Please enter a value: '))
def is_positive(a):
return a > 0
if is_positive(var):
print "%s is greater than zero." %var
else:
print "%s is NOT greater than zero." %var
If you don't cast the input as an int, you are comparing the strings which don't compare as you expect

Related

Python how to check if input is a letter or character

How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.

Why is my function being ignored?

In the console, my program prints the first question, and once the input is entered, prints the second one and terminates. It appears to skip the function. Obviously I've done something(s) wrong, any help would be appreciated. That while-loop still feels wrong.
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
return False
print("This number is not prime.")
else:
i = i - 1
return True
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Your function returns before printing output, so nothing ever gets to the console. Consider printing before returning:
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
print("This number is not prime.") # Here
return False
else:
i = i - 1
print("This number is prime.") # And here
return True

Error: 'int' object not iterable?

I have searched for a fix to my getting this error to no avail. This is mostly because I don't iterate over anything in my code, except maybe the count variable, unless there is an implicit iteration in a library function I call. Why am I getting this error?
import random
import math
rand = random.randint
floor = math.floor
count = 0
pastGuesses = None
ans = 0
success = False
low = 1
high = 100
player = ""
def initC():
"Initialize the game mode where the user guesses."
print "I will come up with a number between 1 and 100 and you have to guess it!"
answer = rand(1, 100)
player = "You"
return answer
def guessEvalC(answer, g):
"Pass the real answer and the guess, prints high or low and returns true if guess was correct."
if g == answer:
print "Correct!"
return True, 1, 100
elif g > answer:
print "Too high!"
return False, 1, 100
else:
print "Too low!"
return False, 1, 100
def guessC(a, b):
"Prompt user for a guess."
suc = 0
print "%u)Please enter a number." % (count)
while True:
try:
gu = int(raw_input())
if gu <= 100 and gu >= 1:
return gu
print "Outside of range, please try again."
except ValueError:
print "NAN, please try again."
def initU():
"Initialize the game mode where the computer guesses."
print "Think of a number between 1 and 100, and I'll guess it!"
player = "I"
return 0
def guessEvalU(a, b):
"Prompt user for correctness of guess"
print "Is this high, low, or correct?"
s = raw_input()
value = s[0]
if value == "l" or value == "L":
return False, b, high
elif value == "h" or value == "H":
return False, low, b
else:
return True
def guessU(l, h):
"Calculations for guess by computer."
guess = int(floor((l + h)/2))
print "I guess %u!" % (guess)
return guess
print "Guessing game!\nDo you want to guess my number?"
resp = raw_input("Yes or no. ")
mode = resp[0]
if mode == "y" or mode == "Y":
init = initC
guess = guessC
guessEval = guessEvalC
else:
init = initU
guess = guessU
guessEval = guessEvalU
ans = init()
while success != True:
count = count + 1
gue, low, high = guess(low, high)
success = guessEval(ans, gue)
print "%s guessed it in %u tries!" % (player, count)
raw_input()
I get the error at line 77, is it because you can't mix types in a tuple?
gue, low, high = guess(low, high)
Edit: I had switched a couple of the function calls when I wrote this, guessEval() is the function that was supposed to return 3 items, while guess only returns 1. The reason I was getting the 'int' object not iterable error was that when you try to assign return values to a tuple of variables, the interpreter assumes that the object being returned by the function will be an iterable object. guess() only returns one value, of type int, and when the interpreter tries to iterate through the returned object and place its contents into the desired variables, it returns this error. It would be helpful if compilers/interpreters, when they return errors pertaining to a certain object, would mention what object the error message is referring to. For instance 'int'(returned from guess()) object not iterable. Not really necessary as a feature, but it would be very useful.
In guessC:
gu = int(raw_input())
return gu
In the main loop:
gue, low, high = guess(low, high)
So, you are trying to receive three answers from a function that only returns one.
Either return an iterable from guessC() or assign to a single int in the main loop.
Both guessC and guessU returns just one value, but on line 77 you try to unpack 3 values.
The call to guess - waiting for the function to return 3 values:
gue, low, high = guess(low, high)
The functions return statement:
return gu
and:
return guess

Python and Functions

I'll admit it, I am very new to python and need some help. I am trying to convert a very simple calculator from c++ to python. Here is the code so far:
x = 0
y = 0
sign = '+'
def getnum(prompt, number):
number = input(prompt)
def getsign(prompt, sign):
sign = raw_input(prompt)
print sign
def calc(string, number1, number2, sign):
print string
print " "
if sign == '+' or 'plus':
a = x + y
elif sign == 'x' or '*' or 'times':
a = x * y
elif sign == '/' or 'divided by':
a = x / y
elif sign == '-' or 'minus':
a = x - y
print string, a
getnum("Enter first number: ", x)
getnum("Enter second number: ", y)
getsign("Enter sign: ", sign)
calc("The answer is: ", x, y, sign)
print x
print y
print sign
The problem with the functions. At the end, I get this:
The answer is: 0
0
0
+
I can't seem to get the two numbers at the end to change.
I give you few suggestions at the places where you have to change your code, these will certainly make your program work given you know how functions work in python (in genral any language)
def getnum(prompt, number):
number = input(prompt)
The variable 'number' is local to that function. So every time you call the function "getnum" you assign a value to the number but what else do you do with that.
**Hint 1: A mechanism where as soon as you get the number, try throwin this number to a variable which can use it. Try using return.
**Hint 2: When you use input, by default the value entered will be converted into a string. So think of a method where the value will be changed from string to int. "casting"?
def getsign(prompt, sign):
sign = raw_input(prompt)
print sign
print sign
Directly prints the sign to the console, just think of a situation where your program can use the sign. I will give the same hint.
**Hint: Try using return.
Python does not have "call by name". C does. Python does not.
A function evaluation like this:
getnum("Enter first number: ", x)
Will never assign a new value to x in Python. In C, a new value can be assigned. In Python a new value cannot be assigned this way.
[A value can be mutated, but that's not relevant to this question.]
There are a number of issues.
Let's look at them in the interactive Python interpreter, which is an invaluable tool when you're experimenting with Python.
Firstly, getnum() doesn't do what you think it does...
>>> def getnum(prompt, number):
... number = input(prompt)
...
>>> x = 0
>>> getnum("Enter first number: ", x)
Enter first number: 6
>>> print x
0
Here you should return the value and capture it in a variable.
>>> def getnum(prompt):
... return input(prompt)
...
>>> x = 0
>>> x = getnum("Enter first number: ")
Enter first number: 6
>>> print x
6
getsign() has a similar issue.
Moving onto calc(). Here or isn't doing what you expect:
>>> sign = '*'
>>> if sign == '+' or 'plus':
... print 'plus'
...
plus
This needs to look more like:
>>> sign = '*'
>>> if sign == '+' or sign == 'plus':
... print 'plus'
... else:
... print 'not plus'
...
not plus
Or better still:
>>> if sign in ('+', 'plus'):
... print 'plus'
... else:
... print 'not plus'
...
not plus
>>> sign = '+'
>>> if sign in ('+', 'plus'):
... print 'plus'
... else:
... print 'not plus'
...
plus
The other conditions in this function have the same issue.
I'm inclined to treat this like a "homework" problem and tell you what you're doing wrong rather than show you the exact solution. When you take your inputs using input(prompt), you are getting a string. If you want to treat it as a number, you need to tell Python that explicitly.
I asume this is for the school, so this maybe can help you.
#!/usr/bin/env python
import re
#put the logic in an object like enviroment
class CalculatorProto(object):
def __init__(self, numberone, numbertwo):
"""
initialize the data
"""
self.firsn = numberone
self.twon = numbertwo
def Verifynumber(self):
"""
verify is you pass abs numbers
"""
numbers = re.compile("^[0-9]+$")
if numbers.search(self.firsn) and numbers.search(self.twon):
self.firsn = int(self.firsn)
self.twon = int(self.twon)
return True
else:
return False
def sum(self):
"""
manage sum
"""
rsum = self.firsn + self.twon
return rsum
def rest(self):
"""
manage rest
"""
if self.firsn > self.twon:
rrest = self.firsn - self.twon
return rrest
else:
rrest = self.twon - self.firsn
return rrest
def div(self):
"""
manage div
"""
if int(self.firsn) > int(self.twon):
if self.twon != 0:
rdiv = self.firsn / self.twon
return rdiv
return "Is not good idea div a number by 0"
else:
if self.firsn != 0:
rdiv = self.twon / self.firsn
return rdiv
return "Is not good idea div a number by 0"
def mul(self):
rmul = self.firsn * self.twon
return rmul
if __name__ == "__main__":
#here you cant write you small interface
print "Enter two numbers, and a operation please"
o = raw_input("One: ")
t = raw_input("Two: ")
operation = raw_input("Operation: ")
while operation not in ("sum", "div", "rest", "mul"):
print "WTF?? Enter a valid operation"
print "sum\ndiv\nrest\nor mul"
operation = raw_input("Operation: ")
cal = CalculatorProto(o, t)
if cal.Verifynumber():
exec("print cal.%s()" % operation)
else:
print "Please insert absolute numbers"
You cant modify this, for a more complex manage.

determinating if the input is even or odd numbers

Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate
Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]
It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"
The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description

Categories

Resources