import random,time,os
def add():
os.system("clear")
idea = input("input your idea ")
f = open("my.ideas", "a+")
f.write(f"{idea}\n ")
f.close()
time.sleep(1)
os.system("clear")
def show():
os.system("clear")
f = open("my.ideas", "r")
ideas = f.read().split("\n")
f.close()
ideas.remove("")
idea = random.choice(ideas)
print(idea)
time.sleep(1)
os.system("clear")
while True:
menu = input("1: Add idea\n2: Show a random idea\n> ")
if menu == "1":
add()
else:
show()
The first line, import random, time, os
, imports the required modules for the program, random
, time
, and os
.
Then, the def add():
part creates a function called add
. It is indented to show that it is a function.
The os.system("clear")
line clears the screen.
The idea = input("input your idea")
line gets user input and puts it into a variable called idea
.
Next the f = open("my.ideas", "a+")
opens a file called my.ideas
with appending permissions.
f.write(f"{idea}\n ")
writes the user-inputted idea
variable to the file and then a newline escape sequence.
f.close()
closes the file.
time.sleep(1)
delays program execution for 1 second.
Then, again, os.system("clear")
clears the screen.
After that, another function is created called show
, which starts by clearing the screen.
Then, again, the my.ideas
file is reopened with reading permissions this time.
The ideas = f.read().split("\n")
puts the ideas into an array, first reading the my.ideas
file, then getting each line of it.
ideas.remove("")
removes all empty ideas from the array.
idea = random.choice(ideas)
gets a random idea from the array.
Then, the idea is printed using print(idea)
.
The time.sleep(1)
, again, delays program execution for a second.
The screen is cleared again using os.system("clear")
.
Next, there is a while loop. A while True:
loop means that the loop will never be stopped unless it is stopped using a break
statement or the program is manually stopped.
Next, menu = input("1: Add idea\n2: Show a random idea\n> ")
prompts the user for input:
If the user answered 1
(add idea) then the add()
function is called.
Otherwise, the show()
function is called (to show a random idea).
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.