basic strings and variables python - python

Write a function, called introduction(name, school) that takes, as input, a name (as a string) and a school, and returns the following text: “Hello. My name is name. I have always wanted to go to school.”
This is my code
def introduction("name","school"):
return ("Hello. My name is ") + str(name) + (". I have always wanted to go to The") + str(school) + (".")
I'm getting this error:
Traceback (most recent call last):
File "None", line 5, in <module>
invalid syntax: None, line 5, pos 23

def introduction("name","school"):
should be
def introduction(name,school):
The names you provide as the formal parameters of the function are essentially variables that the values of the actual parameters get assigned to. Including a literal value (like a string) wouldn't make much sense.
When you call or invoke the function, that is where you provide a real value (like a literal string)
def introduction(name,school):
return ("Hello. My name is ") + str(name) + (". I have always wanted to go to The") + str(school) + (".")
print introduction("Brian","MIT")

The definition of the function should take variables and not strings. When you declare, "introduction("name","school"):", that is what you are doing. Try this:
def introduction(name, school):
Here:
>>> def introduction(name, school):
... return ("Hello. My name is ") + str(name) + (". I have always wanted to go to The") + str(school) + (".")
...
>>> print introduction("Sulley", "MU")
Hello. My name is Sulley. I have always wanted to go to TheMU.
>>>

The arguments to the function are variable names, not string constants, and therefore should not be in quotes. Also, the parentheses around the string constants and the conversions of the arguments to strings in the return statement are not necessary.
def introduction (name,school):
return "Hello. My name is " + name + ". I have always wanted to go to " + school + "."
Now, if you call the function like print(introduction("Seth","a really good steak place")) # Strange name for a school... then the arguments you're calling the function with are string constants and so these you should put in quotes.
Of course, that doesn't apply if the arguments aren't constants...
myname = "Seth"
myschool = "a really good steak place" # Strange name for a school...
print(introduction(myname,myschool))
...and so you are instead providing the variables myname and myschool to the function.

Related

Does string formatting not work within an input() function?

My code:
new_account = sys.argv[1]
confirm_new = input("Would you like to add {} to the dictionary?" +
"\ny or n\n".format(new_account))
This doesn't format the string to place the variable in place of {}. What's up?
This has nothing to do with input. It's just that addition has lower precedence than method calls:
>>> "{}" + "b".format('a')
'{}b'
Normally I just use automatic string concatenation if I have a multi-line string (just omit the +):
confirm_new = input("Would you like to add {} to the dictionary?"
"\ny or n\n".format(new_account))

Trouble inputting interger values into an SQL statement within ArcGIS

So I am defining a function for use in a ArcGIS tool that will verify attributes, catch errors, and obtain user input to rectify those error. I want the tool to select and zoom to the segment that is being currently assessed so that they can make an informed decision. This is what I have been using, and it works well. But the CONVWGID is the variable that will be changing, and I'm not sure how to input that variable into an SQL statement without causing errors.
This is how I had tested the logic:
def selectzoom():
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", " [CONVWGID] = 10000001")
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
Then I needed to work the variable into the function in order to accept different CONVWGID values, which gives me a Runtime/TypeError that I should have known would happen.
Runtime error -
Traceback (most recent call last): - File "string", line 1, in module - TypeError: cannot concatenate 'str' and 'int' objects
def selectzoom(convwkgid):
delimfield = '" [CONVWGID] = ' + convwkgid + ' "'
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", delimfield)
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
And when I alter the delimfield line to change the integer into a string, it selects all of the attributes in the entire feature class. Not just the one that had been passed via the function call.
delimfield = '"[CONVWGID] = ' + str(convwkgid) + '"'
I'm not amazing with SQL and maybe I'm missing something basic with this statement, but I can't figure out why it won't work when I'm basically giving it the same information:
"[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"'
It turned out to be the extra inclusion of Double quotes inside of my single quotes that raised this problem.
Thanks to #Emil Brundage for the help!
Let's say convwkgid = 10000001
'"[CONVWGID] = ' + str(convwkgid) + '"' doesn't equal "[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"' would actually be '"CONVWGID] = 10000001"'
Try instead:
'[CONVWGID] = ' + str(convwkgid)

How to define a variable inside the print function?

I am a newbie in this field, and I am trying to solve a problem (not really sure if it is possible actually) where I want to print on the display some information plus some input from the user.
The following works fine:
>>> print (" Hello " + input("tellmeyourname: "))
tellmeyourname: dfsdf
Hello dfsdf
However if I want to assign user's input to a variable, I can't:
>>> print (" Hello ", name = input("tellmeyourname: "))
tellmeyourname: mike
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
print (" Hello ", name = input("tellmeyourname: "))
TypeError: 'name' is an invalid keyword argument for this function
I have researched inside here and other python documentation, tried with %s etc. to solve, without result. I don't want to use it in two lines (first assigning the variable name= input("tellmeyourname:") and then printing).
Is this possible?
Starting from Python 3.8, this will become possible using an assignment expression:
print("Your name is: " + (name := input("Tell me your name: ")))
print("Your name is still: " + name)
Though 'possible' is not the same as 'advisable'...
But in Python <3.8: you can't. Instead, separate your code into two statements:
name = input("Tell me your name: ")
print("Your name is: " + name)
If you often find yourself wanting to use two lines like this, you could make it into a function:
def input_and_print(question):
s = input("{} ".format(question))
print("You entered: {}".format(s))
input_and_print("What is your name?")
Additionally you could have the function return the input s.
no this is not possible. well except something like
x=input("tell me:");print("blah %s"%(x,));
but thats not really one line ... it just looks like it

replacing text in a file, Python

so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.

How to use "def" with strings

I'm relatively new to programming so I just recently got started with experimenting with "def" in python. This is my code and its keeps on telling me the first name hasn't been defined.
def name(first, last):
first = str(first)
last = str(last)
first = first.upper
last = last,upper
print("HELLO", first, last)
I then run the program and i write a name like
name(bob, robert)
and then it would tell me that "bob" hasn't been defined
You should quote them (using ' or ") if you mean string literals:
name('bob', 'robert')
Beside that, the code need a fix.
def name(first, last):
first = str(first)
last = str(last)
first = first.upper() # Append `()` to call `upper` method.
last = last.upper() # Replaced `,` with `.`.
print("HELLO", first, last)
There's a difference between a variable and a string. A variable is a slot in memory already allocated with a data (string, number, structure...) When you write robert without quotes, Python will search this variable already instancied with this name.
Here it doesn't exists, since you don't write robert = 'something'. If you want to pass a string directly, you just have to write it, surronding by quotes (or triple quotes if it's on multiple lines).
What you want to achieve is calling your name function like this:
def name(first, last):
first = str(first)
last = str(last)
first = first.upper
last = last,upper
print("HELLO %s %s" % (first, last))
name('bob', 'robert') # Will print "HELLO bob robert"
def name(first, last):
first = str(first)
last = str(last)
first = first.upper()
last = last.upper()
print("HELLO", first, last)
name("bob","robert")
1.str-objects has upper-method, but to call it and get result u have to add "()" after the name of method - because you get link to object-method - not to string in upper case...
2.in calling name(bob,robert) - you put the arguments, which are undefined variables..
to do this u have to define these variables before calling, f.g:
bob = "bob"
robert="robert"
name(bob,robert)
You need to put the strings to quotes (either "bob" or 'bob').
So your call would be
name('bob', 'robert')
instead of
name(bob, robert)
.
If you use it without the quotes, python tries to find a variable with a name bob.
Also, you do not need to use the str(first) or str(last) since both are already strings.

Categories