Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

About Products For Teams Search… Log in Sign up

Home
How do you get while loop to repeat over and over again in Python? Ask Question

PUBLIC Asked 1 year, 3 months ago Active 1 year, 3 months ago Viewed 186 times

Questions
I am having trouble getting my while loop to loop over and over again in Python. Here is the
Tags The Overflow Blog
problem/question I am trying to solve:
Users 1 Podcast 395: Who is building clouds for
Implement the roll_dice function in hog.py . the independent developer?
COLLECTIVES
It takes two arguments: a positive integer called num_rolls giving the number of dice to roll Exploding turkeys and how not to thaw
Explore Collectives your frozen bird: Top turkey questions...
and a dice() function.

FIND A JOB It returns the number of points scored by rolling the dice that number of times in a turn: either Featured on Meta
the sum of the outcomes or 1 (aka 'Pig Out': If any of the dice outcomes is a 1, the current
Jobs
player's score for the turn is 1). To obtain a single outcome of a dice roll, call dice() . You Now live: A fully responsive profile
Companies should call dice() exactly num_rolls times in the body of roll_dice. Remember to call dice()
Reducing the weight of our footer
exactly num_rolls times even if 'Pig Out' happens in the middle of rolling. In this way, you
TEAMS
correctly simulate rolling all the dice together. Two B or not two B - Farewell, BoltClock
and Bhargav!
Stack Overflow for
Here is my code so far, where num_rolls : the number of dice rolls that will be made and dice() : a
Teams – Collaborate
and share knowledge function that simulates a single dice roll outcome.
with a private group.
def roll_dice(num_rolls, dice=six_sided):
current_roll = 0
while current_roll < num_rolls:
current_roll += 1
total_sum = 0
current_value = dice()
if current_value == 1 or total_sum == 1:
total_sum = 1
Create a free Team
return total_sum
What is Teams? else:
total_sum += current_value
Your privacy
return total_sum
By clicking “Accept all cookies”, you agree Stack Exchange can Report this ad
store cookies on your device and disclose information in
accordance with our Cookie Policy. When I debug in PyCharm, in my example when it randomly rolls on current_value = 4, the total
sum = 4 and current_roll = 1 even when the required amount of loops is num_rolls = 5. So, Remote jobs
Accept all cookies meaning that it has only looped once when it should loop 5 times. Could anyone give any insight
Back-end developer (Python)
as to why this might be? I've made a tweak before when current_value = dice() was outside the
Nolk Montreal, QC, Canada
Customize settings while loop and I moved it inside the while loop and I thought it would fix that but it hasn't. REMOTE

python elasticsearch
Also, let me know if there are any clarifications I can make. I am a beginner learner and I'm not
great at explaining things Senior Backend Engineer
Tessian London, UK
python £80K - £130K REMOTE RELOCATION

python amazon-web-services

Share Improve this question Follow edited Aug 5 '20 at 16:37 asked Aug 5 '20 at 16:31 (Senior) Backend Engineer at
smci sadfoijdsaoiajdf sustainable start-up (m/f/x) -
28k 17 105 141 11 2 Munich or Remote
FINN München, Germany
€60K - €80K REMOTE RELOCATION

your function will return in either the if or else statement, which breaks out of the loop. it seems like python serverless
what you want to do is move your return total_sum statement outside of your while loop. – hkennyv
Aug 5 '20 at 16:36 Python Developer (Remote)
X-Team No office location
@L.Grozinger isn't my while loop currently true? since current_roll = 0 and the while loop only occurs REMOTE
when current_roll = 0 < num_rolls = 5 which is True –  sadfoijdsaoiajdf Aug 5 '20 at 16:36 python django

Your while-loop itself is ok, but you do the return too early. The if-else clause with the return statements
should not be indented with the loop, it should only happen after the while-loop has finished. – smci Aug 5 Senior Python Developer - Django
Rest Framework
'20 at 16:38
n.exchange Lisbon, Portugal
@khuynh would deleting the two return total_sum statements and only adding only return €70K - €100K REMOTE RELOCATION
total_sum at the same indentation as the while loop fix this issue? –  sadfoijdsaoiajdf Aug 5 '20 at 16:39 ethereum bitcoin

BTW, you should use for _ in range(num_rolls): rather than a while loop. – Barmar Aug 5 '20 at
Senior Data Scientist
16:39
Tessian London, UK
£70K - £100K REMOTE RELOCATION
Show 2 more comments
python nlp

1 Answer Active Oldest Votes Lead Data Scientist


Tessian London, UK
£100K - £120K REMOTE
It seems like you misplaced your final return statement (indentation matters!). This is how it should RELOCATION
look: python nlp
0
def roll_dice(num_rolls, dice=six_sided): Tech Lead Engineering at
current_roll = 0 sustainable start-up (m/f/x) -
total_sum = 0 Munich/New York/Remote
while current_roll < num_rolls: FINN München, Germany
current_roll += 1 €100K - €125K REMOTE
current_value = dice() RELOCATION
if current_value == 1: python typescript
total_sum = 1
break
else: View more jobs on Stack Overflow
total_sum += current_value
return total_sum
Related
Share Improve this answer Follow edited Aug 5 '20 at 17:23 answered Aug 5 '20 at 16:38 1143 How to get file creation & modification
Wouter date/times in Python?
111 6
3410 How to get the current time in Python

thank you! It was such a simple mistake but I was stuck on this for hours. I'll know now for the future 818 How do you get the logical xor of two
–  sadfoijdsaoiajdf Aug 5 '20 at 16:44 variables in Python?

actually, when I run this through my autograder it is failing the last case. I moved the total_sum = 0 to 1480 How can you profile a Python script?
right under current_roll = 0 instead of inside the while loop. Here is what is says in my autograder: >>>
2433 How do I get a substring of a string in
counted_dice = make_test_dice(4, 1, 2, 6) >>> roll_dice(3, counted_dice) 1 >>> # Make sure you call dice
Python?
exactly num_rolls times! >>> # If you call it fewer or more than that, it won't be at the right spot in the cycle
for the next roll >>> # Note that a return statement in a for loop ends the loop >>> roll_dice(1, 1317 How to get the filename without the
counted_dice) 2 Error: expected 6, got 2 –  sadfoijdsaoiajdf Aug 5 '20 at 16:49 extension from a path in Python?

You are right, my bad. I edited my post and moved total_sum out of the while loop now. – Wouter Aug 5 '20 967 How to emulate a do-while loop?
at 17:24
1184 How to get line count of a large file cheaply
Add a comment in Python?

1391 How do I get time of a Python program's


execution?
Your Answer
Hot Network Questions
How to grep full words between spaces

How can the transfer of a soul to a new body lead


to physical deformities?

Stefan-Boltzmann Law Applied to the Human Body

The Problem of Evil/Suffering modified into


Buddhism

Ultrasound effect in a blender

Why is my itemize line spacing so huge?

Identify feminist book involving beast masters

Is it illegal to send email to someone’s work


account?
Sign up or log in Post as a guest How could people hundreds of years ago have
Name protected themselves from radiation?
Sign up using Google
Legend with marks and loosely dashed

"Mama" is now a trademark word. Can't use this


Sign up using Facebook Email word any more?
Required, but never shown
What's going on in this musical notation?
Sign up using Email and Password
What's the easiest way to factor this cubic term?

Cost of PC vs. Amiga 500 in Europe

How to manage depolarization of completed work


Post Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy on Agile Scrum

Can the nth projective space be covered by n


charts?
Not the answer you're looking for? Browse other questions tagged python or ask your own What is the correct translation of "Serviamus in
veritate"?
question.
Do I need Linux for UCB's SPICE(3)?

How to compensate noise at the output of logic


gates?

Why is a 4th order circuit referred to as 2nd order?

Single word for one who enjoys something?

How will DART be able to hit a 170 meter rock


dead-center at 6600 m/s? What technologies will
be use and how will they work together?

Why is the concept of torque necessary?

Can I know if a device is USB 3.0 or 2.0 in Device


Manager?

Question feed

STACK OVERFLOW PRODUCTS COMPANY STACK EXCHANGE Blog Facebook Twitter LinkedIn Instagram
NETWORK
Questions Teams About
Technology
Jobs Talent Press
Culture & recreation
Developer Jobs Directory Advertising Work Here
Life & arts
Salary Calculator Enterprise Legal
Science
Help Privacy Policy
Professional
Mobile Terms of Service
Business
Disable Responsiveness Contact Us
Cookie Settings
API
Cookie Policy site design / logo © 2021 Stack Exchange Inc; user contributions
Data licensed under cc by-sa. rev 2021.11.26.40833

You might also like