How to use "def" with strings - python

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.

Related

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.

basic strings and variables 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.

Put function outputs to a list in Python [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 8 months ago.
The aim of the following program is to convert words in 4 characters from "This" to "T***", I have done the hard part getting that list and len working.
The problem is the program outputs the answer line by line, I wonder if there is anyway that I can store output back to a list and print it out as a whole sentence?
Thanks.
#Define function to translate imported list information
def translate(i):
if len(i) == 4: #Execute if the length of the text is 4
translate = i[0] + "***" #Return ***
return (translate)
else:
return (i) #Return original value
#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")
#Print lines
for i in orgSent:
print(translate(i))
On py 2.x you can add a , after print:
for i in orgSent:
print translate(i),
If you're on py 3.x, then try:
for i in orgSent:
print(translate(i),end=" ")
default value of end is a newline(\n), that's why each word gets printed on a new line.
Use a list comprehension and the join method:
translated = [translate(i) for i in orgSent]
print(' '.join(translated))
List comprehensions basically store the return values of functions in a list, exactly what you want. You could do something like this, for instance:
print([i**2 for i in range(5)])
# [0, 1, 4, 9, 16]
The map function could also be useful - it 'maps' a function to each element of an iterable. In Python 2, it returns a list. However in Python 3 (which I assume you're using) it returns a map object, which is also an iterable that you can pass into the join function.
translated = map(translate, orgSent)
The join method joins each element of the iterable inside the parentheses with the string before the .. For example:
lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
It's not limited to spaces, you could do something crazy like this:
print('foo'.join(lis))
# HellofooWorld!
sgeorge-mn:tmp sgeorge$ python s
Pleae enter a sentence:"my name is suku john george"
my n*** is s*** j*** george
You just need to print with ,. See last line of below pasted code part.
#Print lines
for i in orgSent:
print (translate(i)),
For your more understanding:
sgeorge-mn:~ sgeorge$ cat tmp.py
import sys
print "print without ending comma"
print "print without ending comma | ",
sys.stdout.write("print using sys.stdout.write ")
sgeorge-mn:~ sgeorge$ python tmp.py
print without ending comma
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$

How can i write this function that mostly prints to a file?

So I posted about another part of this code yesterday but I've run into another problem. I made a character generator for an RPG and im trying to get the program the output of a character sheet function to a .txt file, but i think whats happening is that the function may return a Nonevalue for some of the stats (which is totally normal,) and then i get an error because of that when i try to write to a .txt file. I'm totally stumped, and help would be vastly appreciated!
# Character Sheet Function.
def char_shee():
print "Name:", name
print "Class:", character_class
print "Class Powers:", class_power
print "Alignment:", alignment
print "Power:", pow, pow_mod()
print "Intelligence:", iq, iq_mod()
print "Agility:", agi, agi_mod()
print "Constitution:", con, con_mod()
print "Cynicism:", cyn, cyn_mod()
print "Charisma:", cha, cha_mod()
print "All Characters Start With 3 Hit Dice"
print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)
char_shee()
print "Press enter to continue"
raw_input()
# Export to text file?
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to
name it after something important, or you might lose it.
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file")
if text_file == "y":
filename = raw_input("\nWhat are we calling your file, include .txt")
target = open(filename, 'w')
target.write(char_shee()
target.close
print "\nOk I created your file."
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
EDIT: Here is the output i get:
> Please type 'y' or 'n', if you want a .txt filey
>
> What are we calling your file, include .txt123.txt <function char_shee
> at 0x2ba470> Traceback (most recent call last): File "cncg.py", line
> 595, in <module>
> target.write(pprint(char_shee)) TypeError: must be string or read-only character buffer, not None
Using print writes to sys.stdout, it doesn't return a value.
You you want char_shee to return the character sheet string to write it to a file, you'll need to just build that string instead.
To ease building the string, use a list to collect your strings:
def char_shee():
sheet = []
sheet.append("Name: " + name)
sheet.append("Class: " + character_class)
# ... more appends ...
# Return the string with newlines
return '\n'.join(sheet)
you forgot parenthesis here:
target.write(char_shee())
target.close()
and as #Martijn Pieters pointed out you should return value from char_shee(), instead of printing them.

Categories