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
Related
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.
I have the following code:
def five_numbers():
my_list = []
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
# Here I want to go back to five_numbers() and the number x (for example number 4)
Now I want to check if the input contains any letters. If it has, I want to print a message and then I want to go back to the number that the user was on earlier. I've tried to return five_numbers() but then the user will start from the beginning.
I appreciate all the help.
Add a keyword arg for num and default it to None:
def five_numbers(num=None):
my_list = []
if num is None:
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
else:
# do other stuff with num (4) here...
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
five_numbers(4)
You can use a while loop to keep asking the user for a valid input until the user enters one. You should also make the check function raise an exception instead so the caller can catch the exception and retry the input:
def five_numbers():
my_list = []
for i in range(1, 6):
while True:
user_nr = input("Number " + str(i) + ": ")
try:
check_if_number_is_1_to_25(user_nr)
break
except ValueError as e:
print(str(e))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
raise ValueError('Enter a number between 1 and 25.')
Don't use a for loop, use a while loop with the list length as its condition. Make the check function return a boolean and use it to decide whether to append to the list.
def five_numbers():
my_list = []
while len(my_list) < 5:
user_nr = input("Number {}: ".format(len(my_list)+1))
if check_if_number_is_1_to_25(user_nr):
my_list.append(user_nr)
else:
print("Enter a number between 1 and 25.")
return my_list
def check_if_number_is_1_to_25(number):
return number.isdigit() and (1 <= float(number) <= 25)
I am using python 3 and need to print the final result from within the function(this is not optional). Instead it is printing every time it goes through the function.
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
print(result)
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplay(number)
main()
If you enter 12345 it prints out
21
321
4321
54321
I want it to print out 54321
The following worked for me (after I found a Python 3 interpreter online):
def reverseDisplay(n):
tmp = n % 10 # Determine the rightmost digit,
print(tmp, end="") # and print it with no space or newline.
if n == tmp: # If the current n and the rightmost digit are the same...
print() # we can finally print the newline and stop recursing.
else: # Otherwise...
reverseDisplay(n // 10) # lop off the rightmost digit and recurse.
If you need to return the reversed value in addition to printing it:
def reverseDisplay(n):
tmp = n % 10
print(tmp, end="")
if n == tmp:
print()
return tmp
else:
return int(str(tmp) + str(reverseDisplay(n // 10)))
You just need to move your print statement out of the reverseDisplay and into main:
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return result
def main():
number = 12345
print reverseDisplay(number)
main()
If you really need to print it in the recursive function, you'll have to add a parameter (called first in this example) to make sure you only print the first time:
def reverseDisplay(number, first=True):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10, False)))
if first:
print(result)
return result
Try this:
def reverseDisplayPrinter(number):
print reverseDisplay(number)
def reverseDisplay(number):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplayPrinter(number)
main()
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
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