2016-12-03 56 views
0

我正在編寫基於巧克力數學遊戲的代碼(http://www.joe-ks.com/Chocolate_Math.htm)。我可以讓代碼運行良好,除了最後一部分。Python將3位數字分成兩部分

我希望輸出結果是可讀的,例如,「您的最終數字是533.這意味着您的原始數字是5,您的年齡是33歲。」

我無法弄清楚的是如何只打印三位數字的最後兩位數字。

orig_num = int(input("Okay, tell me how many times a week you want chocolate. It should be more than one, but less than 10: ")) 

    guess = ((orig_num * 2) + 5) * 50 

    birthday = input("Have you had your birthday this year? Y/N: ") 
    if birthday == 'Y': 
     guessb = guess + current_year - 250 
    elif birthday == 'N': 
     guessb = guess + current_year - 251 

    year = int(input("What year were you born? (Don't worry, I won't look): ")) 
    less_year = guessb - year 

    print("Well! Your number is {}. That means your original number was {}, and you are {} years old".format(less_year, orig_num, less_year)) 

我感覺好像我應該在這裏某個地方有一個功能,但我太綠了,不知道在哪裏。

回答

0

你有多種方式來解決這個問題 - 一個是使用模數,即533%100=33或者你可以把它作爲一個字符串的選擇最後2位數字str(533)[-2:]

+0

模量工作!非常感謝你。 – mimc83

0

這是你想要實現的嗎?不知道我真的明白你在這裏想要完成什麼,但是我用這種方法實現的輸出似乎與你所描述的一致。

雖然,應該注意的是,由於您沒有考慮月/偏移量,所以您的年齡(以年爲單位)有可能會關閉。

例如對於輸入:我要巧克力每週3天,我還沒有過一次生日,今年誕生96年,輸出是:

Okay, tell me how many times a week you want chocolate. 
It should be more than one, but less than 10: 3 

Have you had your birthday this year? Y/N: N 
What year were you born? (Don't worry, I won't look): 1996 
Well! Your number is 319. That means your original number was 3, and you are 19 years old 

這應該是20;)

我假設這是250251是爲什麼,在這種情況下,他們應該切換?再次,不知道從現在開始他們是神奇的數字。

orig_num = int(input("Okay, tell me how many times a week you want chocolate. It should be more than one, but less than 10: ")) 

guess = ((orig_num * 2) + 5) * 50 
current_year = 2016 
birthday = input("Have you had your birthday this year? Y/N: ") 
if birthday == 'Y': 
    guessb = guess + current_year - 250 
elif birthday == 'N': 
    guessb = guess + current_year - 251 

year = int(input("What year were you born? (Don't worry, I won't look): ")) 
less_year = guessb - year 
orig_num = (less_year - orig_num) // 100 
age = less_year % 100 

print("Well! Your number is {}. That means your original number was {}, and you are {} years old".format(less_year, orig_num, age))