该代码创建一个随机加法问题,如果正确,则吐出“祝贺”,如果输入的值不正确,则吐出“对不起...”。 while循环重复此过程,直到用户在问题“继续(Y / N)”中插入“ N”为止;同时,它跟踪已回答的问题数和正确的问题。代码可以正常工作,我的问题是它具有重复的代码。我想知道是否有办法缩小它。
**我感谢每个人的帮助和建议。我是只在学习python **的菜鸟
import datetime as dt
tz_info = dateutil.tz.gettz(zone_name)
pend_time = pendulum.datetime(...)
dt_time = dt.datetime(
pend_time.year,
pend_time.month,
pend_time.day,
pend_time.hour,
pend_time.minute,
pend_time.second,
pend_time.microsecond,
).astimezone(tz_info)
答案 0 :(得分:0)
通过将变量c初始化为“ Y”,可以满足条件并可以执行循环:
import random
correct=0
count=1
c = "Y"
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
c = c.upper()
else:
print('Your final score is',correct,'/',count)
我还在Y / N输入中添加了方法upper()
,以便用户也可以使用小写字母输入
答案 1 :(得分:0)
尝试将尽可能多的处理移入循环。您代码的第一个“段落”基本上是主循环的副本。通过创建连续变量c
使其直接进入循环,可以删除大部分第一块。
import random
correct=0
count=0
c = 'Y'
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congratulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
两个公式打印语句也可以简化为一个:
print(format(num1,'4d'))
print('+',num2)
可能是
print( format(num1,'4d') + '+', num2 )
可以删除变量sum
,但这确实使代码可以自我记录,这是一件好事。
答案 2 :(得分:0)
第一个开始是通过将count变量(跟踪圈数)初始化为零,并允许while循环运行第一圈,从而消除while
之前的代码,需要有一个want_to_play
之类的变量,默认情况下为True
,所以我们是第一次玩,在游戏结束时如果我不输入Y
或y
假设我不想再玩了,并将变量设置为false,这样我就可以在while循环中进行所有的回合。
,您将得到类似的内容:
from random import sample
correct = 0
count = 0 # STartint in turn zero
want_to_play = True # Control Variable
while want_to_play:
count += 1
# First turn this is zero, and adds one.
[num1, num2] = sample(range(0, 101), 2)
# Just another way of getting two random numbers from 1 up to (including) 100.
# Printing could be done in one line.
print(format(num1, '5d') + '\n+' + format(num2, '4d'))
answer = int(input('= '))
# The comparison really doesn't really hurt if you do it this way.
if answer == num1 + num2:
print('Congraulations!')
correct += 1
else:
print('Sorry the correct answer is', sum)
# HERE you ask if you want to play again or not, using a one line if
# you decide.
want_to_play = (True if 'y' == input('Continue (Y/N).lower():')
else False)
else:
print('Your final score is',correct,'/',count)