Python3 For/While循环

2024-06-28 19:53:19 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,我对Python还很陌生。但是,我需要创建一个程序来计算一个人在一段时间内的收入,如果他或她的奴隶第一天是一便士,第二天是两便士,并且每天都会翻倍。我知道我应该使用for&while循环,但我不完全确定如何执行它。你知道吗

到目前为止,我有:

day = int(input('How many days did you work?: '))
start = 1
end = day
amount_start = 0.01

print()
print('Day     Amount ($)')
print('---     ----------')

for day in range(start, end + 1):
    amount_end = amount_start * 2
    for amount_start in (amount_start, amount_end):
        print(day, amount_end, sep='         ')

当我运行它时,我看到第1天的起始数字是0.02,并且每行重复两次。如果您能给我一些建议,以便我能理解,我将不胜感激。 谢谢。你知道吗


Tags: in程序forinputamountstartintend
2条回答

首先,我将解释你的代码做什么,然后,什么代码会做你想要的。你知道吗

day = int(input('How many days did you work?: '))
start = 1
end = day
amount = 0.01 # Start and End shouldn't be a thing
total = 0 # I think this is what you wanted... the amount will double every time and the total will be increased by the amount every time

print()
print('Day     Amount ($)')
print(' -          ')

在那里初始化,没什么问题。现在,让我们看看这两个for循环。你知道吗

for day in range(start, end + 1):
    amount_end = amount_start * 2
    for amount_start in (amount_start, amount_end):
        print(day, amount_end, sep='         ')

首先,我建议不要考虑变量的名称。变量day已经在前面定义过了,但是由于它不再用于最初的用途,所以在这里没有太大关系。你知道吗

外部循环将循环通过您先前输入的次数。这里也没什么问题。
然后我们将amount_end的值设置为amount_start当前值的两倍。你知道吗

现在,让我们看看内部循环。这里,amount_start的值将通过列表(amount_start, amount_end)
我们将在这个循环中循环两次,首先amount_start保留其初始值,然后amount_startamount_end的值。
这个循环与

amount_start = amount_start
print(day, amount_end, sep='         ')
amount_start = amount_end
print(day, amount_end, sep='         ')

然后你就能明白为什么它会把同一行打印两次。你知道吗

为了消除重复,使代码更具可读性,我建议使用以下代码:

day = int(input('How many days did you work?: '))
start = 1
end = day
amount_start = 0.01

print()
print('Day     Amount ($)')
print(' -          ')

for day in range(start, end + 1):
    amount_end = amount_start * 2
    print(day, amount_end, sep='         ')
    amount_start = amount_end

如果你对我的回答有任何疑问,请尽管问。我希望这有帮助。你知道吗

不要嵌套for循环

您应该只有一个for循环:

day = int(input('How many days did you work?: '))
start = 1
end = day
amount = 0.01 # Start and End shouldn't be a thing
total = 0 # I think this is what you wanted... the amount will double every time and the total will be increased by the amount every time

print()
print('Day     Amount ($)')
print(' -          ')

for day in range(start, end + 1):
    total += amount # Give the person salary
    print(day, total, sep='         ') # Print the total amount of money earned
    amount *= 2 # Double the salary

相关问题 更多 >