print("You're in the lost forest\n" + "*" 25) print("" 25) print(" :-( ") print("" 25) print("" *25) print("Right or Left")
which_way = (str.capitalize(input ())) while which_way == "Right": print("HaHaHa!!! You are still in the forest!!!") break
I'm doing an assignment that requires I make a code that creates random numbers in a loop until I give a specific input. I just don't know how to get the loop to run while an input is requested. PLZ HELP!
EDIT:
To clarify the assignment:
Write a program that enters a number of positive integers.
The program ends when the user gives in a negative number.
a) Before the program ends, the largest number is printed.
b) Before the program ends, the smallest number is printed.
c) Before the program ends, the sum of the even numbers and the sum of the odd numbers are printed.
(I can do the a,b,c part no problem. It's the Program that creates the numbers i have problems with)
I asked my teacher what he meant by "a number of positive integers". He stated that the program should create numbers until the negative number is given.
EDIT 2:
I have concluded that I'm an idiot. It is the user who inputs the numbers. Thank you all for the help and not giving up with my dense skull :) (great community👍)
Videos
For the past 2 months I have been doing the Codecademy Python 3 course and last month I went into loops and functions and I was incredibly overwhelmed just like I was in Java. Functions are easy nothing special, at least yet, but loops are made me take that month break.
I know the theory of loops. I think I know what commands should be used where and when but for the love of god I can not write a simple loop, even after countless errors. Could anyone point me in the right direction? I really dont want to quit another language for the same reason.
Edit: a user pointed out that I need to elaborate on "simple loops". For example if I had a list and wanted to print a sentence as many times as the length of the list I know I would use len and range and have the print statement inside the loop but I can't implement it
It continues to puzzle me why we have no do-while loop in Python.
In Python code, it's common to see the following pattern:
# ... some code ....
while condition:
# ... same code copied here ...This is of course prone to problems because of the "minor" code duplication.
Alternatively, you might see this better option:
def some_code():
# ... some code ...
some_code()
while condition:
some_code()This involves creating a function even though IMHO it often serves to bloat the code unnecessarily.
And than there's this variation:
while True:
# ... do something ...
if not condition:
breakIMHO, this approach, especially when the body of the loop is fairly large, fails to communicate the logical intent of the code in a clean manner.
Of course - all of these approaches do work. But IMHO a syntax which could clarify programmer's intent in the most precise and concise way is the following classical do-while:
do:
# ... do something ...
while some_conditionI know that years ago do-while style constructs have been proposed in PEPs and rejected.
But isn't it time we review the idea again? I think there is a considerable amount of code which could benefit from this.
Would love to hear your thoughts :)
While loops is kinda frustrating I'm 20 days into python and I'm stuck on loops since last 4 days
I have just started learning python and I am really confused between the while loops and the for loops. I don't seem to understand that if there is a while loop then whats the point of a for loop?? when we have a while loop. why would somebody use for loops over while loops??? Can somebody plz give me some examples over when would I use for for loops over while loops cos I am going really frustrated right now cos of for loops
Why would somebody use a loop construct when there is goto? Why would somebody use a high-level language when there is assembly language? Why would somebody name their variables when they can just use the memory addresses?
Answer: Because writing code that intuitively "looks like" the thing it is intended to do, both a) makes writing programs much less work, b) dramatically reduces the number of bugs, and c) greatly decreases the difficulty of reading, understanding, and maintaining the code later.
We use for loops when we want to loop over a range, or loop over the elements of a set. This is a fixed operation over a known amount of steps. Essentially, we are saying something along the lines of "for each employee, calculate the salary and submit a payment", so we call it "for" to highlight this relationship. In the case of Python, for loops also provide a special efficient syntax for looping over the elements of a set, so it's less work to type the thing in too. Some other languages call that variant of the for statement "foreach".
We use while loops when we want to continue repeating an operation while a condition continues to hold. For example, we continue looping as long as we encounter no errors, or as long as we receive more data from a network connection. These are not fixed ranges, but take place while a condition holds, so we call it "while".
Typically, you use a for-loop when you know how many times you want to loop, for example when iterating over a list. You use a while-loop when you don't know how many times you want to loop - for example, if you want to loop until the user enters the string "quit" from the keyboard.
Hi all ! Python hobbist hover here, was asking to myself if there is a pithonic way of keeping a loop until a user input is right, for example this is my piece of code ( which works ):
i = False
while i is not True:
paths = Path(input("Input directory here:\n"))
if paths.is_dir():
i = True
else:
print(paths, " is not a valid directory...\n")Is there a better way to do this or more readable ? Thanks in advance
Is it more efficient than writing a while loop and just telling it to stop at a certain point?
for means "do something with each of these things".
while means "keep doing this until something is no longer true".
So... say what you mean. Readability counts.
In Python a for loop can be used with any iterable, which includes any sequence as well as other kinds of things. For example, a file object an iterable which yields each line when iterated:
f = open(...)
for line in f:
...
Expressing that as a while loop would be very cumbersome. Moreover, that you think the two are essentially the same indicates that you're probably used to looping over indices, which is very much not pythonic. Many things in Python are inherently iterable, including as lists, dicts, sets, strings, etc. Some iterables are even infinite in length, or don't support indexing (such as the file object above), so you couldn't iterate over them by index even if you wanted to. Iterating over them with for on the other hand is simple and natural:
d = {'John': 18, 'Bobby': 23, 'Jan': 22}
for name, age in d.items():
...
Expressing that with a while loop would be hideously ugly.
About a month in to my Intro to Python class at my local community college, this week was the lecture and HW on "While" and "For In" Loops. I gotta say, I'm completely lost. Anyone have any tips or possibly helpful material for a noobie? Genuinely just seems like everything before this was linear and somewhat straightforward on what the solution or answer was going to become. Now print statements are not what they seem or not in the order in which I believe they were gonna print. The formulas as well, just seems like the difficulty level was raised tremendously lol. Either way Thanks and any help is appreciated.
I’ve written a lot of python code over the last few months, but I can’t think of a single time I’ve ever used a while loop. I mean, I use for loops pretty often, but not while loops.
Is this just down to personal preference, and I’m just using what I’m comfortable with? Or can you guys think of some situations where a while loop would be the easiest way to do things, but it’s possible to do it with a for loop? Maybe I’m using for loops in situations that I should be using while loops.
EDIT: Thanks for the suggestions. I found a few places in my code where a while loop makes sense.
First, I check if a folder has any files in it, and while it does, I delete the first one in the list:
useless_files = os.listdir("MGF_HR_Data") # I think these are files it creates when downloading the MGF data but they are extra and don't do anything
while len(useless_files)>0:
os.remove(f"MGF_HR_Data/{useless_files[0]}")
useless_files = os.listdir("MGF_HR_Data")
print("Deleting useless file from MGF_HR_Data") I also used a while loop to check if the data has been downloaded, and if it hasn't prompt the user to download it and then press enter to check again. This way, the code doesn't break if the user forgot to download the file first:
# Check if you downloaded the file in Matlab already. If not, ask the user to download it and try again.
while os.path.exists(file1)==False:
print(f"{file1} not found. Please open Matlab and run the following code to download the MGF data:" )
print(f"download({wstime.year}, {wstime.month}, {wstime.day})")
input("Press enter to try again after downloading the MGF data. \n") (Okay, I know this isn't the most efficient way to do this. There must be a way to use python to open matlab and run a matlab command, rather than asking the user to do it themselves. However, I don't know how to do that, so this works for now.)
please help me. i know what loops are but i dont know how to use them in python. Thanks!
Completely stuck on the concept of loops. Ive looked through all the recourses possible to get a grasp of it but i just cannot get my mind to understand it!
Someone that has tips to cure this illness of mine?
There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break statement:
finished = False
while not finished:
... do something...
finished = evaluate_end_condition()
Complete beginner to python and programming and just enrolled in Angela Yu's 100 Day Python course. I'm only on Day 10 and I am super confused about for loops, while loops, and using the loops in functions. I feel like it's progressing too fast for me.
I'm never able to build the projects without looking at the solutions and I feel like if I continue relying on the solutions to complete the project, I won't actually learn anything.
Does anyone have any advice on how to get a better grip on these basic concepts, and how to practice these concepts by myself?
Hi all
Whenever I write a while loop, I always want to limit the number of iterations it can run to avoid infinite loops while developing the program, what would the most pythonic way of doing that?
theres obviously the basic
n = 0
while condition and n < 100:
n += 1but the n+=1 can easily get lost or commented out when you are working on the code
Ive also tried
def count_generator():
n = 0
while True:
yield n
n += 1
counter = count_generator()
while condition and next(counter) < 100:or
class Counter:
def __init__(self):
self.count = 0
def inc(self):
self.count += 1
return self.count
counter = Counter()
while condition and counter.inc() < 100:both of these feel like a lot of boiler plate for what should be a simple task, is there anything better?
Hey All,
I'm having the hardest time understanding for loops in Python.
Could someone explain what is happening in this example? I see we have a variable v. I somewhat understand that "range" is built into Python. I don't understand the output.
for v in range(3, 10, 3):
print(v)Output:
3
6
9
I keep seeing examples online but they lose me every time. Thank you in advance.
-------------------------------------------------
*Edit Thanks to everyone who replied. My misunderstanding was not knowing what range was fully doing.
range(start, stop, step)
So basically this:
i = 0while i<5 or not success():i += 1
I want to ask, whats the difference between looping using the while and the for function? I know both of these functions loops through stuff but what exactly is the difference between them? I have trouble understanding so I decide to ask this question on here
I started learning python a couple of days ago and decided to make a little text adventure game to practice if, elif, and else stuff. The code might be a little clunky right now, I'm not quite sure, but I'm pretty proud of it. There's several endings, but I'm not sure how to get it to loop back to the start once an ending is reached. Is that possible, and if possible, how would I go about doing it?
I posted the code to GitHub (this is the link Text-Adventure-The-Woods/Text Adventure.py at main · novarowan13/Text-Adventure-The-Woods (github.com) )
I'm also a bit curious on how to loop back to the same prompt if the invalid option is taken, make it so that it doesn't move on until a valid option is picked.