Simple Python loop counter issue - python

Ok, I am trying to make a simple program to kinda test how well i am learning things, I have come to a point where it is getting very large as I want the program to store data in sections (Day1,Day2....ect) so i tried to assign it to read the current Day count (Num_Days = ) but it doesnt seem to like this. I made a small test loop to try and test out if i could do this and have gotten stuck even though the logic looks good to me. I tried to do some searches but as i dont know what I am trying to do is even called I havent gotten very far. What I want to do is have the loop read the Num_Days and give the Days() the count and assign it to that day through 'n'.
Num_Days = 0
Total = 0
Data = 0
Day1 = 0
Day2 = 0
Day3 = 0
def Start_Work(x):
while Num_Days < 3:
Num_Days += 1
print "This is Day:",Num_Days
n = Num_Days
Total = +20
Day(n) += Total
else:
print "failed"
x = str('start')
I also made a dpaste on it as it is easier for me to look at it that way then in the full black: http://dpaste.com/1398446/
In order to clear up apparently where I lost some people with thinking that I am just trying to make a single loop that sits by its self I am going to put up what I am trying to use this for. This program is functioning the way I have wanted it to, the problem being that if i wanted o make it bigger it would get to be very long.
NumDays = 0
TotalOut = 0
Day1Tot = 0
Day1_RepsCnt = 0
Day4 = 0
def Work_Out(x):
while x == 1: ##crunches
NumDays = 0
TotalOut = 0
Day1Tot = 0
Day1_RepsCnt = 0
Day1_WghtCnt = 0
Day4 = 0
while NumDays < 3:
Day1_Wght = float(raw_input("How much weight did you use?"))
Day1_Reps = float(raw_input("How many reps did you do?"))
Day1_Sets = float(raw_input("How many sets were done?"))
Day1 = Day1_Wght * Day1_Reps * Day1_Sets
NumDays += 1
print "Day:",NumDays
print "Your total output is:",Day1
Day1_RepsCnt += Day1_Reps
Day1_WghtCnt += Day1_Wght
Day1Tot += Day1
TotalOut += Day1
if NumDays == 3:
print "Your total output for 3 days is:",TotalOut
print "Lets increase the Weight to",(Day1_Wght + 10)
print "Increase the Weight for days 4-6"
while NumDays >= 3 and NumDays <6:
Day4_Wght = float(raw_input("How much weight did you use?"))
if Day4_Wght <= (Day1_WghtCnt/3):
print "You need to increase your total output, add 10 pounds."
break
Day4_Reps = float(raw_input("How many reps did you do?"))
Day4_Sets = float(raw_input("How many sets were done?"))
Day4 += Day4_Wght * Day4_Reps * Day4_Sets
NumDays += 1
print "Day:",NumDays
if Day4_Wght <= (Day1_WghtCnt/3):
print "Re-enter totals once you have added the additional weight."
else :
print "Your total output was:",Day4
while x == 2: ##Benching
NumDays = 0
TotalOut = 0
Day1Tot = 0
Day1_RepsCnt = 0
Day4 = 0
while NumDays < 3:
Day1_Wght = float(raw_input("How much weight did you use?"))
Day1_Reps = float(raw_input("How many reps did you do?"))
Day1_Sets = float(raw_input("How many sets were done?"))
Day1 = Day1_Wght * Day1_Reps * Day1_Sets
NumDays += 1
print "Day:",NumDays
print "Your total output is:",Day1
Day1_RepsCnt += Day1_Reps
Day1Tot += Day1
TotalOut += Day1
if NumDays == 3:
print "Your total output for 3 days is:",TotalOut
print "Lets increase the Reps to",(Day1_Reps + 10)
print "Increase reps for days 4-6"
while NumDays >= 3 and NumDays <6:
Day4_Wght = float(raw_input("How much weight did you use?"))
Day4_Reps = float(raw_input("How many reps did you do?"))
if Day4_Reps <= (Day1_RepsCnt/3):
print "You need to increase your total output, do 10 more Reps."
break
Day4_Sets = float(raw_input("How many sets were done?"))
Day4 += Day4_Wght * Day4_Reps * Day4_Sets
NumDays += 1
print "Day:",NumDays
if Day4_Reps <= (Day1_RepsCnt/3):
print "Re-enter totals once you have completed the additional reps."
else :
print "Your total output was:",Day4
print "Available work outs in this version: crunches, benching"
Input = raw_input("What type of Work Out did you do?")
if Input.lower() == str('crunches'):
Work_Out(1)
if Input.lower() == str('benching'):
Work_Out(2)
else:
print "Failed"
And yes I understand that this needs to be cleaned up, but I have other ideas of what i want to throw in there and things i want to rearrange, but right now its just trying to figure out how I can break this into weekly cycles, and break each week into daily cycles, so i started with trying to get through one week and figure out that it would be very difficult just trying to get past 2 days so i broke it into 2 parts instead of 6 days. Any advise is welcome.

welcome to Python!
One of the beauties of Python is that the vast majority of Python programmers try to do things in the most "Pythonic" way when possible, so the first step I am going to take is to rename your variables and such according to PEP-8 standards. In other words, class names would be capitalized camelcase, but standard variables should be lowercase underscore-separated.
Second, if you ever find yourself naming variables with numbers like day1, day2, day3 etc, stop yourself and realize how unmaintainable that would be if you ever had to extend your program to work with 100 days (or 1,000, or 10,000, you get the point). Instead, you can just use a list called days and add as many as you need to it according to some configuration variable (e.g. total_days). For example:
total_days = 3
days = []
for _ in range(total_days):
days.append(0)
Or, use a list comprehension to be more Pythonic:
total_days = 3
days = [0 for _ in range(total_days)]
With these implementations all you'd have to do to add more days is to change the value of total_days. With all this in mind, let's try to reproduce your program:
# method definition
def start_workouts(total_days, init_workout, workout_increase):
workouts = [(init_workout + day * workout_increase) for day in range(total_days)]
return workouts
# method execution (3 days, starting at 100, increasing 20 each day)
my_workouts = start_workouts(3, 100, 20)
# my_workouts == [100, 120, 140]
# my_workouts[0] is "Day1"
# my_workouts[1] is "Day2"
# my_workouts[2] is "Day3"
So notice we moved some variable declarations to be passed in as arguments to your method. This way you can easily change the criteria for your workouts depending upon various circumstances that you might decide later. Also, we reduced all the calculations down to be part of a single list comprehension! (Isn't Python awesome?)
I hope I understood what you were trying to do correctly and that this helps you out. Let me know if you have any questions.

Might not be the best idea to set Days explicitly, as #blakev says, just use a list.
Num_Days = 0
Total = 0
Data = 0
Days = []
def Start_Work():
while Num_Days < 3:
Num_Days += 1
print "This is Day:",Num_Days
Total += 20
Days[Num_Days] = Total
else:
print "failed"
Start_Work() # call the function
You should get output that looks like
[20, 40, 60]

Your code does not look as correct Python code. Below are correction:
#-------------------
#while (condition):
# #commands
#-------------------
#for i in xrange(3):
# #commands
#-------------------
#Examples:
Num_Days = 0
Total = 0
Day = [0,0,0]
while Num_Days<3:
Num_Days += 1
print "This is Day:",Num_Days
Total += 20
Day[Num_Days-1] += Total
print Day
>>>
This is Day: 1
This is Day: 2
This is Day: 3
[20, 40, 60]
or better use:
Total = 0
Day = [0,0,0]
n = 3
for i in xrange(n):
print "This is Day:",i+1
Total += 20
Day[i] += Total
print Day
>>>
This is Day: 1
This is Day: 2
This is Day: 3
[20, 40, 60]

Related

index element creates not needed input

I want to make a code that would propose a customer one or more of products to add to his shop list if he has total cart less than available budget (for example, he bought products for 120 dollars, and program should ask him if he want to add one or a couple of products (for example for 20 and 30 dollars) in list so budget gets close to 150 dollars limit)
My problem here is that somehow i += 1 creates an unwanted input() process which i cannot explain
I am a newbie in Python so maybe someone can propose the solving of problem or even better version of my code, i'll be greatful for every help!
https://ibb.co/vJwhMw0 link for image here
inp = 'bar'
product_list = ['bar', 'bread', 'milk', 'coconut']
product_price = [10, 24, 30, 25]
indx = product_list.index(inp)
price = product_price[indx]
budget = 150
total = 120
proposal_list = ''
i = 0
while total < budget:
if (product_price[i] + total) <= budget:
total += product_price[i]
proposal_list += product_list[i]
i = i + 1
print (f'You can also add: {proposal_list}')
There is some problems with your code. No unwanted input() is created it's just that your while loop is infinite because i never changes because the condition is never true at some point.
while total < budget:
if i >= len(product_price):
break
elif (product_price[i] + total) <= budget:
total += product_price[i]
proposal_list += product_list[i]
i += 1
You code got inside infinite loop right after this line:
while total < budget:
Once the code inside this line is executed
if (product_price[i] + total) <= budget:
total become equal 130. Condition total < budget is still true but condition
if (product_price[i] + total) <= budget:
is not.
You need to exit the while loop. You can't do it until you update total.

How to add to a counter using decisions and input

I have tried for the past hour to make this program. The aim of the program is to record the preference of food for 15 people and count and display the total at the end. Each person can only choose 1 food. Here is where I'm stuck. None of this code seems to work(add to the counters). If anybody can help or send me the correct code it would be greatly appreciated:)
#Choices of food for the customers
meatplate_1 = 0
fishplate_2 = 0
vegetableplate_3 = 0
#Decision making as input data
for i in range (15):
num = int(input("What do you want for lunch?"))
if num == 1 :
meatplate + 1
print(meatplate_1)
As already mentioned by #0x5453 in comments, you should increment meatplate_1 variable.
And, If condition should come inside for loop, increment should be done by += operator.
You can refer below code.
#Choices of food for the customers
meatplate_1 = 0
fishplate_2 = 0
vegetableplate_3 = 0
#Decision making as input data
for i in range (15):
num = int(input("What do you want for lunch?"))
if num == 1 :
meatplate_1+=1
elif num==2:
fishplate_2+=1
elif num==3:
vegetableplate_3+=1
else:
pass
print(meatplate_1)

Probability Dice Game in Python with two dices

I want to interate 1000 times over the following function to find out if you win or loose money in this game.
The game is designed as such that you throw a pair of dice and get money back or loose money. Let's say we start with 5 coins.
Throwing a 12 yields 1.5 coins.
Throwing an 11 yields 1 coins.
Throwing a 10 yields 0.5 coins.
Throwing a 9,8 or 7 yields nothing.
Throwing a 6,5,4,3,2 or 1 deducts 0.5 coins from your amount of coins.
This is what my implementation looks like so far:
def luckCalc():
amount = 5
# if 12 then 1/36 chance
if random.randrange(1,7) == 6 and random.randrange(1,7) == 6:
amount = amount + 1.5
# if 11 then 2/36 chance
elif (random.randrange(1,7) == 5 and random.randrange(1,7) == 6) or (random.randrange(1,7) == 6 and random.randrange(1,7) == 5):
amount = amount + 1
# if 10 then 3/36 chance
elif (random.randrange(1,7) == 5 and random.randrange(1,7) == 5) or (random.randrange(1,7) == 4 and random.randrange(1,7) == 6) or (random.randrange(1,7) == 6 and random.randrange(1,7) == 4):
amount = amount + 0.5
# if 9,8,7
# 4/36 + 5/36 + 6/36 chance
# 1+6, 2+5, 3+4, 4+3, 5+2, 6+1 chance
# 2+6, 3+5, 4+4, 5+3, 6+2 chance
# 3+6, 4+5, 5+4, 6+3 chance
# then no change in amount
# if 6,5,4,3,2,1
# chances...
# then amount -0.5
return amount
# Iterate over the dice throwing simulator and calculate total
total = 0.0
for a in range(1000):
total = total + luckCalc()
print (total)
I stopped coding towards the end of the function, because I recognised that there must be a more elegant solution on how to achieve this. Any interesting suggestions, what is this Monte Carlo I keep hearing about?
Each time you call random.randrange(1,7), you generate a new random number. Since you're testing a single "turn", roll twice:
def roll_die():
return random.randrange(1, 7)
total = roll_die() + roll_die()
And see if the sum is in a range:
def play_turn():
total = roll_die() + roll_die()
if total == 12:
return 1.5
elif total == 11:
return 1.0
elif total == 10:
return 0.5
elif total <= 6:
return -0.5
else: # total is 7, 8, or 9
return 0
Here's the result of 100,000 rounds:
>>> from collections import Counter
>>> counts = Counter(play_turn() for i in xrange(100000))
>>> counts
Counter({-0.5: 41823, 0: 41545, 0.5: 8361, 1.0: 5521, 1.5: 2750})
>>> probabilities = {score: count / 100000.0 for score, count in counts.items()}
>>> probabilities
{-0.5: 0.41823, 0: 0.41545, 0.5: 0.08361, 1.0: 0.05521, 1.5: 0.0275}
You can actually roll (ha!) everything you are doing into a single function:
from random import randrange
def play_game(rolls=1000, amount=5, n=6):
"""Play game 'rolls' times, starting with 'amount' on 'n'-sided dice."""
for i in range(rolls):
roll = randrange(1, n+1) + randrange(1, n+1)
if roll == 12:
amount += 1.5
elif roll == 11:
amount += 1
elif roll == 10:
amount += 0.5
elif roll < 7:
amount -= 0.5
return amount
I notice a few things in your code. First, for the 6-1 cases you're not actually subtracting 0.5 from the amount. Second, since you don't pass in the initial amount each loop you're adding between 5 and 6.5 to your total, which makes the total pretty pointless.
A more effective total would be to pass in the amount each time:
def luckCalc( amount ):
And then for your loop:
total = 5.0
for a in range(1000):
total = luckCalc(total)
Blender's answer, which just posted as I was writing this, is a great way to simplify your main function.
I personally like setting up my results table as an array (or a dictionary, but this suited my purpose better since every result was one of a small number of possible integers), with the index of each dice roll set to the value of the resulting change. See below.
import random
def luckCalc(coins=5):
diceroll = random.randint(1,6)+random.randint(1,6) #roll them bones
#here's that table I was talking about....
results_table = ['index 0 is blank',"you can't roll a one on two dice",-.5,-.5,-.5,-.5,-.5,0,0,0,.5,1,1.5]
coins += results_table[diceroll] #changes your coins value based on your roll (as an index of results_table)
if results_table[diceroll] > 0: #change the string if your result was + or -
result = "gained {}".format(results_table[diceroll])
else:
result = "lost {}".format(results_table[diceroll]*-1)
print("You {} coins, putting you at {}".format(result,coins)) #report back to the user
return coins #this is how you save your output
#CONSTANTS GO HERE -- YOU CAN CHANGE THESE TO CHANGE YOUR PROGRAM
STARTING_COINS = 5
HOW_MANY_ITERATIONS = 1000
#this way we don't modify a constant
coins = STARTING_COINS
#do it how many times?
for _ in range(HOW_MANY_ITERATIONS): #oh yeah that many times
coins = luckCalc(coins) #runs the function and saves the result back to coins
#report to the user your final result.
print("After {} rolls, your final total is {}".format(HOW_MANY_ITERATIONS,coins))

Writing python code to calculate a Geometric progression

Im new to programming and python. I need help with coding a geometric progression thats supposed to calculate the progression 1,2,4,8,16... Heres what I have so far:
def work_calc (days_worked, n):
temp=int(1)
if days_worked<2:
print (1)
else:
while temp <= days_worked:
pay1 = (temp**2)
pay = int(0)
pay += pay1
temp +=1
print ('your pay for ',temp-1,'is', pay1)
main()
Right now it gives me this output: 1, 4, 9, 16, 25
i need : 1,2,4,8,16,32...
im writing code that basically should do this:
Example:
Enter a number: 5
your value 1 is: 1
your value 2 is : 2
your value 3 is : 4
your value 4 is : 8
your value 5 is : 16
your total is: 31
Thanks in advance for your help and guidance!
P.S: Im like a dumb blonde sometimes(mostly) when it comes to programming, so thanks for your patience..
As I said, looks like you need powers of 2:
def work_calc (days_worked, n):
for temp in range(days_worked):
print ('your pay for ', temp + 1, 'is', 2 ** temp)
if you want to print strings (not tuples as you're doing now):
def work_calc (days_worked):
for temp in range(days_worked):
print 'your pay for {} is {}'.format(temp + 1, 2 ** temp)
>>> work_calc(5)
your pay for 1 is 1
your pay for 2 is 2
your pay for 3 is 4
your pay for 4 is 8
your pay for 5 is 16
Just to note - your code is calculating squares of temp, not powers of 2 that's why is not working
I understand this is probably overkill for what you are looking to do and you've been given great advice in the other answers in how to solve your problem but to introduce some other features of python here are some other approaches:
List comprehension:
def work_calc(days):
powers_of_two = [2**x for x in range(days)]
for i, n in enumerate(powers_of_two):
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(sum(powers_of_two)))
This is compact and neat but would hold the whole list of 2^n in memory, for small n this is not a problem but for large could be expensive. Generator expressions are very similar to list comprehensions but defer calculation until iterated over.
def work_calc(days):
powers_of_two = (2**x for x in range(days))
total = 0
for i, n in enumerate(powers_of_two):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
Had to move the total to a rolling calculation and it still calculates 2**n each time, a generator function would avoid power calculation:
import itertools
def powers_of_two():
n = 1
while True:
yield n
n *= 2
def work_calc(days):
total = 0
for i, n in enumerate(itertools.islice(powers_of_two(), days)):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
As I said overkill, but hopefully introduces some of the other features of python.
Is this a homework question? (insufficient rep to comment)
In the sequence 1,2,4,8,16,32 each term is double the previous term.
So, you can keep a record of the previous term and double it to get the next one.
As others have mentioned, this is the same as as calculating 2^n (not, as I previously stated, n^2) , where n is the number of terms.
print ('your pay for 1 is' 1)
prevpay = 1
while temp <= days_worked:
pay1 = prevpay*2
pay = int(0)
pay += pay1
temp +=1
prevpay = pay1
print ('your pay for ',temp-1,'is', pay1)
That is all too complicated. Try always to keep things as simple as possible and especially, keep your code readable:
def main():
i = int(input("how many times should I double the value? "))
j = int(input("which value do you want to be doubled? "))
double_value(i,j)
def double_value(times,value):
for i in range(times):
i += 1
value = value + value
print(f"{i} --- {value:,}")
main()
Hope I could help.

How do I update a single variable within a loop?

What I'm trying to do in the while loop is iterate the payments by an integer of 10 so that if that integer (g) fails to get the CBalance <= 0 within a 12 months period then all of the variables reset except for g, which goes up by 1.
Balance = float(raw_input('Enter Balance '))
Rate = float(raw_input('Enter interest rate '))
monthlyI = Rate/12
month = 0
g = 1
Payment = 10
CBalance = Balance
while CBalance > 0:
Payment = Payment*g
month += 1
CBalance = CBalance *(1+ monthlyI)- Payment
if month > 12:
month = 0
g += 1
Cbalance = Balance
I think I finally understand what your question is about and what's causing the problem -- namely a simple misspelling of a variable name. To fix it, just change the last line of the statements following the if in your while loop from:
if month > 12:
month = 0
g += 1
Cbalance = Balance
to:
if month > 12:
month = 0
g += 1
CBalance = Balance # note corrected spelling of variable name on left
Which explains why all the values weren't being reset. It would have been helpful if you explicitly mentioned which variable it was in your question if you knew it. Anyway, this sort of thing is more likely to happen when one uses Capitalized and mixedCase variable names as you are doing.
Many programmers try to avoid them for that reason, is especially with languages like Python where you generally don't have to declare variables before using them. You might want to check out the Naming Conventions section of PEP 8's style guidelines.
What I'm trying to do in the while loop is iterate the payments by an integer of 10 so that if that integer (g) fails to get the CBalance <= 0 within a 12 months period then all of the variables reset except for g, which goes up by 1.
I think what's happening is that each time you run this while you will get:
Payment = 10 * 1 //First while payment = 10
2nd time
Payment = 10 * 1 //payment = 10 again.
Which results in:
CBalance = CBalance * (1 + monthlyI) - 10
Which can never won't go to a negative value, which is needed to end the loop?
While you probably want:
counter = 1;
while CBalance > 0:
Payment = Payment*counter
month += 1
counter += 1
CBalance = CBalance *(1+ monthlyI)- Payment
if month > 12:
month = 0
counter = 1
g += 1
Cbalance = Balance

Categories