#app.route("/<name>")
def office(name):
return F"Hello {name}! "
What is the F doing before "Hello {name}! "?
These are called "f-strings" and are not limited to Flask. It's basically a string formatting mechanism used in Python.
Suppose you have a variable name = "XYZ". Using
print ('Hello {name}')
will print "Hello {name}", which is not what you want. Instead, you use an f-string so you can have the value {name} be the same as your variable.
print (f'Hello {name}')
The above would print "Hello XYZ". Alternatively, you could also use the following:
print ('Hello {}'.format(name))
You can read about them in more detail here: https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/
Related
#BOT.message_handler(commands=['drink'])
def drink(message):
try:
BOT.send_message(message.chat.id, f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')
except IndexError:
BOT.send_message(message.chat.id, 'IndexError')
I basically want to create a function to shorten the "BOT.send_message(message.chat.id," part, since it will always be the same (at least for this project)
I tried creating this function inside the (handler? method? the # thingy):
def send(message): BOT.send_message(message.chat.id, message)
And then in the drink() function, change it to:
#BOT.message_handler(commands=['drink'])
def drink(message):
try:
send(f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')
except IndexError:
send('IndexError')
That doesn't work because it doesn't need a string but a "chat" object (if I understood correctly the error message), but is there any way to make it work?
This project should be fairly simple and short, so I won't lose too much time typing "BOT.send_message(message.chat.id,", but in the future it might save me some time :)
You can't avoid using message or message.chat.id completely. The best (shortest) you can do is:
def respond(message, text):
BOT.send_message(message.chat.id, text)
#BOT.message_handler(commands=['drink'])
def drink(message):
try:
respond(message, f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')
except IndexError:
respond(message, 'IndexError')
Although, doesn't Message have .reply_text(text)?
You can modify the helper function to take two arguments, chat_id and text :
def send(chat_id, text):
BOT.send_message(chat_id, text)
Then in the drink function, change it to:
#BOT.message_handler(commands=['drink'])
def drink(message):
try:
send(message.chat.id, f'I added {message.text.split(" ", 2)[1]} to your daily intake for today, {fecha_excel}!')
except IndexError:
send(message.chat.id, 'IndexError')
Now use the helper function send to send messages to the chat with a given chat id and text.
Write a Python program that takes the user's name as input and displays and welcomes them.
Expected behavior:
Enter your name: John
Welcome John
The Python code for taking the input and displaying the output is already provided
#take the user's name as input
name = input("Enter your name: ")
print(name)
#the vaiable that includes the welcome message is alredy provided.
#Please complete this part using the knowledge obtained in this lesson.
greeting = ("Welcome John")
#print the welcome message
print(greeting)
Out put I got with one error
greeting = (f' Welcome {name}')
Or
greeting = ('Welcome ' + name )
The problem I see is an error in your code where you have hard coded the name "John" with the output. What you ought to do instead, is to output the Variable alongside the greeting message.
greeting = (f"Welcome {name}")
Using this will output the welcome message alongwith the name that's entered. What I have done is used an F-string however there's other ways to do it as well. Hope that answer's your question.
You have hard coded the greeting
greeting = ("Welcome John")
Given you have a name the user has provided, you can use string formatting to interpolate that name into your greeting like this:
greeting = (f"Welcome {name}")
(Notice, you put the variable in curly braces)
# take the user's name as input
name = input("Enter your name: ")
print(name)
# Please complete this part using the knowledge obtained in this lesson.
greeting = ("Welcome" +" "+ name)
# print the welcome message
print(greeting)
I need to print the following of code :
print('hello "my friend '{}' "'.format(name))
such that the output is:
'hello "my friend 'ABCD' " '
But I get the error: End of Statement expected
What is the correct syntax?
You need to escape quotes if you want to use them in a string:
print('hello "my friend \'{}\'"'.format(name))
Try this,
print("""hello "my friend '{}' " """.format(name))
I'm trying to import a function from another class on another file.
When I print it out I get the memory location of the file(I think)
Here is my code:
first_app.py
class Welcome:
def greeting(self):
return 'Hello There'
second_app.py
from first_app import Welcome #imports the class
def answer():
reply = Welcome.greeting #access greeting function
print('Meeting')
print(reply) #prints <function Welcome.greeting at 0x000001EDCC8130D8>
print('Thank you')
answer()
then when I run second_app.py, this is output
Meeting
<function Welcome.greeting at 0x000001EDCC8130D8>
Thank you
Where as it it was the string it would be
Meeting
Hello There
Thank you
Thanks for any help
You need to call the function/method, like this:
reply = Welcome().greeting()
Now reply will contain the string that you expect.
The parentheses following Welcome() tell Python to create an instance of class Welcome.
The second set of parentheses tell Python to call the function greeting(), i.e. to execute it. Without these you are simply referencing the function and the default output of print() is the function name and it's memory location.
I am working on a small project and I am not sure if the error I am getting is due to the IDLE I am using or something I am doing wrong.
I am using OOP in python running on the Wing IDLE. I have the latest version of the python shell running on a Windows 8 PC.
In my program I have a method that takes user input and using that input it creates the parameters required to create a shelf.
'def subject_creator(self):
subject_name = input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name'
Ideally the program would then use the three returned statements namely subject_name, subject_file, and name in opening the new shelf.
'def __init__(self, subject_name, subject_file, name ):
subject_name = shelve.open ("subject_file", "c")
self.name = name
print("The", self.name ,"note has been created")'
while True:
print ("""
1.Create new note
2.Add new term
3.Look up term
4.Exit/Quit
""")
ans= input("What would you like to do?: ")
if ans=="1":
subject_creator()
note = Notebook(subject_name, subject_file, name)
subject_name.sync()
However when I run the program and in my main menu I select choice 1 which runs the code above, I receive and error that states.
<module>
builtins.TypeError: subject_creator() missing 1 required positional argument: 'self'
This is somewhat puzzling as I include the self parameter when I wrote the code for subject creator as shown above. Other than this I have no other errors.
Any feedback would be greatly appreciated.
You are confusing "function" and "method".
In Python, a method is a function defined inside a class scope, and it will receive the object as its implicit first argument:
class Example:
def try_me(self):
print "hello."
You would use it like this:
x = Example()
x.try_me()
and try_me() will receive x as its first (here, ignored) argument. This is useful so that the method can access the object instance's attributes etc.
Contrast this with a regular function, i.e. one defined outside of a class:
def try_me_too():
print "hello."
which is simply invoked like
try_me_too()
Tangentially, your example code does not pick up the values returned by your subject_creator function:
> if ans=="1":
> subject_creator()
> note = Notebook(subject_name, subject_file, name)
The scope where this happens doesn't have variables named subject_name etc. You need to create them somehow.
if ans=="1":
ick, bar, poo = subject_creator()
note = Notebook(ick, bar, poo)
(I chose nonsense variable names mainly to emphasize that these are different from the variables defined, and only available, inside subject_creator.)
Just to complete this, here is a demonstration of how self is useful.
class Otherexample:
def __init__(self, greeting):
self.greeting = greeting
def try_me_also(self):
print self.greeting
use like this:
y = Otherexample("hello.")
y.try_me_also()
Here, the greeting is a property of the object we created; the __init__ method receives it as its argument, and stores it as an attribute of the instance. The try_me_also method uses self to fetch this attribute, and print it.
This line causes your error
subject_creator()
You should change
def subject_creator(self):
subject_name = input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name
to
def subject_creator():
subject_name = raw_input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name
You don't need a parameter in your function if you won't use it.
Also,if you are using python 2.x, consider using raw_input() and not input(). For more info, please read differences between input() and raw_input().