why Python keeps saying prompt is not defined - function

this is the code in Python, I really don't know how to do this, I am just a beginner and someone can understand my question and help me
def get_float(prompt, low, high):
while True:
prompt = input("Enter monthly investment:")
number= float(input(prompt))
if number > low or number <= high:
is_valid = True
return number
else:
print("Entry must be greater than {low}and less than or equal to {high}")
def main():
get_float(prompt,low,high)
if __name__ == "__main__":
main()

In main, you are passing in the prompt variable into get_float. However, prompt is not defined in main, therefore you are attempting to pass an undefined variable which is not allowed.
In fact, given that get_float reads the prompt from input (and not the value passed in), you do not need to pass prompt into get_float, and prompt can be removed from the function signature.

You cannot pass prompt as a Function argument cause you are reading the value inside the function
def get_float(low, high):
while True:
prompt = input("Enter monthly investment:")
number= float(input(prompt))
if number > low or number <= high:
is_valid = True
return number
else:
print("Entry must be greater than {low}and less than or equal to {high}")
def main():
get_float(200,1000)
if __name__== "__main__":
main()

Related

Using exception handling

I am trying to create an exception block that reads an error message and shuts down the program gracefully if my user inputs anything other than a number. How can I achieve this?
x=int(input("Choose a number:"))
try:
x==int()
except:
print("Invalid input.")
sys.exit()
y=int(input("Choose a number:"))
try:
y>=0 or y<=0
except:
print("Invalid input. Please try again.")
sys.exit()
In python the try block lets you test a block of code for errors.
The except block lets you handle the error.
In except block you can use ValueError as you are trying to convert the input to an integer, so if the input value is an integer, the code in the try block will be executed. otherwise the code in the excpet block will be executed.
You can use the while loop to exit the program only when you want by changing the value of the start variable to False.
start = True
while start:
try:
x=int(input("Choose a number for x :"))
y=int(input("Choose a number for y :"))
# if x > y:
# print("x is greater than y")
# elif x == y:
# print("x equal to y")
# else:
# print("x is less than y")
except ValueError:
print("Invalid input. Please enter a number")
start = False
Learn more about exceptions:
https://www.w3schools.com/python/python_try_except.asp
https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Learn more about while loop:
https://www.w3schools.com/python/python_while_loops.asp

how can i make the input work with my parameters?

I have started a python class and my book does not seem to help me.
My professor has a program that bombards my code with different inputs and if any of the inputs do not work then my code is "wrong". I have done many days worth of editing and am at a complete loss. I have the code working if someone puts and input of an actual number. But where my code fails the test is if input is "miles_to_laps(26)" it errors out.
I have tried changing the input to int(input()) but that does not fix the issue. I've gone through changing variables and even changing the input method but still am at a loss. I have already tried contacting my teacher but 6 days of no response and 3 days of being late i feel like I'm just going no where.
user_miles = int(input())
def miles_to_laps(user_miles):
x = user_miles
y = 4
x2 = x * y
result = print('%0.2f' % float(x2))
return result
miles_to_laps(user_miles)
my code works for real number inputs but my professor is wanting inputs like
miles_to_laps(26) and miles_to_laps(13) to create the same outputs.
For the wierd input functionality you can try:
import re
def parse_function_text(s):
try:
return re.search("miles_to_laps\((.+)\)", s)[1]
except TypeError:
return None
def accept_input(user_input):
desugar = parse_function_text(user_input)
if desugar is not None:
user_input = desugar
try:
return float(user_input)
except ValueError:
raise ValueError("Cannot process input %s" % user_input)
assert accept_input("miles_to_laps(3.5)") == 3.5
I'm trying to keep all the pedantism aside, but what kind of CS/programming teaching is that?
Areas of concern:
separate user input from rest of code
separate output formatting from function output
the code inside miles_to_laps is excessive
Now here is the code to try:
LAPS_PER_MILE = 4
# the only calculation, "pure" function
def miles_to_laps(miles):
return LAPS_PER_MILE * miles
# sorting out valid vs invalid input, "interface"
def accept_input(user_input):
try:
return float(user_input)
except ValueError:
raise ValueError("Cannot process input %s" % user_input)
if __name__ == "__main__":
# running the program
laps = miles_to_laps(accept_input(input()))
print ('%0.2f' % laps)
Hope this is not too overwhelming.
Update: second attempt
MILE = 1609.34 # meters per mile
LAP = 400 # track lap
LAPS_PER_MILE = MILE/LAP
def miles_to_laps(miles):
return LAPS_PER_MILE * miles
def laps_coerced(laps):
return '%0.2f' % laps
def accept_input(user_input):
try:
return float(user_input)
except ValueError:
raise ValueError("Cannot process input %s" % user_input)
def main(user_input_str):
miles = accept_input(user_input_str)
laps = miles_to_laps(miles)
print (laps_coerced(laps))
if __name__ == "__main__":
main(input())

binary output for python def function

New:
I am now working on a calculator for the terminal. I'm having the same error as before. but this time its telling me this: <function div at 0x7faf88c9e488>
code is at : https://github.com/mishiki1002/Solo-Calculater/blob/master/Solo-Main.py
Solved:
I have been programming in python for Year and a half. I have played around with the def function and variables. My current programming project is a RPG Fantasy type game. I am currently still at the begging and i am wondering what kind of output this is and why i am getting it. I believe it is some kind of binary bit.
<function showInstructions at 0x7fa8933162f0>
when i compile my code through my terminal using python main.py that is what i get. This is my full source code for the game. Please leave any comments and or suggestions for my programming. Also please tell me if my code is sloppy. I try and document all i can so its easier for me and programmers around me to read it.
Sincerely Josh
!/usr/bin/python3
#We will import this so that we have a random in counter chance for the game.
#this will all so prove use full when we have attacks sequences and Loot drops
from random import randint
class Character:
def __init__(self):
#This is the name that you have made for your character
self.name = ' '
#Amount of health for you character
self.health = 100
#Max amount of health for your character
self.health_max = 9999
#Damage class to define the attack methods needed to Battle?
def do_damage(self, enemy):
#Defining a varible called damage. Stating that the minimum damage can be 0. And No less than that, for either
damage = min(
# Stating that the minimum damage can be 0. And No less than that, for either character
max(radint(0, self.health)) - randint(0, enemy.health), 0), (enemy.health)
#Actual Damage System
enemy.health = enemy.health - damage
#Printing the product to the user/gamer
if damamge ==0: "%s evades %s's attack." % (enemy.name , self.name)
#If you land a hit
else: print("%s hurts %s!" % (self.name, enemy.name))
#printing your enemys health so you know how much left un-till 0
return enemy.health <= 0
class Enemy(Character):
def __init__(self, player):
#Since we declared that the enemy is a character it takes a characters paramaters
Character.__init__(self)
#It needs a name Like a Goblin
self.name = 'a Goblin'
#And it needs health
self.health = randint(1, 15 + player.health)
class Player(Character):
#Now we are delcaring a Side characters role
def __init__(self, player):
Character.__init__(self)
#when you check out the menu to see how your characters are doing you will see a meesage saying Normal and
#the amount of health they have
self.state = 'Normal'
#Now we set their health
self.health = 100
#Max Health
self.health_max = 9999
#Start Menu will be here
def showInstructions():
print("Sound_Soul")
print("----------")
print("Commmands:")
print(" 'go [direction]'")
print("The Cardinal Directions:")
print(" north")
print(" east")
print(" south")
print(" west")
print (showInstructions)
You are getting that because you are using only function name showInstructions instead of a call to the function like so showInstructions().
Edit:
One more thing: you don't need to also use print when calling your function as you already have print statements within your function. This causes "None" to be printed below your intended text because the function indeed return None by default.

changing a defineded function name depending on n term used

def usersdecision(n):
if option == n:
calculation.format(n)()
Is there a way to get calculation to become calculation + the value of n then (),
so if n=1 calculation would become calculation1().
Here is an inelegant way of doing it. Pass in a list, see how long it is and use the length to call different routines
import sys
def userd(*n):
if (len(n) == 1):
return calc1(n[0])
if (len(n) == 2):
return calc2(n[0],n[1])
if (len(n) > 2):
warn("bad input",n)
sys.exit(1)
def calc1(x):
return x*2
def calc2(x,x2):
return x**x2
assert userd(1) == 2
assert userd(2,3) == 8
print "it works"

trying to make a menu for a program and run a specific function

i am trying to make a fortune cookie program and i need a menu, then the chosen option's function will be executed. i get an error when i try to run the code, i need to be able to run the function that is chosen (i have only written the code for option 1 as i came across this error: (i need to append the new fortune onto the end of the text file)
Traceback (most recent call last):
File "N:\work\computing\fortune cookie\fortunecookie.py", line 9, in
if option == 1:
NameError: name 'option' is not defined
def menu():
print "Your options are: "
print "1-Add a new fortune"
print "2-Tell my fortune"
print "3-Exit"
option = raw_input("What do you want to do?")
menu()
if option == 1:
addfortune()
elif option == 2:
tellfortune()
elif option == 3:
exitProgram()
else:
print("Invlaid menu choice")
menu()
def addfortune():
newfortune = input("What is the new fortune?")
f = open("fortune.txt","w")
f.write(str(newfortune))
f.close()
menu()
It tries to access a variable from the global scope.
def menu():
global option
...
The above code should do it.
Read more about scopes here
Maby try to return that value instead of using a global variable:
def menu():
...
return option
And turn your conditions accordingly to it.
Some opinions about global variables: Why are global variables evil?