2016-12-26 63 views
0

我目前正在构建一个简单的程序,根据分配的月份和日期确定一个人的星座符号。Python如何将列表中的第二个值转换为int

我遇到检查列表中的第二个值的问题,我只能将第二个值转换为int。

这是我到目前为止有:

user_day_month = input("Enter your birth month and day").lower().split(' ') 
print(user_day_month) 
user_sign = "" 

if (user_day_month[0]=="january" and user_day_month[1]>=20) or (user_day_month[0]=="february" and user_day_month[1]<=18): 
    user_sign = "Aquarius" 
    print(user_sign) 

elif (user_day_month[0]=="february" and user_day_month[1]>=19) or (user_day_month[0]=="march" and user_day_month[1]<=20): 
    user_sign = "Pisces" 

回答

0

拆开用户的输入为两个独立的命名变量,然后将它们转换的一个整数:

month, day = input("Enter your birth month and day").lower().split(' ') 
day = int(day) 

然后,您可以参考直接对这些变量中的每一个:

if (month=='january' and day>=20) or... 

更复杂,更重复的替代方法是当日转换为整数的if语句中:

if (user_day_month[0]=='january' and int(user_day_month[1]>=20)) or... 

,当你结束了int多次铸造是不是最好的选择。第一个选项更清洁。

作为一个中间的可能性,你可以访问用户输入的列表,并转换该值:

user_day_month = input("Enter your birth month and day").lower().split(' ') 
user_day_month[1] = int(user_day_month[1]) 

然后使用你原来的if声明:

if (user_day_month[0]=="january" and user_day_month[1]>=20) or... 

但第一个选项是最好的。

0

我试着使用上面的解决方案,但该行

month, day = input("Enter your birth month and day").lower().split(' ') 

真的搞糊涂了。我不知道什么类型的输入控制台期望从我。我尝试了不同的策略,比如在空间之间放置空格或放置逗号......对我来说不适合。

我推荐什么是独立的输入转换成两个不同的变量行:

day = int(input("Input the day when you were born: ")) # this will be an integer 
mon = input("Input the month when you were born: ").lower() # this will be a string 

如果有必要让你有那些在一个数组,你可以这样做:

dateofbirth = [ int(input("Input the day when you were born: ")), input("Input the month when you were born: ").lower() ] 

现在,您可以轻松访问使用[]的人。

>>> Input the day when you were born: 23 
>>> Input the month when you were born: December 
>>> dateofbirth[0] 
23 
>>> dateofbirth[1] 
'december' 

关于个月以下

我们共有的12个标志和你if语句由出生日期和月份一些关键值进行比较,以确定标志的几点建议在if else报表中,您必须输入约22个不同的月份。

这就是我的意思是:

if (user_day_month[0]=="january" and user_day_month[1]>=20) or (user_day_month[0]=="february" and user_day_month[1]<=18): 
    user_sign = "Aquarius" 
    print(user_sign) 

elif (user_day_month[0]=="february" and user_day_month[1]>=19) or (user_day_month[0]=="march" and user_day_month[1]<=20): 
    user_sign = "Pisces" 

,从你的例子是,在这里你都已经在“一月”,“二月”和“二月”再次键入某个点。我可以预测,你会继续这样做,这是漫长的,无聊的和低效的。

更好地创造月的数组这样的:

months = [ None, "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" ] 

添加None作为第一个项目将允许你正常调用个月,根据他们的日历中的数字。一月,例如将一如既往地months[1]

使用此构造将允许您缩短条件语句并照亮拼写错误。

if (month == months[1] and day >= 19) or (month == months[2] and day <= 20): 
    sign = "Pisces" 
    print(sign) 
相关问题