def getType():
inp=int(input("\t<<<<<APARTMENT RENTAL PROGRAM>>>>>\n1 studio\n2 One-Bedroom\n3 Two-Bedroom\n4 Exit\nEnter Your Choice ::"))
while(inp>4 or inp<0):
print("Enter Valid Choice!!")
inp=int(input("\t<<<<<APARTMENT RENTAL PROGRAM>>>>>\n1 studio\n2 One-Bedroom\n3 Two-Bedroom\n4 Exit\nEnter Your Choice ::"))
if(inp==4):
return 4,0
furnished=input("Do you want the apartment furnished(Y/N)?")
valid=['y','n','Y','N']
while(furnished not in valid):
print("Enter Valid Choice!!")
furnished = input("Do you want the apartment furnished(Y/N)?")
if(furnished == 'Y' or furnished=='y'):
return inp,1
return inp,0
def determineRent(kind,furnish):
rents=[[400,600,750],[500,750,900],[600,925,1025]]
return rents[kind-1][0],rents[kind-1][furnish+1]
def displayRent(kind,furnish,rent,deposit):
if(kind==1):
print("\tStudio")
elif (kind == 2):
print("\tOne-Bedroom")
elif(kind==3):
print("\tTwo-Bedroom")
**if (furnish == 1):
print("\tFurnished")**
else:
print("\tUnfurnished")
print("\tDeposit : $",deposit)
print("\tRent : $",rent)
I am trying to get rid of my syntax issues and I cannot get my statement to work (bolded) I included the entire code for reference. I tried redefining furnish and changing it to furnished to no avail.
Code inside function definitions (indented under a def statement) is not executed until you call those functions, so will not cause NameErrors when running the program. I'm not sure if this is your intention, but based on the way you have your code indented above, the only code that is being executed is the final if statement and 2 print statements. This should make it clearer:
def getType():
*** definition of getType function ***
def determineRent(kind,furnish):
*** definition of determineRent function ***
def displayRent(kind,furnish,rent,deposit):
*** Definition of displayRent function ***
if (furnish == 1):
print("\tFurnished")
else:
print("\tUnfurnished")
print("\tDeposit : $",deposit)
print("\tRent : $",rent)
Since you never call the getType, determineRent, or displayRent functions, the interpreter just passes through storing those in memory without attempting to actually execute the code. So the first line it actually attempts to execute is:
if (furnish == 1):
But you haven't defined a variable called furnish at this point. That's why you get the NameError. If you write furnish = 1 above this line you'll see that it works (but next you get NameError for deposit instead).
while(furnished not in valid):
print("Enter Valid Choice!!")
That looks like an infinite loop to me :)
Assuming that these are functions called from another module, and that the code erroring out was suposed to be inside the displayRent function, your problem is indentation.
Python has an indentation based syntax, which means that your spaces/tabs at the beginning of the line matter a lot. In this case you have none on your line if (furnish == 1): and on the next lines, which means that Python will understand that they should be considered at the global level of that module. If you want it to be within the displayRent function you need to indent correctly, i.e. add leading tab/spaces to match the rest of the function code. Like this:
def getType():
inp=int(input("\t<<<<<APARTMENT RENTAL PROGRAM>>>>>\n1 studio\n2 One-Bedroom\n3 Two-Bedroom\n4 Exit\nEnter Your Choice ::"))
while(inp>4 or inp<0):
print("Enter Valid Choice!!")
inp=int(input("\t<<<<<APARTMENT RENTAL PROGRAM>>>>>\n1 studio\n2 One-Bedroom\n3 Two-Bedroom\n4 Exit\nEnter Your Choice ::"))
if(inp==4):
return 4,0
furnished=input("Do you want the apartment furnished(Y/N)?")
valid=['y','n','Y','N']
while(furnished not in valid):
print("Enter Valid Choice!!")
furnished = input("Do you want the apartment furnished(Y/N)?")
if(furnished == 'Y' or furnished=='y'):
return inp,1
return inp,0
def determineRent(kind,furnish):
rents=[[400,600,750],[500,750,900],[600,925,1025]]
return rents[kind-1][0],rents[kind-1][furnish+1]
def displayRent(kind,furnish,rent,deposit):
if(kind==1):
print("\tStudio")
elif (kind == 2):
print("\tOne-Bedroom")
elif(kind==3):
print("\tTwo-Bedroom")
if (furnish == 1):
print("\tFurnished")
else:
print("\tUnfurnished")
print("\tDeposit : $",deposit)
print("\tRent : $",rent)
Documentation for reference and better understanding: Python Docs - Indentation
Related
No matter how many times I google variations of my question, I cannot seem to find a solution. I am a beginner programmer, trying to build a game that randomly generates events as you progress through the stages. The problem I am running into are return statements, and passing the values between different modules. Each method for each file are inside of classes. They are all static methods, and calling these methods is not my problem. It is transferring the value of the variables. I'm not sure where I am going wrong, whether it is how I am structuring it, or if I just don't understand how these return statements work.
This is the first File I am starting from. Print statements will be filled out after everything functions properly.
def story():
print("---Intro Story Text here--- ... we will need your name, Traveler. What might it be?")
user_prompt = Introduction.PlayerIntroduction
name = user_prompt.player_info(1)
print(f"Welcome {name}!")
print(f"----After name is received, more story... how old might you be, {name}?")
age = user_prompt.player_info(2)
This is the file I am trying to get the values from. File: Introduction, Class: PlayerIntroduction
#staticmethod
def player_info(funct_select):
if funct_select == 1:
name = PlayerIntroduction.get_player_name()
player_name = name
elif funct_select == 2:
age = PlayerIntroduction.get_player_age()
player_age = age
return player_name, player_age
#staticmethod
def get_player_name():
print("\n\n\nWhat is your name?")
players_name = input("Name: ")
while True:
print(f"Your name is {players_name}?")
name_response = input("Yes/No: ")
if name_response == "Yes" or name_response == "yes":
name = "Traveler " + players_name
break
elif name_response == "No" or name_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_name()
else:
print("Please respond with 'Yes' or 'No'.")
return name
#staticmethod
def get_player_age():
print("\n\n\nHow old are you?")
age = input("Age: ")
while True:
print(f"Your age is {age}?")
age_response = input("Yes/No: ")
if age_response == "Yes" or age_response == "yes":
break
elif age_response == "No" or age_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_age()
else:
print("Please respond with 'Yes' or 'No'.")
return age
I would like to use the values for "name" and "age" throughout multiple modules/multiple methods within my program. But in order to get those values, I need to assign a variable to the function call.. Resulting in prompting the user to re-enter their name/age at later stages in the game. My idea to combat this was in the first method of this module, creating a conditional statement "if 'example' == 1: 'run the name prompt' and elif == 2: run age prompt, thinking the initial run with the arguments defined would run these prompts, store the values into the variables (name, age), and finally pass the values to the new variables that are NOT assigned to the function call (p_name, p_age), avoiding triggering the user prompt over and over. Ultimately, this failed, and as the code sits now I am getting:
UnboundLocalError: local variable 'player_age' referenced before assignment
Why is this? The only instance 'player_age' is called that is reachable at this point is in the return statement, indented in-line with the conditional statement. The code should read (If I understand incorrectly, please explain) from top to bottom, executing in that order. The 'if' condition is met, so it should run that. If I were to define 'player_name' and 'player_age' as null at the top of this method to avoid this error, then every time I would need to reference these values initially entered by the user, they would be re-assigned to 'null', negating everything I am trying to do.
Thank you all for your patience, I tried to explain what I was doing and my thought process the best I could. Any feedback, criticism, and flaws within my code or this post are GREATLY appreciated. Everything helps me become a better programmer!! (:
Python code to generate two random variables that can add up and give an answer
print("What is You Favorite Maths Operation \nAddition(a) \nSubstraction(s) \nMultiplication(M) \nDivision(d)")
#user input operator from the table given
class cooperators:
def choose(self):
return input("Choose One Of Them To Solve Some Interesting Problem:")
def operator(self,user):
#if you chose a then addition
if user =='a':
return True
#if you chose s then Substraction
elif user =='s':
return True
#if you chose m then multiplication
elif user =='m':
return True
#if you chose d then division
elif user =='d':
return False
def play(self,users):
randomNumber = random.randint(1, 10)
if users =='a':
print(f"Addition: {randomNumber} \n {randomNumber}")
print("Your answer: ")
print(f"Correct answer is: {randomNumber}+{randomNumber}")
t= caloperators()
t.choose()
t.operator()
t.play()
print(t.choose)
print(t.operator)
print(t.play)
I am not able to get an answer but getting errors and also if someone can complete the code it will really help to end this project and complete it.
t.operator()
You're not passing any arguments into this. hence the error.
You can do:
a = t.choose()
t.operator(a)
since choose() is returning the input.
You're then passing that input into a variable called a, which is then passed into operator(user).
in this case a == user.
You will then have the problem of not passing any arguments into play(users)
which you then can pass a into that too:
t.play(a)
I have a program that is supposed to show all classes in the external .txt file when the user presses "V", and is supposed to allow the user to lookup a specific class based off of its course code (EX. user types csce101 and it will print "Introduction to computer concepts"). However, I can't get the V and L functions to work properly. As it sits currently, the V function is only working because I called a break... but after it prints all the classes, it asks the user for a course code when it is not supposed to. That is what the L function is supposed to do. I am unsure on how to call a function inside of an if/elif loop. The function name just comes up as undefined. Is it possible with the way I have the code setup?
Python Code:
while True:
command = input("(V)iew, (L)ookup, or (Q)uit: ")
if command == "v":
break
elif command == "l":
print(f"{code}")
elif command == "q":
print("Goodbye!")
quit()
else:
print("Invalid command")
def getCourses():
courses = {}
with open("assignments/assignment-19/courses.txt") as file:
for line in file:
data = line.split(':')
code = data[0].strip()
className = data[1].strip()
courses[code] = className
return courses
def getDescription(courseList):
code = input("Enter course code: ").strip().lower()
if code in courseList:
print(f"{courseList[code]}")
else:
print(f"Sorry {code} is not in our system")
courseList = getCourses()
for classes in courseList:
print(f"{classes}: {courseList[classes]}")
getDescription(courseList)
.txt file contents
csce101: Introduction to Computer Concepts
csce102: General Applications Programming
csce145: Algorithmic Design 1
csce146: Algorithmic Design 2
csce190: Computing in the Modern World
csce201: Introduction to Computer Security
csce204: Program Design and Development
csce205: Business Applications Programming
Some general observations:
Functions, like any other object, need to be defined before they are
referenced/used. You aren't violating this, but you will be if you
fill in the rest of your while-loop. Ideally, you'll want a main
entry point for your program, so that it's clear in what order things
are being executed, and your functions are guaranteed to be defined
by the time flow-of-execution reaches the lines on which your functions are called.
It would make sense to define one function for each corresponding
command type (except for quit). You were on the right track here.
A couple questionable/redundant instances of f-strings (f"{code}" almost certainly doesn't do what you think it should.)
Prefer snake_case over camelCase when writing Python source code.
Your V command will terminate the loop (and the program)
prematurely. What if the user wants to print all courses, then a
description?
Here are my suggestions incarnate:
def get_courses():
courses = {}
with open("assignments/assignment-19/courses.txt", "r") as file:
for line in file:
data = line.split(":")
code = data[0].strip()
class_name = data[1].strip()
courses[code] = class_name
return courses
def display_courses(courses):
for key, value in courses.items():
print(f"{key}: {value}")
def display_description(courses):
code = input("Enter course code: ").strip().lower()
if code in courses:
print(courses[code])
else:
print(f"Sorry, \"{code}\" is not in our system.")
def main():
courses = get_courses()
while True:
command = input("(V)iew, (L)ookup or (Q)uit: ").lower()
if command == "v":
display_courses(courses)
elif command == "l":
display_description(courses)
elif commany == "q":
print("Goodbye!")
break
else:
print("Invalid command.")
# 'main' ends here
main()
I wrote a simple program about User sign_up & log_in System with Python.I used many self-defining functions to make codes elegant. Here is the 'choose_page' function:
def choose_page():
print('Welcome to the code system!')
print('****************************\n')
print('there are the three options:\n'
'1.sign up\n'
'2.log in\n'
'3.quit')
print('****************************\n')
option = eval(input('Please input your option:'))
return option
And here is 'sign_up' function:
def sign_up():
global customer
# global option
# global option2
..................
..................(many codes)
option2 = eval(input('Now you can log in the main page by inputting 2 or 0 to return the sign_page: '))
return option2
I also wrote 'log_in' and 'quit' self-defining functions,then I can company them as I want like this(this step without 'quit' function as it doesn't matter now):
if choose_page() == 1:
sign_up()
if sign_up() == 0:
choose_page()
elif sign_up() == 2:
log_in()
elif choose_page() == 2:
log_in()
I run it but got trouble seems like logic error:
When I got in 'choose_page' and input 1,it run into 'sign_up',at the end of the 'sign_up',I input either 2 or 0 it still run into the 'sign_up' again and again without stopping.
Is there any logic error when I company these self-defining functions?
Thanks for help in advance.
Every time you write sign_up() it's going to call it and run through the function. Python isn't smart. It doesn't go, "We've already run sign_up() before. I remember the answer. No need to run it again!" It does exactly what you tell it. If you write sign_up(), it calls sign_up().
To avoid the repeated prompts you need to save its result to a variable and only call the function a single time.
if choose_page() == 1:
sign_up_answer = sign_up()
if sign_up_answer == 0:
choose_page()
elif sign_up_answer == 2:
log_in()
Repeat that same idea for any of the other functions that have the same problem.
I am doing a school project and I need some help communicating between functions. This is what I have got so far
def difficuilty():
level = 0
while level >=4 or level == 0:
level = int(input("Please enter the difficulty (1/2/3)"))
if level == 1:
yesNo = input("you have chosen difficulty 1, is this correct? ")
if yesNo.upper() == 'Y':
level = 1
elif yesNo.upper() == 'N':
level = 4
else:
print ("You have entered the wrong thing")
elif level == 2:
yesNo = input("you have chosen difficulity 2, is this correct? ")
if yesNo.upper() == 'Y':
level = 2
elif yesNo.upper() == 'N':
level = 4
else:
print ("You have entered the wrong thing")
elif level == 3:
yesNo = input("you have chosen difficulity 3, is this correct? ")
if yesNo.upper() == 'Y':
level = 3
elif yesNo.upper() == 'N':
level = 4
else:
print ("You have entered the wrong thing")
return level
def question(level):
if level == 1:
print ("hi")
def main():
getName()
difficulty()
question(level)
I am trying to get the variable 'level' from the difficulty function to go into the question function so I can use it, when I run the program, it gives me an error which says 'NameError: Name 'level is not defined'. Can someone please help me. Thanks
The variable level is only defined within the scope of your two functions, but not at the scope of main(). You have to define a variable (called level) within the scope of main() in order to access it. Try:
def main():
getName()
level = difficulty()
question(level)
This way, the variable that is returned from difficulty() (named level within difficulty()) is accessible to main().
Also, is this your actual code? I notice some mistakes, like difficulty() being spelled two different ways, and a lack of indentation within difficuilty(), that will have unexpected results if you run this. Please post your verbatim code if you have it so that it's easier to tell what the specific problem is.
You need to retrieve the value of level that is returned from your difficult function
def main():
getName()
level = difficulty()
question(level)
I believe the global method does just that, it turns the local arg used within a function to a global one callable by all means.
def difficuilty():
level = 0
while level >=4 or level == 0:
level = int(input("Please enter the difficulty (1/2/3)"))
global level
That way (level) will be callable. One last thing, given your application I would go with Milo's answer, because using global method can have its cons.