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

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()

Related

How can I solve a KeyError in my code, I'm a begginer

I'm resolving a basic problem consisting of make a list of products, the user choose the product and the amount of the product and the total price is printed. I get a keyerror in the line 22.
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[code] * quantify)
print("The total price is: $", totalPrice)
The error displayed is
Traceback (most recent call last):
File "main.py", line 30, in <module>
main()
File "main.py", line 22, in main
print("The price is $", relation[code])
KeyError: '5'
In this case I choose the product code "5".
When you use input it returns a string, not an integer. You can see this because the error message shows '5', not 5. The keys to your dictionary are integers, though, so the key you are providing in the statement (code) is not found.
You could instead use
print("The price is $", relation[int(code)])
A better format, at least in Python 3.6 and later, would be
print(f"The price is ${relation[int(code)]}")
for line 26, the problem is similar. Just convert to integers (or float, if there's a decimal point)
totalPrice = float(relation[int(code)] * int(quantify))
or
totalPrice = relation[int(code)] * float(quantify)
input in python receives data as a string, you need to typecast it
it is something along:
print("The price is $", relation[int(code)])
I think you should also follow the Python idiom EAFP (Easier to ask for forgiveness than permission) here when asking for user input as he could write literally everything but integers you expect:
while True:
code = input("Enter the product code: ")
try:
price = relation[int(code)]
except (ValueError, KeyError):
print("Error: Incorrect code value, try again!")
else:
break
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[int(code)] * quantify)
print("The total price is: $", totalPrice)
you need to take the input as integer because the input() take the default as a string so you can type it like quantify = int(input("Enter amount: "))
or another method is to use int() in the place where the calculations are like
totalPrice = float(relation[int(code)] * int(quantify))

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 )

Simple Python Program Loop Error

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)

Can't get this simple python program to work

I'm learning how to program in Python and got stuck on this simple exercise. I saved the code below to a file, test.py and ran it from my OSX command line using "python test.py" and keep getting an error message that I can't understand. My guess that the error is some fairly obvious thing that was overlooked :P
The error message follows the code:
def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
total = 40 * days
if days >= 7:
total = total - 50
elif days >= 3:
total = total - 20
return total
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) +
spending_money
thecity = raw_input("What city will you visit? ")
thedays = raw_input("How many days will you be traveling? ")
thespending_money = raw_input("How much spending money will you have? ")
trip_cost(thecity, thedays, thespending_money)
The console error message:
$ python test.py
What city will you visit? Los Angeles
How many days will you be traveling? 5
How much spending money will you have? 600
Traceback (most recent call last):
File "test.py", line 29, in <module>
trip_cost(thecity, thedays, thespending_money)
File "test.py", line 23, in trip_cost
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money
File "test.py", line 17, in rental_car_cost
total = total - 50
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Change thedays = raw_input("How many days will you be traveling? ") into thedays = input("How many days will you be traveling? "), and replace all other raw_input with input whenever you need a numerical value.
Afrer thecity = raw_input("What city will you visit? ") "thecity" is a string. Make integer from string with int:
thecity = int(raw_input("What city will you visit? "))
Similarly for other inputs.
thedays = raw_input("How many days will you be traveling? ")
raw_input returns a string. So, when you enter 5, you get the string '5' rather than the integer 5. Python does not automatically convert these for you when you try to add them, since that can lead to bigger surprises in some cases. Instead, it wants you to do the conversion explicitly, so that your code is always unambiguous in the case of any input (eg, "parse the string 'abc' as a base 10 integer" is always an error; trying to do "abc" + 5 via implicit conversion might decide to turn 5 into the string '5' and do string concatenation to give "abc5").
The way to do this is with the builtin int, which takes a string and gives you back an integer parsed from it:
thedays = int(raw_input("How many days will you be traveling? "))

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