Python循环直到满足条件

时间:2017-11-30 19:16:48

标签: python-3.x

我正在尝试为作业编写一个程序,而我需要创建一个除法问题。我需要它,以便当选择随机数时,第一个数字将始终大于第二个数字。我创建的函数完成了大部分工作,但我似乎无法弄清楚如何让它循环直到满足条件。在代码中,我尝试使用while循环但是当我运行它时,我仍然得到第一个数字作为较低的数字。

有没有人对我如何做到这一点有任何建议?

import random
import time

score = 0
Addition = range(1, 20)
Multiplication = ['1', '2', '3', '4', '5']
Division = ['1', '2', '4', '6', '8', '10']

def additionfunc():
 for x in range (0, 4):
  a = random.choice(Addition)
  b = random.choice(Addition)

  c = float(a) + float(b)
  print("What is", a," plus", b)
  answer = int(input("Please enter your answer: "))

  if answer == c:
     print("Correct")
     print("Plus 10 points")
     global score
     score = score + 10
     print()
     time.sleep(1)
  else:
     print("Incorrect")
     print("No points added")
     print()
     time.sleep(1)
     print("Well done, your score was", score)
     print()
mainmenu()

def multiplicationfunc():
 for x in range (0, 4):
  a = random.choice(Multiplication)
  b = random.choice(Multiplication)
  c = float(a) * float(b)

  print("What is", a," multiplied by", b)
  answer = int(input("Please enter your answer: "))

 if answer == c:
  print("Correct")
  print("Plus 10 points")
  global score
  score = score + 10
  print()
  time.sleep(1)
 else:
  print("Incorrect")
  print("No points added")
  print()
  time.sleep(1)
  print("Well done, your score was", score)
  print()
mainmenu()

def divisionfunc():
 for x in range (0,4):
  a = random.choice(Division)
  b = random.choice(Division)
  c = float(a) / float(b)

  print("What is", a, "divided by", b)
  answer = float(input("Please enter your answer: "))

  if answer == c:
   print("Correct")
   print("Plus 10 points")
   global score
   score = score +10
   print()
   time.sleep(1)
 else:
   print("Incorrect")
   print("No points added")
   print()
   time.sleep(1)
   print("Well done, your score was", score)
   print()
mainmenu()

def mainmenu():
 print("Welcome to the Numeracy Game")
 print("1. Addition")
 print("2. Multiplication")
 print("3. Division")
 print("Score =", score)
 time.sleep(2)

 Genre = int(input("Enter the value for the mode:"))
 print()

if Genre == 1:
 additionfunc()
elif Genre == 2:
 multiplicationfunc()
elif Genre == 3:
 divisionfunc()

mainmenu();

1 个答案:

答案 0 :(得分:0)

我希望这就是你所需要的:

division= ['1', '2', '4', '6', '8', '10'] #[1,2,4,6,8,10]
# you could also use random.randint(start, stop)
#if you only want even ints you can use random.randint(0,10,2)
a = random.choice(division) # random.ranint(0,10)
b = random.choice(division) # random.randint(0,10)
if b == 10:
    #prevents b from being the biggest number which would result in an endless loop
    b = random.choice(division)
while a < b or a==b: # if a is smaller or same as b change a
    a = random.choice(division)
else:
    # it would be easier to use ints instead string and only convert
    # them to string in your print statemnt
    c = float(a)/float(b)