This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
Here's the coding I've done:
from math import *
from time import sleep
def vacation():
print("Time to plan for a vacation.")
sleep(1)
dates = input("Let's start with the dates. What day are you getting there, and what day are you leaving? For formatting, you can use month/day-month/day.")
sleep(1)
location = input("Now where are you traveling to?")
sleep(1)
ticketCost = input("What is the cost of a two-way ticket to " + location + " and back?")
sleep(1)
dayOne = input("What is the cost for at least two meals on the first day?")
dayTwo = input("What is the cost for at least two meals on the second day?")
sleep(1)
hotel = input("What is the name of the hotel you are staying at?")
hotelCost = input("What is the cost for one night at (the) " + hotel + "?")
sleep(1)
print("Vacation! Going to " + location + " for " + dates + ".")
print("-------------------------------")
print("Total cost of the trip:")
print("-------------------------------")
sleep(1)
print("Plane Ticket: " + ticketCost)
sleep(1)
print("Estimate Cost of Meals (Day One): " + dayOne + ".")
sleep(1)
print("Estimate Cost of Meals (Day Two): " + dayTwo + ".")
sleep(1)
print("One Night at (the) " + hotel + ": " + hotelCost + ".")
sleep(1)
**total = hotelCost + dayOne + dayTwo + ticketCost**
**totalExtra = total + 50
print("The total is: " + total + ".")**
sleep(1)
print("Make sure you leave some room for souvenirs, pay tolls, and other expenses. Additional $50 is added for this, and that total is: " + totalExtra + ".")
print("-------------------------------")
sleep(1)
print("Enjoy your vacation!")
vacation()
The problem areas are in bold. I do not know what to do, I've tried using int(), str(), and etc in multiple places. The total shouldn't be gibberish (ie, "843290842"). Am I missing something?
The input function returns a string, not an integer. Just cast them everywhere:
dates = int(input("Let's start with the dates. What day are you getting there, and what day are you leaving? For formatting, you can use month/day-month/day."))
etc...
A couple of other points
If you're going to add these all together later consider putting them in a collection instead of just a whole bunch of loose variables. A dictionary would let you keep the names so:
costs = {}
costs['dates'] = int(input("Let's start with the dates. What day are you getting there, and what day are you leaving? For formatting, you can use month/day-month/day."))
At the end you can easily get the total by just looping over the dictionary
total = sum(costs.values())
Just remember to leave out values that are supposed to be strings like hotel, which should probably be called hotel_name instead.
Lastly, you should try out string interpolation (this depends on your Python version but for 3.6+):
"What is the cost for one night at (the) " + hotel + "?"
becomes
f"What is the cost for one night at (the) {hotel}?"
Related
def trip_planner_welcome (name):
print("Welcome to tripplanner v1.0 " + name)
def destination_setup(origin, destination, estimated_time, mode_of_transport="Car"):
print("Your trip starts off in " + origin)
print("And you are traveling to " + destination)
print("You will be traveling by " + mode_of_transport)
print("It will take approximately " + estimated_time + " hours")
I got an error that estimate_time should be put in str(). Why can't numbers be numbers when it's being concatenated in between strings?
As #NickODell said on the comments + operator has different meanings depending on the types it is used on, you can either convert the numerical value (int) to str or you can use f strings which does this conversion automatically:
print(f"It will take approximately {estimated_time} hours")
first of all, i'm very new at programming and starting my courses in college, i'm still trying to get the hang of it, please be nice. // i'm doing homework and it's this thing about calculating my age in the year of 2050, i've followed the instructions and everything and i get a syntax error in the print("I will be") line, can anyone tell me why and what am i doing wrong?
YEAR = "2050"
myCurrentAge = "18"
currentYear = "2019"
print("myCurrentAge is" + str(myCurrentAge)
myNewAge = myCurrentAge + (YEAR - currentYear)
print("I will be" + str(myNewAge) + "in YEAR.")
stop
First, as #ObsidianAge pointed out, your print("myCurrentAge is" + str(myCurrentAge) line is missing the second closing parenthesis, it should be like this print("myCurrentAge is" + str(myCurrentAge)).
Next is the error that you are talking about. You are calculating here myNewAge = myCurrentAge + (YEAR - currentYear) a bunch of string variables. You need to parse first your variables into int like this :
myNewAge = int(myCurrentAge) + (int(YEAR) - int(currentYear))
#then print,
print("I will be " + str(myNewAge) + " in YEAR" + YEAR)
To solve the confusion in the comments and I saw that you are following this answer's suggestion so here's the entire code:
# int variables
YEAR = 2050
myCurrentAge = 18
currentYear = 2019
# printing current age
print( "myCurrentAge is " + str(myCurrentAge))
# computing new age, no need to parse them to int since they already are
myNewAge = myCurrentAge + (YEAR - currentYear)
# then printing, parsing your then int vars to str to match the entire string line
print("I will be " + str(myNewAge) + " in YEAR " + str(YEAR))
Also, after you fix the bracket thing mentioned by #ObsidianAge, you will have to fix another thing.
All your variables are Strings right now since you have declared them within double-quotes. To be able to do what you intend to do, you will need to convert them to integers.
I'd recommend assigning them integer values in the very beginning by removing the quotes. With your current code, it will just concatenate all your variable strings together when you use the + operator. So your new declarations will look like this:
YEAR = 2050
myCurrentAge = 18
currentYear = 2019
I just started working with python 3 and I'm using a command shell. Why is there an exception with the code below?
name = input("whats your name: ")
age = input("what is your age: ")
work = input("how long will you be working: ")
print("Good luck " + name + " you will be " + int(age) + int(work) + " years old")
Python debugger generates error "should be str vs int".
The problem is string + integer doesn't work (for good reason). Instead we need to convert back to a string in your method.
But don't write strings like that. As you can see it is pretty error prone. Instead, use string formatting
print("Good luck {} you will be {} years old".format(name, int(age) + int(work)))
or even better in python 3.6
print(f"Good luck {name} you will be {int(age) + int(work)} years old")
Try this:
print("Good luck " + name + " you will be " + str(int(age)) + int(work)) + " years old")
Most likely because you are concatenating strings and adding ints at the same time. Add them together then convert to string and concatintate afterwards.
Ideally you are converting the str to int by int(age) and again trying to concatenate string with integer. By default, the input() gets the data in string.
please avoid using int() conversion. Also if needed check type(var) and try to concatenate.
This question already has answers here:
Print Combining Strings and Numbers
(6 answers)
Closed 5 years ago.
I would like to include the user's response to 'age' in the answer.
However, including 'age' returns an error. Seems to be because it is preceded by float. Is there a way to include the response to 'How old are you?'?
Here's the code:
name = input("What is your name? ")
age = float(input("How old are you? "))
answer1 = (age + "!? That's very old, " + name + "!")
answer2 = (age + "? You're still young, " + name + ".")
if age > 60:
print(answer1)
if age < 60:
print(answer2)
Unlike e.g. Java, Python does not automagically call the __str__ method when concatenating objects some of which are already strings. The way you do it, you would have to convert it to a string manually:
answer1 = (str(age) + "!? That's very old, " + name + "!")
Consider, however, using proper string formatting in the first place:
answer1 = ("{age}!? That's very old, {name}!".format(age=age, name=name))
You have a few options here.
Convert age to string:
answer1 = (str(age) + ...)
Use old-style string formatting:
answer1= "%f!? That's very old, %s!" % (age, name)
Use Python 3.6's excellent string interpolation:
answer1 = f"{age}!? That's very old, {name}!"
I would go with the third.
I'm doing a maths quiz that asks people questions and at the end it would write their name and score to a file. I want there to be a date before the scores but the way I do it:
file1.write(time.strftime("%d/%m/%y" + "\n"))
file1.write("Name: ")
file1.write(Name + "\n")
file1.write("Score: ")
file1.write(str(Score)+ "\n")
file1.write("" + "\n")
file1.close()#
Writes the date every time someone finishes the quiz. I want it to write the date only once before a person's results unless it's a new day. For example today is 10/06/2015, it would print this date before the results of the first person that attempts this quiz and then not print the date again until it's a new day like 11/06/2015. Thanks
Fast and dirty solution:
with open("results.txt", "r+") as f:
if time.strftime("%d/%m/%y") not in f.read():
f.write(time.strftime("%d/%m/%y" + "\n"))
1 - Get today's date by:
myToday = time.strftime('%x')
2 - Check whether the date has changed or not:
if time.strftime('%x') != myToday:
myToday = time.strftime('%x') # change today var if it's a new date.
file1.write(myToday+'\n')