What am I doing wrong with this? - python

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

Related

hackerrank python 3 string operation, resume function for 8 different strings

There are 6 test cases and 5 are getting passed based on python 3 on a string operations problem, but 1 test case is failing since inception.
Pls help me out. The question is as follows:
8 Strings are given in a function.
Remove spaces from both end of strings: first, second, parent, city
Capitalize : first, second, parent
Print Strings with a space : first, second, parent, city
Check if string : 'phone' only contains digits
Check if phone number starts with value in string 'start' and print the result(True or False)
Print : total no. of times 'strfind' appears in the strings : first, second, parent, city
Print : list generated by using split function on 'string1'
Find position of 'strfind' in 'city'
My Code is as follows: Let me know what wrong I have done. 5/6 test cases are passed only 1 test case failed for unknown reason. :(
def resume(first, second, parent, city, phone, start, strfind, string1):
first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isdigit())
print(phone[0]==start[0])
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))
Not too sure without being given details on the test case. However, number 5 may be incorrect as you are only checking if the first values of the strings are the same. This is not the same as checking if "phone number starts with value in string 'start'". I recommend using the following code instead:
print(phone.startswith(start))
In addition number 6 seems like it could cause some mismatches with overlapping strings. Instead I would suggest using:
print(first.count(strfind) + second.count(strfind) + parent.count(strfind) + city.count(strfind))
first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isnumeric())
print(phone.startswith(start))
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))

Python print and input on same line

I am trying to execute this but not able to.
Can someone assist?
teamname1 = print(input((plyer1,' Name of your team? '))
teamname2 = print(input(plyer2,' Name of your team? '))
print(teamname1)
print(teamname2)
Three issues:
the first line contains one parenthesis too many
input() takes only one argument, the prompt. If plyer1 is a
string, you must concatenate it
same as in comment: print() does not return anything, and can be
omitted because the prompt of the input() command is already
displayed.
You probably need something like this:
plyer1 = 'parach'
plyer2 = 'amk'
teamname1 = input(plyer1 + ' Name of your team? ')
teamname2 = input(plyer2 + ' Name of your team? ')
print(teamname1)
print(teamname2)
I'm not exactly sure what you're trying to do with the teamname variables. If you could modify the question/code it would help a lot.
As far as print and input on the same line, I think this might be what you're going for.
print("player1" + " " + input("Name of your team: "))
print("player2" + " " + input("name of your team: "))
P.S. There are many tutorials on-line that could help. Make sure to look around first, then come here.

How to concatenate multiple variables?

I have three UV sensors - integers output; one BME280 - float output (temperature and pressure); and one GPS Module - float output.
I need to build a string in this form - #teamname;temperature;pressure;uv_1;uv_2;uv_3;gpscoordinates#
and send them via ser.write at least one time per second- I'm using APC220 Module
Is this the right (and fastest) way to do it?
textstr = str("#" + "teamname" + ";" + str(temperature) + ";" + str(pressure) + ";" + str(uv_1) + ";" + str(uv_2) + ";" + str(uv_3) + "#")
(...)
ser.write(('%s \n'%(textstr)).encode('utf-8'))
You may try something like this:
vars = [teamname, temperature, pressure, uv_1, uv_2, uv_3, gpscoordinates]
joined = ';'.join( map( str, vars ))
ser.write( '#%s# \n', joined )
If using python 3.6+ then you can do this instead
textstr = f"#teamname;{temperature};{pressure};{uv_1};{uv_2};{uv_3}# \n"
(...)
ser.write((textstr).encode('utf-8'))
If teamname and gpscoordinates are also variables then add them the same way
textstr = f"#{teamname};{temperature};{pressure};{uv_1};{uv_2};{uv_3};{gpscoordinates}# \n"
(...)
ser.write((textstr).encode('utf-8'))
For more info about string formatting
https://realpython.com/python-f-strings/
It might improve readability to use python's format:
textstr = "#teamname;{};{};{};{};gpscoordinates#".format(temperature, pressure, uv_1, uv_2, uv_3)
ser.write(('%s \n'%(textstr)).encode('utf-8'))
assuming gpscoordinates is text (it's not in your attempted code). If it's a variable, then replace the text with {} and add it as a param to format.

Need Variables to Add, Not Concatenate Python [duplicate]

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}?"

adding two numbers that are in variables

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.

Categories