Error: 'int' object not iterable? - python

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

Related

Validated Value still causing TypeError?

keep running into this error, but I'm confused because in theory I've already validated the variable as an integer before sending it through my function as a parameter. Any ideas? Thank you!
The function is question is: "calculate_distance(n):" and it doesn't like that I'm using the "<>" operators with those values.
print("Welcome Astronaut to Apollo 11 - the mission to land on The Moon.")
print("Lets determine the length of your journey so far - It should take about 3 days to reach Lunar orbit.")
# Function Boolean valid_integer(String input_string)
# Declare Boolean is_valid
#
# is_valid = is input_string a valid integer?
# Return is_valid
# End Function
def valid_integer(input_string):
try:
val = int(input_string)
is_valid = True
except ValueError:
is_valid = False
return is_valid
# Function Integer get_number()
# Declare String input_string
# Declare Boolean is_valid
#
# Display "Enter a number: "
# Input input_string
# Set is_valid = valid_integer(input_string)
# While Not is_valid
# Display "Please enter a whole number: "
# Input input_string
# is_valid = valid_integer(input_string)
# End While
# input_integer = int(input_string)
# Return input_integer
# End Function
def get_number():
input_string = input("Enter your hours of spaceflight: ")
is_valid = valid_integer(input_string)
while not is_valid:
input_string = input("Please enter a whole number: ")
is_valid = valid_integer(input_string)
input_integer = int(input_string)
return input_string
def output_distance(counter, distance, percent):
print("Since hour", counter, "you have traveled", distance, "miles,", percent, "of the way there")
def calculate_distance(n):
counter = 0
distance = 0
percent = 0
if(n < 1):
print("You're still on the launchpad")
return
if(n > 72):
print("You made it! The Eagle has landed")
return
while counter < n:
counter = counter + 1
distance = counter * 3333
percent = ((counter * 3333) / 240000) * 100
output_distance(counter, distance, percent)
# Module main()
# Set n = get_number()
# Call calculate(n)
# End Module
def main():
n = get_number()
calculate_distance(n)
main()
Even though you're validating the number as an integer within the valid_integer() function, you could pass the number as an integer to the calculate_distance() function.
calculate_distance(int(n))
Or at any other point along the way, for that matter. Return it in the get_number() function, for instance:
return(int(input_string))
use int(input) for input number

TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

I am having trouble with feeding a value into a function, and not having that values type be an int, instead it is a NoneType, which I cannot operate with. Here's the error message I am thrown:
Traceback (most recent call last):
File "NumberGame1.py", line 140, in <module>
main()
File "NumberGame1.py", line 29, in main
result = guessinggame(number)
File "NumberGame1.py", line 92, in guessinggame
if guess - number <= level * 0.1:
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
Here is all of the code:
import random
import timeit
def main():
print "\nWelcome to Ethan's Number Guessing Game!"
print "What would you like to do?: \n1. Play game\n2. View High Scores\n3. View Credits"
menuchoice = input()
## choice is Menu Decision
if menuchoice == 1:
difficulty = input("Pick a difficulty!: \n1: Easy\n2: Medium\n3: Hard\n4: Insane\n5. Out of control!\n6. Custom\n")
leveldif = difcalc(difficulty)
## Exits program if you don't choose a difficulty
global level
level = leveldif[0]
difmod = leveldif[1]
number = numbergenerator(level)
result = guessinggame(number)
totalTime = result[0]
tries = result[1]
scorer(tries, totalTime)
elif menuchoice == 2:
## Figure out how to access high scores
print "This feature is currently under development.\n"
elif menuchoice == 3:
print "\nDeveloped by Ethan Houston"
raw_input()
print "\nDeveloped in Python 2.7.9 using Sublime Text 2"
raw_input()
print "\nThanks for playing :)"
raw_input()
## Simple credits reel. Go me
def difcalc(difficulty):
if difficulty == 1:
leveldif = [10, 1]
elif difficulty == 2:
leveldif = [50, 1.5]
elif difficulty == 3:
leveldif = [100, 2]
elif difficulty == 4:
leveldif = [1000, 10]
elif difficulty == 5:
leveldif = [10000, 20]
elif difficulty == 0:
leveldif = [1, 1]
return leveldif
def guessinggame(number):
tries = 1
## Counter for number of attempts at guessing
guess = input("Guess a number between 1 and " + str(level) + "!: ")
## Takes input from user
while guess > level:
guess = input("Above range!\nMake sure to guess between 1 and " + str(level) + "!: ")
## If the user chooses a number above the range, makes you try again until within range
startTime = timeit.default_timer()
## Starts a timer once first valid number is selected
while guess != number:
## While loop that runs as long as guess isn't correct
if guess > number:
if guess - number <= level * 0.1:
guess = input("Too high, close!: ")
tries += 1
## If difference between guess and answer is less than or equal to 10% of level,
## prints different prompt
else:
guess = input("Too high, guess again: ")
tries += 1
## Normal behavior
elif guess < number:
if guess - number <= level * 0.1:
guess = input("Too low, close!: ")
tries += 1
## If difference between guess and answer is less than or equal to 10% of level,
## prints different prompt
else:
guess = input("Too low, guess again: ")
tries += 1
## Normal behavior
endTime = timeit.default_timer()
## Takes the time after the correct number is chosen
totalTime = endTime - startTime
## Calculates time difference between start and finish
result = [totalTime, tries]
return result
def numbergenerator(level):
global number
number = random.randint(1, level)
def scorer(tries, totalTime):
print "\nCorrect! It took you " + str(round(totalTime, 2)) + " seconds and " \
+ str(tries) + " tries to guess.\n"
## Once user guesses correct number, program tells how many tries it took, and how long
score = 1/(1+(tries * round(totalTime, 2))) * 1000 * difmod
## Calcualtes score, making lower times and fewer tries yield a higher score
## Difmod takes into account the difficulty
## Multiply by 1000 to make number more readable
print "Score: " + str(round(score, 2)) + "\n"
## Printsthe score, rounded to 1 decimal place
main()
When a python function does not explicitly return anything , it returns None . In your case, you have a function -
def numbergenerator(level):
global number
number = random.randint(1, level)
This does not return anything, instead you set a global variable number .
But when you are calling this function in main() , you do -
number = numbergenerator(level)
And here number is not a global variable (Even if it was a global it wouldn't matter) , so after calling numbergenerator() , since it does not return anything, it returns None , which gets set to number variable, and hence number is None, causing the issue you are having.
I believe you do not need to use global variable there, you should just return the number from numbergenerator() function , example -
def numbergenerator(level):
return random.randint(1, level)

Returning the highest of two NoneTypes

we are trying to find out how to compare the values of two nontypes to find the highest scoring dice, but every time we run the code it displays Typeerror: unorderable types: Nonetype() > Nonetype()
def compareresult():
if giveresult(dice) > giveresult(newdice):
print(giveresult(dice))
elif giveresult(newdice) > giveresult(dice):
print(giveresult(newdice))
return dice, newdice
giveresult is:
def giveresult(tempDice):
if fiveofakind(tempDice) is True:
tempScore = int(50)
print(tempScore)
if fiveofakind(tempDice) is False:
tempScore = int(0)
print(tempScore)
Your giveresult() function is not returning anything, so the default None is returned. Printing is not the same thing; you are writing text to the terminal, not returning and the caller cannot use text written to a terminal.
Replace print() with return:
def giveResult(tempDice):
if fiveofakind(tempDice):
return 10
else:
return 0
I also simplified your function; there is no need to test for is True; if already tests if the result of fiveofakind() is true or not. And because you already tested for fiveofakind(), all you need to do is use else to pick the other case.
Next, avoid calling giveResult more than per dice, and again, return the result from your function:
def compareresult():
dice_result = giveResult(dice)
newdice_result = giveResult(newdice)
if dice_result > newdice_result
return dice_result
elif newdice_result > dice_result:
return newdice_result
return dice, newdice
If you must return the greater result, just use the max() function:
def compareresult():
dice_result = giveResult(dice)
newdice_result = giveResult(newdice)
return max(dice_result, newdice_result)

Python-Testing user-defined function but not running properly

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

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