Print date and time in response to the user

2

I have the date and time format inside the Script, but I see myself in the problem of not being able to include it. As I would in another situation, entering a value within the impression of the message. I have the code in two ways:

Form 1 :

import datetime

dt = datetime.datetime.now()

def tiempo():

    if dt.time() < datetime.time(12):
        print("dias")'
    elif dt.time() > datetime.time(12):
        print("tardes")

nombre = input("Por favor ingrese su nombre: ")

print("Buenas",tiempo(),nombre, "que duda tiene?: ")

In this first form it looks like this:

  

Please enter your name: Test Name
afternoons
  Good None Test Name you have doubts ?:

Form 2 :

import datetime


dt = datetime.datetime.now()

tiempo = dt.time() < datetime.time(12), dt.time() > datetime.time(12)

if tiempo == True: print("dias")

elif tiempo == True: print("tardes")


nombre = input("Por favor ingrese su nombre: ")

print("Buenas", tiempo, nombre, "que duda tiene?: ")

In this second it looks like this:

  

Please enter your name: Test Name
  Good (False, True) Test Name you have doubts ?:

    
asked by Franco M 02.09.2017 в 02:39
source

1 answer

0

The problem with your function is that when it is called it prints the corresponding string but returns None (default return of all methods in Python) and it is this None that prints your print .

Your function should return the appropriate string (using return ) and not print it. By returning the string if you can call it directly from your print and use your return to print, concatenated as you do or using str.format :

import datetime

def tiempo():
    dt = datetime.datetime.now()
    if dt.time() < datetime.time(12):
        return "dias"
    else:
        return "tardes"

nombre = input("Por favor ingrese su nombre: ")
print("Buenas {} {}, ¿qué duda tiene?: ".format(tiempo(), nombre))

Your second form has a similar problem, the variable tiempo should store the string or use the conditional in print . Using the ternary operator could look like this:

import datetime

tiempo = "dias" if datetime.datetime.now().hour < 12 else "tardes"
nombre = input("Por favor ingrese su nombre: ")

print("Buenas", tiempo, nombre, "que duda tiene?: ")

A more compact but less readable option is:

from datetime import datetime

print("Buenas {} {}, ¿qué duda tiene?: ".format("dias" if datetime.now().hour < 12 else "tardes", 
                                                input("Por favor ingrese su nombre: ")))
    
answered by 02.09.2017 / 03:14
source