我是編程的新手,並試圖通過使用python來介紹類來學習它。如何比較兩個兩位數的整數是一樣的,一次翻轉和一個字符
我的一個任務的要求我們做到以下幾點:
比較用戶生成的兩位數整數隨機生成的兩位數整數。
- 如果兩個隨機的,並且用戶產生的整數匹配打印blah1
- 如果用戶生成的整數具有相同的兩個數字中的反向隨機生成的整數,打印blah2
- 如果用戶生成的整數具有一個數字與隨機生成的整數相同,print blah3。
現在,到目前爲止,我們只學會了基本的東西,(運營商,if
/else
/elif
,while
環,印刷,字符串,整數)
我想出的東西,隨機分配兩位數字,將它們轉換爲字符串,然後將它們連接成兩位數字符串。從這裏,我用elif
語句來匹配每個可能的條件。
不幸的是,這不是必需的。當我進行比較時,我必須使用兩位數的整數。不幸的是,我完全不知道如何比較一個整數的部分,或者將整數與我所教導的整數相反。
現在,我不想找人爲我解決這個問題。我希望得到一些幫助,或者提示或者建議我應該如何用我擁有的基本知識思考這個問題。
任何和所有的幫助,非常感謝。
我已經包含了我編寫的代碼。
# homework 2
# problem 1
#
# lottery guessing program
#
# the program randomly generates a two-digit number, prompts the user to enter a two-digit number,
# and determines whether the user wins according to the following rules:
#
# 1. if both digits match in the right order, you will win $10,000.
# 2. if both digits match, but in the reversed order, you will win $3,000.
# 3. if you match one digit in either place, you will win $1,000
#imports
import random
#rules
print("guess a number. if both digits match in the right order, you will win $10,000."\
"\nif both digits match, but in the reversed order, you will win $3,000." \
"\nif you match one digit in either place, you will win $1,000." \
"\nif you don't match any digits, you do not win anything.")
# random variables
rand_num1 = str(random.randint(1,9))
rand_num2 = str(random.randint(1,9))
#ask user for number
user_num1 = input("what is your first number? ")
user_num2 = input("what is your second number? ")
#for testing purposes, if testing, comment out the previous two lines
#combd_num = (str(rand_num1)) + (str(rand_num2))
#revsd_num = (str(rand_num2)) + (str(rand_num1))
#print(rand_num1)
#print(rand_num2)
#print(combd_num)
#print(revsd_num)
#user_num1 = input("what is your first number? ")
#user_num2 = input("what is your second number? ")
#ucomb_num = (str(user_num1)) + (str(user_num2))
#output the numbers
print("the number is, ", (rand_num1 + rand_num2),"\
\nyour number is, ", (user_num1 + user_num2), sep="")
#elif statement
if (user_num1 + user_num2) == (rand_num1 + rand_num2):
print("you guessed the exact number. you win $10,000!")
elif (user_num2 + user_num1) == (rand_num1 + rand_num2):
print("you guessed both digits but in reverse. you win $3,000!")
elif user_num1 == rand_num1 and user_num2 != rand_num2:
print("you guessed one digit right. you win $1,000!")
elif user_num1 == rand_num2 and user_num2 != rand_num2:
print("you guessed one digit right. you win $1,000!")
elif user_num2 == rand_num1 and user_num1 != rand_num2:
print("you guessed one digit right. you win $1,000!")
elif user_num2 == rand_num2 and user_num1 != rand_num2:
print("you guessed one digit right. you win $1,000!")
else:
print("sorry, you didn't guess the right number.")
薩米爾也可能會發現它有用知道,明顯'[1,2] ==逆轉([2,1])''給FALSE',你必須使用'[1,2] ==列表(反轉([2,1]))'或切片符號來得到一個列表進行比較。順便說一句,我不相信你使用'reversed()'給出的例子。 – Duncan
在Python 3中,正確的是一個迭代器,我仍然經常使用Python 2。我會糾正的。 –
不是'revers'在Python 2中返回一個'listreverseiterator object'? – DSM