【发布时间】:2012-09-18 22:13:05
【问题描述】:
我是编程新手,正在尝试通过使用 python 参加介绍课程来学习它。
我的一项任务要求我们执行以下操作:
-
将随机生成的两位整数与用户生成的两位整数进行比较。
- 如果随机整数和用户生成的整数都匹配 print blah1
- 如果用户生成的整数与随机生成的整数的两位数相同,则打印 blah2
- 如果用户生成的整数有一位与随机生成的整数相同,则打印 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.")
【问题讨论】:
标签: python string python-3.x integer logic