Currently I'm making a project and I want to add a function to it. But I have no clue about the problem I encountered recently. So, here's the wrong code of the function I wrote:
user_input = input()
while True:
if user_input == "add_1":
print("Start adding your #1 note...")
content_1 = input("Please enter content: ")
elif content_1 != '':
print("You have added the #1 note. Please use other functions.")
user_input = input()
if user_input == "add_2":
print("Start adding your #2 note...")
content_2 = input("Please enter content: ")
elif content_2 != '':
print("You have added the #2 note. Please use other functions.")
user_input = input()
if user_input == "add_3":
print("Start adding your #3 note...")
content_3 = input("Please enter content: ")
elif content_3 != '':
print("You have added the #3 note. Please use other functions.")
user_input = input()
The expected result:
When the user input the string 'add_1',
the system will process:
Start adding your #1 note...
(Next line) Please enter content: (e.g. Write something here)
Then, the content the user input will be stored into the variable 'content_1'.
Next, after the variable 'content_1' is NOT EMPTY, when the user input the string 'add_1', the system will print the message, 'You have added the #1 note. Please use other functions.'
The system will do the similar function according to the other input 'add_2' and 'add_3'.
The situation now is that I can't think of a solution to write a suitable code for the function. Can some programming masters help me with this problem? Thanks a lot.
The code is messy and hard to read, I would suggest sketching out a diagram of how the logic should work out before even opening the computer and writing your first line of code.
The problem lies within the nested if/elif statements. For each option ("add_1", "add_2", "add_3") there should be a while loop which should run for as long as the content_1 is not empty. After the inner loop finishes, the outer loop restarts.
The code should look something like this. Other options should work the same way.
while True:
# take user input at the start of the loop
user_input = input()
# option 1
if user_input == "add_1":
print("Start adding your #1 note...")
content_1 = input("Please enter content: ")
# while content_1 is '', ask again
while content_1 == '':
print("Start adding your #1 note...")
content_1 = input("Please enter content: ")
print("You have added the #1 note. Please use other functions.")
# similarly for other options
elif user_input == "add_2":
# ...
Further reading:
In some cases the newly added walrus operator (:=) can be useful when checking user input.For more information visit this tutorial
content_1 is not defined till here if you meant user_input change content_1 to >user_input:
elif content_1 != '':
print("You have added the #1 note. Please use other functions.")
user_input = input()
you have similar multiple mistakes
if/elif statement must have else statement at last:
if (CONDITION):
STATEMENTS
elif (CONDITION):
STATEMENTS
else:
STATEMENTS
I'm not sure exactly what you want to do but let's try to find a solution
while True:
user_input = input('What function do you want to use: ')
if user_input == "add_1":
print("Start adding your #1 note…")
content_1 = input("Please enter content: ")
if content_1 != '':
print("You have added the #1 note. Please use other functions.")
elif user_input == "add_2":
print("Start adding your #2 note…")
content_2 = input("Please enter content: ")
if content_2 != '':
print("You have added the #2 note. Please use other functions.")
elif user_input == "add_3":
print("Start adding your #3 note…")
content_3 = input("Please enter content: ")
if content_3 != '':
print("You have added the #3 note. Please use other functions.")
But we could simplify this solution:
content = {}
while True:
user_input = input('What function do you want to use: ')
if user_input.startswith("add_") and len(user_input) == 5:
note_number = user_input[4]
if note_number in ('1', '2', '3'):
print(f"Start adding your #{note_number} note…")
content[note_number] = input("Please enter content: ")
if content[note_number]:
print(f"You have added the #{note_number} note. Please use other functions.")
Is that you wanted to do?
Related
I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.
I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
again = str(input("Again? (Y or N) "))
again = again.upper()
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
EDIT:
So I have made some progress but I have one last problem
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
while True:
again = input("again? (Y or N)")
if again not in "yYnN":
continue
break
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?
You could create another loop (inside this main loop) where you are asking for input, and have a try block there, so that it loops just the section where the user is giving input until they give correct input.
This is my first small python task when i found out about speedtest-cli.
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 2:
print(st.upload())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
i am just a beginner so i could't find any way to shorten this code. Any tips would be helpful :)
If you don't care about execution time but only about code length:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
st.get_servers([])
tst_results = [st.download(), st.upload(), st.results.ping]
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option >= 1 and option <= 3:
print(tst_results[option-1])
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
Did not really make it smarter, just shorter by creating a list and take option as index in the list
First, you can look at this line:
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
this line happens on each of the options, so we don't need to repeat it. instead you can add it at the end of the "while" clause. also add "continue" to your "else" clause to avoid asking this when wrong input is entered.
also, the "else" clause for the "while" loop is not needed
e.g:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice")
continue
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
print("Test is ended")
second, there is an error in your logic. your prompt says enter 1 to continue or 2 to quit, and indeed when you enter 2 the loop will end, but also when the user enters 3 or any other number. Even worse, if a user will enter a character that is not a number or nothing at all, they will get an exception. For this we use try-except clauses. another way to do this kind of loop is using "while "True" and then using "break" to exit.
while True:
... your code here ...
q = input("enter 1 or 2:")
try:
q = int(q)
except ValueError:
print("Invalid input")
if q == 2:
break
print("Test is ended")
This is helpful to you if:
you are a pentester
or you (for some other arbitrary reason) are looking for a way to have a very small python script
Disclaimer: I do not recommend this, just saying it may be helpful.
Steps
Replace all \n (newlines) by \\n
Replace two (or four) spaces (depending on your preferences) by \\t
Put """ (pythons long quotation marks) around it
Put that oneline string into the exec() function (not recommended, but do it if you want to)
Applied to this questions code
exec("""import speedtest\n\nq = 1\nwhile q == 1:\n\t\tst = speedtest.Speedtest()\n\t\toption = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))\n\t\tif\toption == 1:\n\t\t\t\tprint(st.download())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 2:\n\t\t\t\tprint(st.upload())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 3:\n\t\t\t\tservernames =[]\n\t\t\t\tst.get_servers(servernames)\n\t\t\t\tprint(st.results.ping)\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telse:\n\t\t\t\tprint("Please enter the correct choice")\nelse:\n\t\tprint("Test is ended")\n""")
I have found the solution to that by using the sys module. i suppose this could work if a wrong data is input.
import speedtest
import sys
#Loop for options
while True:
st = speedtest.Speedtest()
option = input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: ")
#To check if the input value is an integer
try:
option = int(option)
except ValueError:
print("Invalid input")
continue
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice: ")
continue
q = 0
#Choice to continue or to end
while (q != 1) or (q != 2):
q = input("Enter '1' if you want to continue or Enter '2' if you want to stop the test: ")
try:
q = int(q)
except ValueError:
print("Invalid input")
continue
if q == 1:
break
elif q == 2:
sys.exit("Test is ended")
else:
print("Invalid input")
continue
Doing an assignment, this is my first program so bear with me. I cant get the while loop to end although i have broke it. I need a way to get out of the loop, and what I'm doing isn't working. Any suggestions would be very helpful thank you.
def main(): #Calls the main function
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
The problem with your code is your indentation. You have told the program to break when the marker_name is an empty string. I am assuming that you would like the code to finish when all three values are correct, so as such the following code should work for you:
def main():
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
main()
I am a little confused why you have used a try and except? What is the purpose of it?
May I ask why the code block is wrapped in the try-except?
Some suggestions:
remove the try-except as you shouldn't be raising any errors
remove the break statement (after marker_name) as the loop should end when the input is valid
ensure the indentation of all the input while-loop code blocks are identical (your formatting is messed up so I'm not sure if you have nested while loops)
Let me know how this works
Well first of all you break out of a while loop in python with break as you did already. You should only break if a condition you set is met in the loop. So lets say you wanted to break in a while loop that counts and you want to break if the number reaches 100, however, you already had a condition for your while loop. You would then put this inside your while loop.
if x == 100:
break
As you have it now you just break in your while loop after a couple lines of code without a condition. You will only go through the loop once and then break every single time. It defeats the purpose of a while loop.
What exactly are you trying to do in this code? Can you give more detail in your question besides that you would like to break in a while loop? Maybe I can help you more than giving you this generic answer about breaking in a loop.
I'm learning a bit of Python in my spare time. Trying to make a phonebook, found one on this site; Python assignment for a phonebook. Have used that as a template but left out the print_menu function. That's the only difference that I can see but when I add a number it gets stuck in that part. Just asking to enter name and number, not escaping the if loop. If anyone can tell me why I get stuck like this I would appreciate it.
phoneBook = {}
def main():
action = input("What would you like to do? \n 1. Add \n 2. Delete \n 3. Print \n 4. Quit \n")
while action != 4:
if action == '1':
name = input("Enter name: ")
num = input("Enter number: ")
phoneBook[name] = num
elif action == '2':
name = input("Delete who?")
if name in phoneBook:
del phoneBook[name]
else:
print("Name not found")
elif action == '3':
print("Telephone numbers: ")
for x in phoneBook.keys():
print("Name: ", x, "\tNumber: ", phoneBook[x])
elif action == '4':
print("Application closed.")
main()
You have two problems here. As Padraic and Leistungsabfall mention, input returns a string, but you also are only getting the input one time. If you want to continue getting input, you're going to need to put that inside your loop:
action = None
while action != '4':
action = input('What action would you like? ')
# the rest of your code here
input() returns a string, not an integer.
So
while action != 4:
should become:
while action != '4':