首页 > 解决方案 > 如何在带有 if 的辅助函数中使用 isdigit() 方法

问题描述

cani 如何使用 isdigit 方法 像那样if self.month.isdigit():

需要知道我的输入是否是数字

class myclass():
def __init__(self,year,month,day):
    self.mah = ['none','farvardin','ordibehesht','khordad','tir','mordad','shahrivar','mehr','aban','azar','dey','bahman','esfand']
    self.daylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
    self.year = year
    self.month = month
    self.day = day
def myfunc(self):
    if self.month.isdigit(): # problem is (isdigit) not working



p1= input("Please enter date:")
year,month,day = p1.split('-')
p2 = myclass(year,month,day)
p2.myfunc()  

标签: python

解决方案


@Tiago 据我了解,我已经更新了您的代码。当您从标准输入中获取输入时,p1 将只是一个字符串对象,但如果 p1 中没有任何“-”,那么代码将生成解包错误。例如,如果您通过20211114

Please enter date: 
Traceback (most recent call last):
  File "jdoodle.py", line 19, in <module>
    year,month,day = p1.split('-')
ValueError: not enough values to unpack (expected 3, got 1)
  • 我已将您的班级名称从range更改为 CustomRange

  • 加上我使用列表理解的日程表变量。

     class CustomRange():
     def __init__(self,year,month,day):
         self.daylist = [i for i in range(1,32)]
         self.year = year
         self.month = month
         self.day = day
         self.mah = ['none','farvardin','ordibehesht','khordad','tir','mordad','shahrivar','mehr','aban','azar','dey','bahman','esfand']
     def myfunc(self):
         if self.month.isdigit(): # problem is (isdigit) not working
             print(self.month, "is number")
             return True
         else:
             print(self.month, "is not number")
             return False
    
     p1= input("Please enter date: ")
     year,month,day = p1.split('-')
     p2 = CustomRange(year,month,day)
     p2.myfunc()  
    

推荐阅读