簡體   English   中英

編寫一個 python 程序,通過循環查找數字的第一位和最后一位的總和

[英]Write a python program to find sum of first and last digit of a number by using loop

您好,我是編碼新手,只是學習編碼的一些基礎知識,任何人都可以幫助我解決這個問題:-我編寫了一個代碼來使用循環查找第一個和最后一個術語,但無法添加它們,代碼如下所示

n = input("enter your number:-")

#By loop 

if (n.isnumeric):
    for i in range(len(n)):
        if i == 0:
            print(f" your first digit of the number is {n[0]}")
        elif i== len(n)-1:
            print(f" your last digit of the number is {n[-1]}")
else:
    print("Please enter a number and try again!")

請有人可以修改此代碼以找到第一個數字和最后一個數字的總和嗎? 謝謝你:)

實際上,您非常接近您正在尋找的答案,只有一些錯誤需要更正。 查看修改后的版本,並檢查?

注意- 這是為了遵循 OP 的想法,並進行最小的更改。
當然,有許多替代方法可以實現它(以及更多的無效輸入錯誤檢查,但那是另一個故事/練習)。


n = input("enter your number:-")    # ex. 123 

#By loop 

if (n.isnumeric()):                # calling the method:  isnumeric()
    for i in range(len(n)):
        if i == 0:
            first = n[0]          # assign it to first digit
            print(f" your first digit of the number is {n[0]}")
        elif i == len(n)-1:
            last = n[len(n) -1]   # assign it to last digit
            print(f" your last digit of the number is {n[-1]}") # convert to integer

print(f' the sum of first and last digits: {int(first)+int(last)} ')
# 4      <- given input 123

您已經知道如何獲取序列中的最后一項 - 即 n[-1]

因此,使用循環是無關緊要的。

但是,您需要做的是檢查兩件事。

  1. 輸入的長度是否至少為 2 個字符?
  2. 輸入是否完全由十進制字符組成

這使:

inval = input('Enter a number with at least 2 digits: ')

if len(inval) > 1 and inval.isdecimal():
    first = inval[0]
    last = inval[-1]
    print(f'Sum of first and last digits is {int(first)+int(last)}')
else:
    print('Input either too short or non-numeric')

另一種有趣的方法是使用map()和一些解包來處理輸入:

inval = input('Enter a number with at least 2 digits: ')

if len(inval) > 1 and inval.isdecimal():
    first, *_, last = map(int, inval)
    print(f'Sum of first and last digits is {first+last}')
else:
    print('Input either too short or non-numeric')

暫無
暫無

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

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