簡體   English   中英

Python時間問候程序

[英]Python time greeting program

我正在嘗試創建一個基於一天中的時間來吸引用戶的程序,但是當我運行我的代碼時,我收到此錯誤:無法排序的類型:str() < int()

我不認為我以正確的方式做這件事,我想不出更好的方法來做這件事,那么編寫這個程序的更好方法是什么???

這是我的代碼:

import time
currentTime = time.strftime('%H:%M')   

if currentTime.hour < 12 :
     print('Good morning')
if currentTime.hour > 12 :
     print('Good afternoon')
if currentTime.hour > 6 :
     print('Good evening')

看起來您想使用代表時間的對象。 我推薦datetime模塊。

此外,您的代碼假定計算機會猜測您輸入的小時是上午還是下午。 您必須使用18小時來表示下午 6:00。

>>> import datetime
>>> currentTime = datetime.datetime.now()
>>> currentTime.hour
0
>>> if currentTime.hour < 12:
...     print('Good morning.')
... elif 12 <= currentTime.hour < 18:
...     print('Good afternoon.')
... else:
...     print('Good evening.')
...
Good morning.

字符串變量中沒有名為hour的屬性。

import time
currentTime = int(time.strftime('%H'))   

if currentTime < 12 :
     print('Good morning')
if currentTime > 12 :
     print('Good afternoon')
if currentTime > 6 :
     print('Good evening')

我看到這里列出的答案很長,所以為那些需要它的人創建了一個更簡潔的版本(即使這篇文章已經超過 2 年了)。 然而,這個頂級版本可能會破壞PEP-8 中概述的格式,因為第三行超過 80 個字符 (92),所以請隨意使用更長的版本。

import datetime
hour = datetime.datetime.now().hour
greeting = "Good morning" if 5<=hour<12 else "Good afternoon" if hour<18 else "Good evening"

然后在任何需要的地方使用它......

print("{}!".format(greeting))

...或分解為可讀性...

import datetime
now = datetime.datetime.now()
hour = now.hour

if hour < 12:
    greeting = "Good morning"
elif hour < 18:
    greeting = "Good afternoon"
else:
    greeting = "Good night"

print("{}!".format(greeting))

一個示例用例是說一個隨機的“再見”,使程序看起來更逼真。 這會做這樣的事情......

import random, datetime
hour = datetime.datetime.now().hour
greeting = "Have a nice day" if hour<20 else "Good night"
print(random.choice(["I look forward to our next meeting!",greeting+"!"]))
a=input("Enter your name:")

import datetime
currentTime = datetime.datetime.now()
currentTime.hour

if currentTime.hour < 12:
    print('Good morning',a)
elif 12 <= currentTime.hour < 18:
    print('Good afternoon',a)
else:
    print('Good evening',a)

[write this without using python,click this link provided below to write]

https://colab.research.google.com/

希望現在對這個問題做出貢獻還為時不晚:

from datetime import datetime

current_hour = int(datetime.now().strftime('%H'))
if current_hour<12:
    print('Good morning')
elif 12<=current_hour<18:
    print('Good afternoon')
else:
    print('Good Evening')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM