gpt4 book ai didi

python - 如何获得正确的变量引用

转载 作者:行者123 更新时间:2023-12-01 06:12:09 24 4
gpt4 key购买 nike

在下面的代码中,我试图获取第二个“while”语句(while digital_check)以从之前的 while_count 语句接收新日期。但它似乎从第一个赋值行中获取了 user_date 变量的原始赋值。

如何将新的变量赋值传递给第二个 while 语句?

非常感谢

def main():

user_date = raw_input("Enter a date in the format mm/dd/yyyy and press 'Enter' ")
count = len(user_date)
digit = ''
digit_check = ''

while count != 10:
user_date = raw_input('try again ')
count = len(user_date)

if user_date[0].isdigit() and user_date[1].isdigit() and user_date[3].isdigit() \
and user_date[4].isdigit() and user_date[6].isdigit() and user_date[7].isdigit() \
and user_date[8].isdigit() and user_date[9].isdigit() and user_date[2] == '/' \
and user_date[5] == '/':
digit_check = True

while digit_check != True :
user_date = raw_input('Not right - try again')

convert_date(user_date)

print 'That date is ',convert_date(user_date) + ' ' + user_date[3] + user_date[4] + ',' + user_date[6:]

def convert_date(user_date):

# Convert date to different format
month = ''

if user_date[0] == '0' and user_date[1] == '1':
month = 'January'
elif user_date[0] == '0' and user_date[1] == '2':
month = 'February'
elif user_date[0] == '0' and user_date[1] == '3':
month = 'March'
elif user_date[0] == '0' and user_date[1] == '4':
month = 'April'
elif user_date[0] == '0' and user_date[1] == '5':
month = 'May'
elif user_date[0] == '0' and user_date[1] == '6':
month = 'June'
elif user_date[0] == '0' and user_date[1] == '7':
month = 'July'
elif user_date[0] == '0' and user_date[1] == '8':
month = 'August'
elif user_date[0] == '0' and user_date[1] == '9':
month = 'September'
elif user_date[0] == '1' and user_date[1] == '0':
month = 'October'
elif user_date[0] == '1' and user_date[1] == '1':
month = 'November'
elif user_date[0] == '1' and user_date[1] == '2':
month = 'December'

return month


main()

最佳答案

一个问题是您没有在此处重新计算 digital_check:

while digit_check != True :
user_date = raw_input('Not right - try again')

这将进入无限循环。

我建议不要编写一个包含许多循环和大量赋值的巨大函数,而是将代码重构为更小的函数并使用更简单的逻辑。例如:

def getDate():
while True:
user_date = raw_input('Enter a date')
if validate(user_date):
return user_date
else:
print 'Error, try again.'

def validate(user_date):
# etc...

关于python - 如何获得正确的变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5214103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com