What function should I use to fix my code? - python

I'm an amateur trying to code a simple troubleshooter in Python but I'm sure what function I need to use to stop this from happening...
enter image description here
What should I do so the code doesnt continue running if the user inputs yes?
TxtFile =open('Answers.txt')
lines=TxtFile.readlines()
import random
def askUser(question):
answer = input(question + "? ").lower()
Split = answer.split()
if any(word in Split for word in KW1):
return False
elif any(word in Split for word in KW2):
return True
else:
print("Please answer yes or no.")
askUser(question)
KW1=["didn't", "no",'nope','na'] #NO
KW2=["did","yes","yeah","ya","oui","si"] #YES
print (lines[0])
print("Nice to meet you, " + input("What is your name? "))
print("Welcome to my troubleshooter")
#This is the menu to make the user experience better
shooter=True
while shooter:
print('\n\n1.Enter troubleshooter\n2.Exit\n\n')
shooter=input('Press enter to continue: ')
if shooter==('2'):
print('Ok bye')
break
words = ('tablet', 'phone', 's7 edge')
while True:
question = input('What type of device do you have?: ').lower()
if any(word in question for word in words):
print("Ok, we can help you")
break
else:
print("Either we dont support your device or your answer is too vague")
if askUser("Have you tried charging your phone"):
print("It needs to personally examined by Apple")
else:
if askUser("Is it unresponsive"):
print (lines[0])
else:
print ("Ok")
if askUser("Are you using IOS 5.1 or lower"):
print (lines[1])
else:
if askUser("Have you tried a hard reboot"):
print (lines[2])
else:
if askUser("Is your device jailbroken"):
print (lines[3])
else:
if askUser("Do you have a iPhone 5 or later"):
print (lines[4])
else:
print(lines[5])
print ('Here is your case number, we have stored this on our system')
print (random.random())
Here is my code for reference.
Edit: Here is the problem
enter image description here
It should just end the code there but it doesnt. I'm not sure how I can fix it

I would recommend moving the following:
if askUser("Are you using IOS 5.1 or lower"):
print (lines[1])
else:
if askUser("Have you tried a hard reboot"):
print (lines[2])
else:
if askUser("Is your device jailbroken"):
print (lines[3])
else:
if askUser("Do you have a iPhone 5 or later"):
print (lines[4])
else:
print(lines[5])
print ('Here is your case number, we have stored this on our system')
print (random.random())
into the else part of:
if askUser("Is it unresponsive"):
Hope this helps.

Related

How do I clear an "if" condition

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.

Python: Skip user input and call later on

I'm fairly new to Python and am currently just learning by making some scripts to use at work. Real simple, just takes user input and stores it in a string to be called later on. The questions are yes/no answers but I wish for the user to have the option to skip and for the question to be asked again at the end, how would I do this?
Currently this is what I've got:
import sys
yes = ('yes', 'y')
no = ('no', 'n')
skip = ('skip', 's')
power = str(raw_input("Does the site have power? (Yes/No): "))
if power.lower() in yes:
pass
elif power.lower() in no:
pass
elif power.lower() in skip:
pass
else:
print ''
print '%s is an invlaid input! Please answer with Yes or No' % power
print ''
exit()
then at the end of the script after all the questions have been asked I have this:
if power.lower() in skip:
power = str(raw_input("Does the site have power? (Yes/No): "))
if power.lower() in yes:
pass
elif power.lower() in no:
pass
else:
print ''
print '%s is an invlaid input! Please answer with Yes or No' % power
print ''
exit()
else:
pass
if power.lower == 'yes':
print 'Site has power'
else:
print 'Site doesnt have power, NFF.'
I understand this is very messy and I'm just looking for guidance/help.
Regards,
Trap.
Since you're rather new to Python I'll give you some tips:
Store all the questions which receive "skip" as a response into a list.
At the end of all your questions, iterate through (hint: "for" loop) all the questions which the user skipped and asked them again.
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
message=("is this correct")
Print=(message)
#store input
answer = input("yes/no:")
if answer == "yes": print("thank you")
if answer == "no": print("hmm, are you sure?")
#store input
answer = input("yes/no:")
if answer == "yes" : print("please call my suppot hotline: +47 476 58 266")
if answer == "no" : print("ok goodbye:)")
if someone had a solution for line 7 when answerd yes skiped to the end desplaing ok `goodbye:) thank you`

Use of continue in python - how to break out of an individual loop?

I have written some code that contains several while loops.
answer = "yes"
while answer == "yes":
name = input("what is your name?")
while len(name) > 0 and name.isalpha():
print("okay")
break
else:
print("error")
continue
job = input("what is your job?")
while job.isalpha():
print("great")
else:
print("not so great")
continue
age = input("how old are you?")
while age.isnumeric():
print('nice')
else:
print("not so nice")
continue
What I want the code to do is check for a valid name entry, and if it is invalid re-ask the user for their name. I want it to do the same thing with their job. Unfortunately, when I use continue after the job statement, instead of just re-asking for their job, it re-asks for their name as well. Does anyone know how to make it only re-ask for the job, and not re-do the whole program? Does anyone know how I could replicate this for multiple while loops I.e. Asking for job, name, age, star sign etc.?
Thank you.
You can use while True because answer never change.
It's useless while for 1 expression and 1 break.
You should put everything on a while True and check:
while True:
name = input("what is your name?")
job = input("what is your job?")
if len(name) > 0 and name.isalpha() and job.isalpha():
print("great")
break
print("error")
I moved the question into a seperate fuction to de-duplicate the code. It will ask again and again as long as the answer is not satisfactory.
def ask(s):
r = ""
while not r or not r.isalpha():
r = input(s)
return r
name = ask("What is your name?")
print("Okay. Your name is {}.".format(name))
job = ask("What is your job?")
print("Great. Your job is {}.".format(job))

Program in Python 2.7

I need help with writing my program in Python 2.7.
My problem is that I am not sure how to start the program again if the user inputs 'yes'. Here is my program:
import random
#Set up the lists for charades and the answers (words)
charadelist = ["Mary's father has 5 daughters: Chacha, Chichi, Cheche, Chocho. What is the name of the 5th daughter?"]
wordlist = ["Mary"]
lencharades = len(charadelist)
lenwords = len(wordlist)
rndnum = random.randrange (0, lenwords)
answer = wordlist[rndnum]
charade = charadelist[rndnum]
print "***Welcome to Charades!***"
print "You are given a charade. Try to guess the answer:"
print '"'+charade+'"'
guess = raw_input('Your answer: ')
if guess == answer:
print "Well done!"
else:
print "Sorry, the correct answer is " + '"'+answer+'"' + '.'
print 'Do you want to play again?'
reply = raw_input('Type `yes` or `no`: ')
if reply == 'yes':
# How do I run the program again??? Please help
if reply == 'no':
print 'Thanks for playing!'
exit
Thanks.
I would recommend running your game inside a function, that way you can call it any time:
import random
def runGame():
#Set up the lists for charades and the answers (words)
charadelist = ["Mary's father has 5 daughters: Chacha, Chichi, Cheche, Chocho. What is the name of the 5th daughter?"]
wordlist = ["Mary"]
lencharades = len(charadelist)
lenwords = len(wordlist)
rndnum = random.randrange (0, lenwords)
answer = wordlist[rndnum]
charade = charadelist[rndnum]
print "***Welcome to Charades!***"
print "You are given a charade. Try to guess the answer:"
print '"'+charade+'"'
guess = raw_input('Your answer: ')
if guess == answer:
print "Well done!"
else:
print "Sorry, the correct answer is " + '"'+answer+'"' + '.'
reply = ""
while reply != 'no':
runGame()
print 'Do you want to play again?'
reply = raw_input('Type `yes` or `no`: ')
if reply == 'no':
print 'Thanks for playing!'
Try this:
import random
#Set up the lists for charades and the answers (words)
charadelist = ["Mary's father has 5 daughters: Chacha, Chichi, Cheche, Chocho. What is the name of the 5th daughter?"]
wordlist = ["Mary"]
lencharades = len(charadelist)
lenwords = len(wordlist)
rndnum = random.randrange (0, lenwords)
answer = wordlist[rndnum]
charade = charadelist[rndnum]
print "***Welcome to Charades!***"
print "You are given a charade. Try to guess the answer:"
rep = "yes"
while rep == "yes":
print '"'+charade+'"'
guess = raw_input('Your answer: ')
if guess == answer:
print "Well done!"
else:
print "Sorry, the correct answer is " + '"'+answer+'"' + '.'
print 'Do you want to play again?'
reply = raw_input('Type `yes` or `no`: ')
if reply == 'yes':
pass
# How do I run the program again??? Please help
if reply == 'no':
print 'Thanks for playing!'
rep = "no"
Maybe you can put your program in a loop.If the input is "no",break out the loop.
while(1):
your code
if reply == "no":
break

How can I restart my python 3 script?

I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .

Categories