Simple Python Program Loop Error - python

Can anyone help me see what's going wrong in this? I'm getting an error at the end: "NameError: name 'age' is not defined". I'm just getting into Python and programming in general, and don't see what to change to fix it.
import random
def greeting():
print("Hi there, welcome to the world's simplest tv suggestion program!")
print("")
def get_birth_year():
birth_year = 0
birth_year = (input("Please enter your year of birth: "))
is_valid = is_year_valid(birth_year)
while not is_valid:
birth_year = input("Please enter a four digit year of birth: ")
is_valid = is_year_valid(birth_year)
birth_year = int(birth_year)
return birth_year
def is_year_valid(birth_year):
try:
birth_year = int(birth_year)
is_valid = True
except ValueError:
is_valid = False
return is_valid
def calculate_age(birth_year):
age = 0
age = 2018 - birth_year
return age
def show_rec_output(age):
print("Based on your age, a good Netflix show for you to watch would be:")
adult = ["Master of None", "Unbreakable Kimmy Schmidt", "Black Mirror", "Godless",
"Dear White People", "Grace and Frankie", "Jessica Jones"]
all_ages = ["The Crown", "The Great British Bake Off", "Jessica Jones",
"Sherlock", "A Series of Unfortunate Events", "Big Mouth"]
if age >= 18:
print(random.choice(adult))
else:
print(random.choice(all_ages))
def another_rec():
second_rec = ""
second_rec = (input("Would you like another recommendation Y/N: "))
while second_rec == str("Y"):
show_rec_output(age)
second_rec = (input("Would you like another recommendation? Y/N: "))
else:
print("Go make some popcorn!")
def main_module():
greeting()
birth_year = get_birth_year()
age = calculate_age(birth_year)
show_rec_output(age)
another_rec()
main_module()
The assignment I'm trying to complete requires one piece of input, one piece of output, two loops, input validation, and everything in modules.

The problem is here:
def another_rec():
second_rec = ""
second_rec = (input("Would you like another recommendation Y/N: "))
while second_rec == str("Y"):
show_rec_output(age)
You don't have age here, but you're trying to use it anyway.
To fix it, you want to do the exact same thing you do with show_rec_output. First, add an age parameter to the another_rec function:
def another_rec(age):
… and then, pass the value in from main_module:
show_rec_output(age)
another_rec(age)

Related

Creating a menu using a dictionary

I need help with the below code please, I am trying to create a piece of code that displays true or false at the beginning with a given course code using a function. four letters, 3 digits, and a 'space' in between them if that condition is true then the program will ask the user to choose the menu with 6 options using a dictionary. please explain to me where did I go wrong.
Thank you
What I have tried:
def CourseCode(input_word):
COURSES = ['SCIN', 'ENGG', 'MATC', 'BCSE', 'BCMS', 'ENGS', 'MGMT', 'COMM']
VALID_DIGITS = (1, 2, 3, 4, 6)
if user_code == 'SCIN 123':
return True
else:
return False
def user_menu():
add_course = {}
add_course['1'] ="Add new Course:"
add_course[True] = "Course added"
add_course[False]= "Invalid course code: The format is XXXX 111"
list_course = {}
list_course['2'] = "List Course:"
print("SCIN 123", "ENGG 101", "MATC 354", "MATC 355", "BCSE 202", "CCMS 100", "ENGS 202" )
stu_enrol = {}
stu_enrol['3'] = "Enrol Student"
stu_enrol = input("Please enter student family name: ")
stu_enrol[new_student]=[]
print(stu_enrol)
stu_enrol = input(f"Please enter student first initial {new_student}: ")
stu_enrol = input(f"Please enter course to enrol or X to finish {new_student}: ")
if key_data in stu_enrol:
print("Successfully enrolled.")
elif(key_data != add_course ):
print("Sorry you need to enrol in at least two courses")
elif(key_data != stu_enrol):
print("Sorry, already enrolled in that course")
elif(key_data != CourseCode):
print("Sorry, that course does not exist.")
else:
print("Sorry, a maximum of four courses are allowed")
lis_enr_stu = {}
lis_enr_stu['4']={"List Enrolments for a Student"}
lis_all_enr = {}
lis_all_enr['5']={"List all Enrolments"}
user_exit['6'] = "Quit"
if action() is False:
break
input_word = input("Please select menu choice: ")
CourseCode = CourseCode(input_word)

Variables dont change to "int" - stuck at "str"

In my program I need to make simple math calc, but my variables are defind at str and i need to make it int for the calc and sum .
ex:
When age=40, in return I got 404040404040 (6 times the num 40)
is read the res like "str" and I need "int".
def check_age(age):
age = int(age)
return 30 * 6 if age >= 30 else 0
def just_married():
sum_married = 0
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
sum_married = sum_married + check_age(woman_age)
husband = int(input("Please enter the husband age : ").strip())
sum_married = sum_married + check_age(husband)
return int(sum_married)
def children_age(number_of_children):
sum_children = number_of_children*50
return int(sum_children)
def work_hard():
print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ")
wife_work = input()
print("for HUSBAND = Are you working part-time (0.5) or full-time (1)? : ")
husband_work = input()
sum_work = (wife_work+husband_work)*75
return int(sum_work)
def main():
sum_func = 0
print("The following is a program aimed at examining eligibility conditions "
"for participation in the tender Housing for the occupant.")
sum_func += just_married()
print("How many children over the age of 18 do you have? : ")
children = input()
sum_func += children_age(children)
sum_func += work_hard()
program_number = 599
if sum_func > program_number:
print("you got : " + str(sum_func) + " points ")
else:
print("sorry, but you need " + str(program_number-sum_func) + " point to join the program. try next time.")
main()
edit:
i edit the code, with the new change at func"check_age", and update the full code.
this is the input :
The following is a program aimed at examining eligibility conditions for participation in the tender Housing for the occupant.
Please enter the wife age [we know that is not ok ask woman about she's age] : 40
Please enter the husband age : 50
How many children over the age of 18 do you have? :
4
for WIFE - Are you working part-time (0.5) or full-time (1)? :
1
for HUSBAND = Are you working part-time (0.5) or full-time (1)? :
1
you got : 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111155555555555555555555555555555555555555555555555915 points
Process finished with exit code 0
In your function check_age:
def check_age(age):
age = int(age)
return 30 * 6 if age >= 30 else 0
Also, consider changing these lines:
print("Please enter the wife age [we know that is not ok ask woman about she's age] : ")
woman_age = input(int)
To this:
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
Explanation:
input takes a string, prints it and wait for user input.
str.strip removes trailing spaces
int convert a variable to an integer
Once you've sanitized your inputs, you can remove the explicit conversion to int in check_age:
def check_age(age):
return 30 * 6 if age >= 30 else 0
[EDIT] A few more suggestion:
create a function sanitize_input that takes a text, ask for input
ad returns an integer. Then use it anywhere to replace print...input
create logic blocks that make sense: For example, the main function contains all the texts that print out to the screen and store all inputs for later. Then, only process the variables in one function like check_eligibility or something where you do all the calculations. If you do that, you code will be more understandable and less error prone, for you and for the people who try to help you
The string -> number conversions have to be done before you attempt any calculations, it is too late at the time of return, as the strange things have happened already. Remember/learn that Python can add strings (which is common to many languages, "1"+"1" is "11" in various other languages too), and on top of that, it can also multiply them with integer numbers, "1"*5 is "11111".
If you assume correct input from the user, the simplest thing is to do the conversion in the input lines, which already happens in just_married, but not in the other places.
And of course remember that when you expect an input like 0.5, those should be converted to float.
def check_age(age):
#age = int(age) - removed this one, should happen at input
return 30 * 6 if age >= 30 else 0
def just_married():
sum_married = 0
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
sum_married = sum_married + check_age(woman_age)
husband = int(input("Please enter the husband age : ").strip())
sum_married = sum_married + check_age(husband)
return sum_married # removed int(), it is already an integer
def children_age(number_of_children):
sum_children = number_of_children*50
return sum_children # removed int(), it was too late here
# and it should happen at input
def work_hard():
print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ")
wife_work = float(input()) # added float()
print("for HUSBAND = Are you working part-time (0.5) or full-time (1)? : ")
husband_work = float(input()) # added float()
sum_work = (wife_work+husband_work)*75
return int(sum_work) # int() may stay, depending on what should happen
# with fractions - they are just thrown away now
def main():
sum_func = 0
print("The following is a program aimed at examining eligibility conditions "
"for participation in the tender Housing for the occupant.")
sum_func += just_married()
print("How many children over the age of 18 do you have? : ")
children = int(input()) # added int()
sum_func += children_age(children)
sum_func += work_hard()
program_number = 599
if sum_func > program_number:
print("you got : " + str(sum_func) + " points ")
else:
print("sorry, but you need " + str(program_number-sum_func) + " point to join the program. try next time.")
main()

python classes, def __init__(): and input statements

I am trying to define a class called 'Vacation' to store information about the user once they have answered a set of input statements (my project is a vacation program where the user answers a set of questions in order to receive a randomly generated vacation itinerary). My professor told me to put all of my questions (aka input statements) within my constructor, however I keep getting an error saying I have a syntax error although I am not sure why. I have tried putting the different variable names in the () of my constructor but this does nothing (I thought maybe I had a syntax error because I forgot to include one of the variable names - specifically the error is coming from 'excursions'). I am fairly new to Python (just started in January) so my knowledge of the programming language is very limited (plus I just learned classes about 2 weeks ago). Any and all help/feedback/ideas would be greatly appreciated!
class Vacation:
def __init__ (self, num_guests, max_price, vacay_len, excursions, user_input, excursions_price, excursions_num, user_preference):
user_input = input("Would you like a (R)andomly generated vacation or a (T)ailored vacation?: ")
num_guests = int(input("Please enter number of guests: "))
max_price = float(input("Please enter your maximum willingness to pay (ie. 700): "))
vacay_len = int(input("Please enter how many days you would like your vacation to be: ")
excursions = (input("Would you like to include excursions while on vacation? (Y/N) : ")).upper()
if excursions == "Y":
excursions_num = int(input("How many excursions would you like to sign up for (up to 2): "))
excursions_price = float(input("How much would you like to spend on each excursion? : "))
else:
print("Let's get to exploring!")
user_preference = user_input
self.user_preference = user_preference
self.num_guests = num_guests #number of guests
self.max_price = max_price #maximum price range
self.housing_price = .3(self.max_price) #housing budget allocation
self.vacay_len = vacay_len #vacation length
self.excursions_price = excursion_price #price for each excursion
self.excursions_num = excursions_num #number of excursions
You are missing closing bracket on this line:
vacay_len = int(input("Please enter how many days you would like your vacation to be: "))
You have a typo excursion_price should be excursions_price as below:
self.excursions_price = excursions_price #price for each excursion
You also need to add * for multiplication here:
self.housing_price = .3*(self.max_price)
You can remove the variables from the __init__ function in this case since they will be provided by the users input to the programme.
I would recommend using a python IDE which will highlight the issues for you in red.
Not sure if this is what you want but the following code seems to work:
class Vacation:
def __init__ (self):
user_input = input("Would you like a (R)andomly generated vacation or a (T)ailored vacation?: ")
num_guests = int(input("Please enter number of guests: "))
max_price = float(input("Please enter your maximum willingness to pay (ie. 700): "))
vacay_len = int(input("Please enter how many days you would like your vacation to be: "))
excursions = (input("Would you like to include excursions while on vacation? (Y/N) : ")).upper()
if excursions == "Y":
excursions_num = int(input("How many excursions would you like to sign up for (up to 2): "))
excursions_price = float(input("How much would you like to spend on each excursion? : "))
else:
print("Let's get to exploring!")
user_preference = user_input
self.user_preference = user_preference
self.num_guests = num_guests #number of guests
self.max_price = max_price #maximum price range
self.housing_price = .3(self.max_price) #housing budget allocation
self.vacay_len = vacay_len #vacation length
self.excursions_price = excursion_price #price for each excursion
self.excursions_num = excursions_num #number of excursions
As suggested by Steve I removed your variables from the constructors parameters as you probably won't be passing arguments. At the Excursions line you were simply missing a closing )

First steps in python: how to combine two lists

So I just started learning a few basics with Python. Since I am a pretty practical person, I enjoy doing it with the book "Automate the boring stuff with Python".
No there is a chapter introducing lists in python and their advantages.
To be practical one should write a code which asks the user to enter cat names, which then will be added to the list. If no cat name is added anymore, all the cat names should be displayed.
Until now, fair enough. So I thought I should give it a try and go a small step further and extend the functionality by adding the ages of the cats. The desired result would be that the user is asked for the name input, then the age input, the name input again and the age input again and so on. If the user doesn´t put in a name again, it should list the cats with the respective ages.
I created a second list and also the second input and everything kinda works but I just dont know how to combine the both lists or rather the values.
It just gives me the two names first and then the two ages.
Is anyone happy to help me with this beginner problem?
Thanks in advance
catNames = []
catAges = []
while True:
print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter
nothing to stop.)")
name = input()
while name !="":
print("Enter the age of cat ")
age = input()
break
if name == "":
print("The cat names and ages are: ")
for name in catNames:
print(" " + name)
for age in catAges:
print(" " + age)
break
catNames = catNames + [name]
catAges = catAges + [age]
I think you're looking for zip:
catNames = ['Fluffy', 'Whiskers', 'Bob']
catAges = [5, 18, 2]
catZip = zip(catNames, catAges)
print(list(catZip))
Out:
[('Fluffy', 5), ('Whiskers', 18), ('Bob', 2)]
In general you would use dictionaries for this kind of task.
But if you were to use lists for your problem, it could be implemented like this:
catNames = []
catAges = []
while True:
print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter nothing to stop.)")
name = input()
while name !="":
print("Enter the age of cat ")
age = input()
break
if name == "":
print("The cat names and ages are: ")
for i in range(len(catNames)):
print("Cat number",i, "has the name", catNames[i], "and is", catAges[i], "years old")
break
catNames = catNames + [name]
catAges = catAges + [age]
If I can understand correctly you want it to print the age and the name together?
Well if thats so you can do it like this:
catNames = []
catAges = []
while True:
name = input("Enter the name of Cat {} (Or enter nothing to stop): ".format(str(len(catNames) + 1)))
while name != "":
age = input("Enter the age of {}: ".format(name)) # Takes inputted name and adds it to the print function.
catNames.append(name) # Adds the newest name the end of the catNames list.
catAges.append(age) # Adds the newest age the end of the catNames list.
break
if name == "":
print("\nThe cat names and ages are: ")
for n in range(len(catNames)):
print("\nName: {}\nAge: {}".format(catNames[n], catAges[n]))
break
Resulting output:
Enter the name of Cat 1 (Or enter nothing to stop): Cat1
Enter the age of Cat1: 5
Enter the name of Cat 2 (Or enter nothing to stop): Cat2
Enter the age of Cat2: 7
Enter the name of Cat 3 (Or enter nothing to stop): # I hit enter here so it skips.
The cat names and ages are:
Name: Cat1
Age: 5
Name: Cat2
Age: 7
If you have any issues with what I did, please just ask.

How to get a difference between two input variables in Python

I'm currently working on a program, in Python. I have came over a slight patch. What I'm trying to do is simple. Calculate the difference between two numbers that the user has input into the program.
nameA = input("Enter your first German warriors name: ")
print( nameA,"the noble.")
print("What shall",nameA,"the noble strength be?")
strengthA = input("Choose a number between 0-100:")
print("What shall",nameA,"the noble skill be?")
skillA = input("Choose a number between 0-100:")
#Playerb
nameB = input("Enter your first German warriors name: ")
print( nameB,"the brave.")
print("What shall",nameB,"the noble strength be?")
strengthB = input("Choose a number between 0-100:")
print("What shall",nameB,"the brave skill be?")
skillB = input("Choose a number between 0-100:")
I' trying to calculate the difference between what the user has input for StrengthA and StrengthB.
This question maybe a little noobish. But, we all have to learn.
Thanks.
Just use the - operator, then find the abs() of that to get the difference between two numbers.
abs(StrengthA - StrengthB)
However you must first make sure you are working with integers. Do this by:
StrengthA = int(input()) # Do the same with StrengthB.
EDIT:
To find that overall divided by five, you would just do:
(abs(StrengthA - StrengthB)) / 5
Code structure is really great for making your program easier to understand and maintain:
def get_int(prompt, lo=None, hi=None):
while True:
try:
value = int(input(prompt))
if (lo is None or lo <= value) and (hi is None or value <= hi):
return value
except ValueError:
pass
def get_name(prompt):
while True:
name = input(prompt).strip()
if name:
return name.title()
class Warrior:
def __init__(self):
self.name = get_name("Enter warrior's name: ")
self.strength = get_int("Enter {}'s strength [0-100]: ".format(self.name), 0, 100)
self.skill = get_int("Enter {}'s skill [0-100]: " .format(self.name), 0, 100)
def main():
wa = Warrior()
wb = Warrior()
str_mod = abs(wa.strength - wb.strength) // 5
if __name__=="__main__":
main()

Categories

Resources