I have written a program but I do not know how to loop it. Help would be appreciated.
Here is the program I need help with.
There are two types of loops: indefinite (while) loops and definite (for) loops. If you want to loop your program a specific amount of times, then use the for loop:
for count in range(0, <number of repetitions minus one>):
# code
If you want to loop the program until the user enters "QUIT" or some other string, use this:
sentinel = input("Enter QUIT to exit or anything else to continue: ")
while sentinel.upper() != "QUIT":
# code
Here are some helpful links to tutorials:
http://www.learnpython.org/en/Loops
http://www.python-course.eu/python3_for_loop.php
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html#while-statements
If you're talking about an infinite loop (i.e it has to go on and on without stopping) then simply use
white True:
<Your code here>
If it's not an infinite loop and only till a certain value comes true then you can do something like:
counter = 0
while counter <= 10:
print "This will continue till counter = 10"
counter += 1
You should make a function of the program, this function you can put in a loop. For further help, please post your code!
Related
I'm trying to exit an infinite loop but I'm stuck in it. I've tried using the break statement in different ways but the result is always the same: the program terminates after exiting the loop and it doesn't perform the rest of the code. What should I change in the code to solve this problem?
moylist = []
import copy
while True:
thing = input()
if thing == '':
break
moylist.append(thing)
moylist.insert(-2, 'and')
moynovlist = copy.deepcopy(moylist)
moynovlist1 = moynovlist[-2:] # cutting the end
perv = str(moynovlist1)
perv1 = perv[:4] + perv[4:] #without the comma (and ...)
The code is running fine! The reason you think it is exiting the whole program instead of just the while loop is because you don't have any print statements. Simply add, print(perv1) at the end of your program and you'll see that perv1 changes, meaning the loop was exited properly.
I've lurked on SO for a little while, but all of the existing posts I've seen haven't been able to help me. I'm currently teaching myself python, so I apologize if this is an easy fix I'm not seeing.
My objective with this piece of code is to cycle through tabs in a browser using pyautogui.hotkey. It takes user input for number of tabs to cycle through, and executes the pyautogui command.
My issue, however, is that I can't manage to create a looping for or while loop.
I've played around with should_restart variables, for i in range(x) etc etc, but I'm just not seeing my fix.
The code below is essentially what I want to streamline together.
My idealized flow is:
Take input -> increase tabcounter by 1 until it equals input -> reset tabcounter-> rinse & repeat.
numberofTabs = input('How many tabs do you have? \n')
tabcounter = 0
while int(tabcounter) < int(numberofTabs):
tabcounter = tabcounter+1
pyautogui.hotkey('alt', str(tabcounter))
break
while int(tabcounter) == int(numberofTabs):
tabcounter = 0
I want this code to loop until I interrupt it, or for a lengthy period of time.
Thank you in advance. I appreciate the help!
EDIT: After reworking it, and wrapping my code in a loop, I came up with this:
loopcount = input('How many times do you want this to loop?')
time.sleep(5)
count = 0
for i in range(int(loopcount)):
while count < int(numberofTabs):
count += 1
pyautogui.hotkey('alt', str(count))
time.sleep(1)
else:
count = 0```
I'm trying to make the program choose one of the items from the list, print it and repeat the process again and again.
I tried to create a boolean for the loop and the time.sleep doesn't seem to do something.
import random
import time
sounds=["Kick", "Hi-Hat", "Snare"]
beat=random.choice(sounds)
while True:
print(beat)
time.sleep(0.5)
It was supposed to print random items infinitely with a sleep of half a second but every time I run the program it just picks a random item and prints it again and again really fast (sorry for the bad English, I'm Portuguese).
You are only selecting the random item once and then running the loop. Try putting the random function inside the loop like this:
while True:
beat=random.choice(sounds)
print(beat)
time.sleep(0.5)
If it's faster than 0.5 seconds in your code it's probably because you've indented it bad and only the print statement falls inside the while loop. Be sure to indent everything that should be inside the loop with 4 spaces like I did here.
def jump_slide():
num=int(input('Enter a number :'))
if num>20:
print('slide under')
else:
print('jump over')
The above runs just fine when not in a while loop.
But once in the loop below, it completely ignores the else block
while True:
jump_slide()
Any suggestion please.
I'm new to Python
Your code is dependent on the input that you give to the variable num in the function `jump_slide()'.
If you give a value less than 20 to the num variable, it will execute the else block.
otherwise your code is fine as far as syntax is concerned.
if-elseis a conditional statement so depending on the condition inside the if it will execute either of the statements.
An example in your program:
Say you enter a number 30 when you run the program, it will print "slide under" but suppose
if you enter 10 your program will print "jump over".
So depending on your input it will print either of the statements but not both.
Your code is fine. One more way for doing your work is.
def jump_slide():
while(True):
num=int(input('Enter a number :'))
if num>20:
print('slide under')
else:
print('jump over')
if num==-1:
break
dont put while loop here.
jump_slide()
now if you enter num greater than 20 if execute and "Slide under" print on the screen
if you enter number smaller than 20 else execute and "Jump over" print on the screen
if you press -1 than your loop will break and code after the function will execute or the program ends
First off, forgive me, because I'm incredibly new at this Python thing (I'm really an HTML/CSS kind of guy, but I'm trying to branch out). This is probably an elementary sort of question, but we all have to start somewhere, right?
I'm putting together a very basic Python program that will select a random letter from a string of letters and print it out every time someone hits the any key. The whole thing is pretty simple, and currently returns a random letter, but doesn't wait for a keypress to do so, and stops after completing the function runs once.
import random
letterlist = 'abcd'
def random_letter(letters):
print ('Press enter for a random letter...')
print random.choice(letters)
random_letter(letterlist)
Output should look like this:
Press enter for a random letter.
'b'
Press enter for a random letter.
(and so on...)
It's clear that whatever I need to do ought to fall inside of random_letter someplace. I've been googling around and have found lots of references to raw_input and mvscrt, but I'm not entirely sure what I need. It's entirely possible that I'm just asking the question wrong.
I'm assuming assuming that I need some sort of loop going on to keep this running indefinitely.
Thanks in advance!
For starters, you need a loop somewhere to continue prompting the user. You also need some sort of exit condition for the loop. This loop can be inside the function like so:
def random_letter(letters):
while True:
x = raw_input('Press enter for a random letter...')
if x == 'done':
break
print random.choice(letters)
random_letter('abcdef')
Notice that inside the loop we use raw_input to prompt the user to type something, anything, then press enter. When the user types done and hits enter, we break out of the loop using break.
An alternative would be to wrap your existing function in a loop and take care of the prompting outside the function.
def random_letter(letters):
print random.choice(letters)
while True:
x = raw_input('Press enter for a random letter...')
if x == 'done':
break
random_letter('abcdef')
If you don't have to use a loop, and thinking of capturing keyboard events, then there are no cross-platform ways of doing it: Is there a cross-platform python low-level API to capture or generate keyboard events?
For Windows, there is pyHook: http://pyhook.wiki.sourceforge.net/
You can look into the code of pyKeyLogger: http://pykeylogger.wiki.sourceforge.net/
Or a dirty way, capture interrupts: Capture keyboardinterrupt in Python without try-except