Python's range() function not looping - python

I tried to make a 'random' text program with 2 possible outputs, randomization works but range() isn't working. I always make some stupid mistakes so don't go hard one me over some stupid small thing pls
import time
import pyautogui
import random
time.sleep(2)
for i in range(50):
if int(random.randint(1,2)) == 1:
pyautogui.typewrite('bruh1')
pyautogui.press('enter')
random.randint(1,2)
elif int(random.randint(1,2)) == 2:
pyautogui.typewrite('bruh2')
pyautogui.press('enter')
random.randint(1,2)

x is the random number returned by random.randint(). Not sure calling x() is the right thing. Can you please have a closer look at that part?

import time
import pyautogui
import random
def typewrite(text):
pyautogui.typewrite(text)
pyautogui.press('enter')
for _ in range(50): # I use _ for variable if don't use it
x = random.randint(0,1) # return 0 or 1 of type int
if x: # if x is 1
typewrite('bruh1')
else: # if x is 0
typewrite('bruh2')

Related

When I use While Loop my Code no Longer works

import pyautogui
import pydirectinput
import time
x = 1
while x <190:
for number in range(190):
time.sleep(0.1)
pyautogui.click(480, 595)
x = x+1
if x == 190:
pydirectinput.keyDown('shiftleft')
time.sleep(2.5)
pydirectinput.keyUp('shiftleft')
x = 1
When I run this all it does is repeat the first code and does not activate the second code I am a newb at coding so I don't know why this is happening. It just activates the 2nd "x = 1" instead of doing the code above it first then resetting the loop.
I want the code to run indefinitely but run both codes instead of only the click code
What should I put in after "if x == 190:"
A while loop executes the code inside its body as long as its condition evaluates to true. Your condition is whether x is equal to 1 or not.
You initialize x to 1, but you never change its value in your while loop's body. So, the condition is always true, and you have an infinite loop.
You need to modify the value of x inside your while loop to break out of the loop.
import pydirectinput
import time
x = 1
while x == 1:
for number in range(190):
time.sleep(0.1)
pyautogui.click(480, 595)
pydirectinput.keyDown('shiftleft')
time.sleep(2.5)
pydirectinput.keyUp('shiftleft') ```

How to set condition to True?

I've created a program that uses pyautogui to locate an image stored in the directory and click on it when it finds it. So when it sees 'Microsoft Edge' it instantly clicks on it. I have this running on a loop and want to stop the loop when it finds the image. This is really important for me—but I want the loop to stop even before it clicks it, so while 'double' is False, as you will see below.
Here it is:
import pyautogui as p
import time
import random
import os
import pygame
from hashlib import sha256
def search(query):
p.hotkey("ctrl","e")
time.sleep(.1)
p.write(query)
p.press("enter")
time.sleep(.67)
def imageFind(image,g,double):
a = 0
b = 0
while(a==0 and b==0):
try:
a,b = p.locateCenterOnScreen(image,grayscale=g)
except TypeError:
pass
if double == True:
p.doubleClick(a,b)
else:
p.click(a,b)
return a,b
#p.hotkey("win","d")
counter = 1
while counter == 1:
image_find = imageFind("Edge.png",False,False)
if image_find == True:
imageFind("Edge.png",False,True)
counter = 0
I've done if image_find == True but it doesn't work as the loop continues.
So how do I code this so that when it finds the image, it stops. How do confirm that what it finds is a True statement?
imageFind does not return a single bool values but instead returns a tuple. your True condition is when both a and b are non zero so change your if image_find == True: to if all(image_find):
all() returns True only if all values are True or non zero
Or try to check if the minimum is nonzero:
if min(image_find):

Setting up a simple function in Python

I'm trying to write a function which takes my input as amount of dicerolls, gets a random number between 1,6 for that amount of dicerolls, and then appends these to a list.
I've tried different return messages, but I can't seem to to make it append to a list, and can't really think of what else I can do with my code.
terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
for x in range(antal_kast, 0, -1):
resultat = random.randint(1, 6)
terninger.append(resultat)
return resultat
print(terninger)
I'm expecting the code to append the random number 1,6 into my list above (terninger), but I'm only receiving an empty list.
you forgot to call your function => terning_kast()
terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
for x in range(antal_kast, 0, -1):
resultat = random.randint(1, 6)
terninger.append(resultat)
return resultat
print('before', terninger)
terning_kast() # this is the line which you have missed
print('after', terninger)
There are few points that you need to correct in your logic. Meantime, following is probably that you want.
import random as rnd
def terning_kast(count):
terninger = []
for x in range(count, 0, -1):
resultat = rnd.randint(1, 6)
terninger.append(resultat)
return terninger
if __name__ == "__main__":
cnt = input("Hvor mange terningekast? ")
if cnt.isdigit():
print(terning_kast(int(cnt)))
else:
print("Invalid entry")
In order to use the random module, first you need to import it into your module.
Though you are appending the generated random number to list, you never attempt to return that list. What you are returning is the last instance of result from the randint(x,y) function call.
You are defining your function as part of your module/script. In order to execute that function, you must either call it within module or import it to some other module. If you look at my example the if __name__ == "__main__": instruct the python interpreter to run your script if you were to execute from same module. If you were to consume this module (importing) from some other then you don't need to mentioned this if __name__ == "__main__":

Randomly calling functions to execute

I have made this short questionnaire:
from random import randint
def pancakes():
q = raw_input("Do you like pancakes?")
if q == "yes":
print("Great!")
elif q == "no":
print("Hmmm...")
def french_toast():
q = raw_input("Do you like french toast?")
if q == "yes":
print("Oh!")
elif q == "no":
print("Same here!")
def random():
num = 2
while num > 0:
random = randint(1, 2)
if random == 1:
num = num -1
pancakes()
elif random == 2:
num = num -1
french_toast()
random()
My goal here was to get the questions in a random order. But sometimes the same question will be asked twice since it's randomly chosen.
So how can I make it ask the same question only once?
Instead of a while loop, I'd suggest you use a for loop in conjunction with random.sample. Create a list of functions before-hand to provide to sample:
from random import sample
funcs = [french_toast, pancakes]
for func in sample(funcs, len(funcs)):
func()
this will now loop through all functions randomly selecting a function in each iteration.
Alternatively, you could shuffle the list (performs in-place) with random.shuffle and then iterate through it, that will be faster too (though, speed shouldn't be the biggest concern here):
from random import shuffle
funcs = [french_toast, pancakes]
shuffle(funcs)
for func in funcs:
func()
Put these in a function if so required:
from random import shuffle
# use *funcs for passing arbitrary number of
# functions as positional arguments.
def call_funcs_randomly(funcs):
shuffle(funcs)
for func in funcs:
func()
and call them:
call_funcs_randomly([french_toast, pancakes])
As a comment noted, don't use random as a function name, it has the possibility of masking the module random leading to odd looking errors.
I would use random.sample Link. Just create a list of indices to your questions and sample 2 of them.
EDIT:
additionally, you could use random.shuffle Link:
random.shuffle(questions)
for question in questions:
# process your random question once
how about this for your last question (random is not a good name! you might overwrite the module of the same name [although you are fine the way do do it right now])
def random_questions():
eligible_questions = [pancakes, french_toast]
while eligible_questions:
question = random.choice(eligible_questions)
eligible_questions.remove(question)
question()
put the questions in a list, select one with random.choice, remove it from the list and execute it. stop if the question list is empty. this way every question is selected exactly once.
this is easily extended if you want to add more questions.
on second thought: the shuffle version in Jim Fasarakis-Hilliard's answer is a lot cleaner!

My functions are not running

Working with random functions and doing 3 things with 3 different functions, the first gives me values from 1,10 randomly displayed in a list of 10 integers. The second gives me a list values 1,10 and squares them. Then last but not least the third singles out numbers that can be divided by three. The problem is my program is not running while on eclipse the program has no errors, yet my program terminates without printing anything. Please help me...
import random
def main():
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
if __name__ == '__main__':
main()
You are just calling main() not any of the functions nested inside main(),
Using if __name__ == '__main__': does not magically call all your functions.
If your main function was like:
def main():
squareint_()
div3()
rand10()
then you would be calling the other functions as it is, main does nothing or returns nothing.
As far as your methods go, squares.append(random.randint(0,10))**2 is not valid, you cannot use ** on a list method.
It needs to be inside the paren squares.append(random.randint(0,10)**2)
Also num is a list so you cannot use if num % 3 == 0:
You could use something like:
def div3():
divlist = []
num = range(1,10)
for n in num: # loop over the list elements
if n % 3 == 0:
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
There are two current problems with the code:
You're defining your functions inside main(), which is allowed but it's not very good coding practice. If you do this, then you can only ever use these functions from inside main().
You're not actually calling any of your functions, you're just defining them. They need to be called with rand10(), squareint_() or div3().
Try this bit of code instead, which fixes both issues:
import random
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
def main():
rand10()
squareint_()
div3()
if __name__ == '__main__':
main()
Of course, if your functions are invalid, then they will need to be fixed on their own. This just solves the issue of nothing happening when you execute your code. Now when you run the project in Eclipse, you'll see some errors and be able to fix them properly.

Categories

Resources