簡體   English   中英

寫一個 function 給定日期編號,並返回日期名稱(字符串)

[英]Write a function which is given the day number, and it returns the day name (a string)

假設從星期日到星期六,一周中的日子編號為 0、1、2、3、4、5、6。 寫一個 function 給定日期編號,並返回日期名稱(字符串)。 請幫我解決這個象牙。 請解釋一下為什么我的代碼返回錯誤:ValueError: invalid literal for int() with base 10: ''

d1 = "Понедельник"
d2 = "Вторник"
d3 = "Среда"
d4 = "Четверг"
d5 = "Пятница"
d6 = "Суббота"
d7 = "Воскресенье"

print (input ("Chose day of number: "))
x = int(input())

if x == 1:

       print (d1)

print("Program ended")

您以錯誤的方式使用了input function,請嘗試以下操作:

d1 = "Понедельник"
d2 = "Вторник"
d3 = "Среда"
d4 = "Четверг"
d5 = "Пятница"
d6 = "Суббота"
d7 = "Воскресенье"

x = int(input("Chose day of number: "))

if x == 1:
    print(d1)

print("Program ended")

我認為你是一個初學者。 您可以使用dictlist等來使您的程序更簡單。

可以使用字典輕松解決此要求。

這是使用 Python 字典的工作解決方案:

# File name: Weekdays.py

weekDays = {
    1: "Понедельник",
    2: "Вторник",
    3: "Среда",
    4: "Четверг",
    5: "Пятница",
    6: "Суббота",
    7: "Воскресенье"
}


userInput = input("Choose a number for day (1 to 7): ")
if(userInput.isdigit() and (int(userInput) > 0) and (int(userInput) < 8)):
    n = int(userInput)
    print(weekDays[n])
else:
    print("Input must be a number between 1 and 7 only")

Output:

> python Weekdays.py
Choose a number for day (1 to 7): 6
Суббота

> python Weekdays.py
Choose a number for day (1 to 7): 1
Понедельник

> python Weekdays.py
Choose a number for day (1 to 7): 99
Input must be a number between 1 and 7 only

> python Weekdays.py
Choose a number for day (1 to 7): 0
Input must be a number between 1 and 7 only

> python Weekdays.py
Choose a number for day (1 to 7): 7
Воскресенье

試試這個:

def days_func(day_index):
    days = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}

    if day_index in range(0, 6):
        return days[day_index]
    else:
        message = 'Invalid Number, try again!'
        return message


try:
    day = int(input('Enter the number of a day : '))
    print(days_func(day))
except ValueError:
    print('Index must be Integer!')

錯誤,因為輸入的字符不是數字。嘗試使用字典來存儲數據並根據需要獲取它。 https://www.programiz.com/python-programming/dictionary

暫無
暫無

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

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