如何根据最终值和倒数第二个值为整数变量编写“ if / unless”语句?

时间:2019-04-08 17:24:37

标签: python if-statement

我正在尝试写一个条件,如果a以1结尾,那么它将以“ st root”回答,除非以11结尾,所以它将像1st root或11th root (然后对于2/12和3/13也以类似的方式工作)

这是我尝试过的代码

    def n():
      print("Only enter whole numbers\n ")
      base = float(input("Enter number to take the root of, then hit enter:\n "))
      input_string = input("Enter degree of roots (if more than one, separate by space) then hit enter:\n ")
      list  = input_string.split()
      a = 1
      for num in list:
          base **= (1/float(num))
      for num in list:
          a *= int(num)
      if str(a)[-1] == '1':
        if str(a)[-1] != '11':
          print(a,"st root",base) 
      elif str(a)[-1] == '2':
        if str(a)[-1] != '12':
          print(a,"nd root",base)
      elif str(a)[-1] == '3':
        if str(a)[-1] != '13':
          print(a,"rd root",base)
      else: 
        print(a,"th root",base)
    n()

3 个答案:

答案 0 :(得分:2)

您几乎可以将句子直接翻译成代码:

  

如果lastCharacter为1而不是penUltimateCharacter为1

如此:

if (str(a)[-1] == '1' and str(a)[-2] != '1'):
   print(a,"st root",base) 

答案 1 :(得分:1)

我找到了将整数转换为序数的答案。

https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers

这是最后的代码段

# much code can be improved by using a datastructe.
SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
def ordinal(num):
    # I'm checking for 10-20 because those are the digits that
    # don't follow the normal counting scheme. 
    if 10 <= num % 100 <= 20:
        suffix = 'th'
    else:
        # the second parameter is a default.
        suffix = SUFFIXES.get(num % 10, 'th')
    return str(num) + suffix

答案 2 :(得分:0)

您基本上需要的是数字的最后一位和最后两位:

a = 1234 #My number to check
last_digit = a - int(a/10)*10
two_two_last_digits = a - int(a/100)*100

现在,这两个数字具有很好的关系,只要满足您的连接,它们的差就是10,所以您有:

if (two_last_digits - last_digit) != 10:
    ...

因此,除非涵盖了“除非”部分,否则可以使用dict来表达if部分:

cases = {1: "st root ", 2:"nd root", 3:"rd root"}

总而言之,我们得到:

if (two_last_digits - last_digit) != 10:
    print(a, "th root", base)
else:
    try:
        print(a, cases[last_digit], base)
    except KeyError:
        print(a, "th root", base)