简体   繁体   中英

Python while loop, print one item from array without it being printed twice in a row

I want pyautogui to type days in a month from 1 to 31. Bellow each number I want it to type city name from an array. Problem is that when loop finishes, in the next run it has a chance to print the same city which I don't want. It can and should print it again just not twice in a row.

I tried several options I was able to Google but none worked. Here's my code. If you have suggestions on how to fix it or completely new code please let me know.

import pyautogui, random

dayDate = 1
while dayDate < 32:
    pyautogui.click(380, 325)
    pyautogui.typewrite(str(dayDate))
    pyautogui.click(380, 345)
    cities = ['London', 'Paris', 'Berlin', 'Barcelona', 'Moscow']
    city = random.choice(cities)
    print(city)
    pyautogui.typewrite(str(city))
    dayDate += 1

Just that I'm clear, preferable output in terminal should not have same city twice in a row.

Eg:

  1. London 2. Berlin 3. Berlin 4. Moscow - wrong

  2. Berlin 2. London 3. Berlin 4. Moscow - correct

Change your code to be like this:

import pyautogui, random

cities = ('London', 'Paris', 'Berlin', 'Barcelona', 'Moscow')
last_city = city = random.choice(cities)

for day in range(1, 32):
    pyautogui.click(380, 325)
    pyautogui.typewrite(str(day))
    pyautogui.click(380, 345)
    pyautogui.typewrite(city)
    print(day, city)
    while city == last_city:
        city = random.choice(cities)
    last_city = city 

Something you could do is store the previous city as a variable. Then, have a while loop where you do a random choice of cities while the city chosen equals the previous city chosen.

import pyautogui, random

dayDate = 1
prevCity = ''
while dayDate < 32:
    pyautogui.click(380, 325)
    pyautogui.typewrite(str(dayDate))
    pyautogui.click(380, 345)
    cities = ['London', 'Paris', 'Berlin', 'Barcelona', 'Moscow']
    city = random.choice(cities)
    while prevCity == city:
        city = random.choice(cities)
    prevCity = city
    print(city)
    pyautogui.typewrite(str(city))
    dayDate += 1

Not totally sure I understood the problem. Maybe the solution is just remember last printed city and choose a different one?

import pyautogui, random

cities = ['London', 'Paris', 'Berlin', 'Barcelona', 'Moscow']
dayDate = 1
city = prev_city = ""
while dayDate < 32:
    pyautogui.click(380, 325)
    pyautogui.typewrite(str(dayDate))
    pyautogui.click(380, 345)
    while city == prev_city:
        city = random.choice(cities)
    prev_city = city
    print(city)
    pyautogui.typewrite(str(city))
    dayDate += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM