Troubleshooting Program in Python. How to link Qs? - python

I am here to ask another question about the code I am working on. I keep getting invalid syntax error. I asked a similar question on another account and someone answered the question and gave me a code. I edited it but i cannot seem to work it out. My project is to make a troubleshooting program for a mobile company. At the moment this is my code:
CODE:
print("Please answer 'yes' or 'no' to all questions. If you write something else instead of yes or no then your solution might not come out correctly.")
solution = "Keep holding the power on button until the screen is on. If it doesn't turn on, contact your phone provider to get a replacement."
solution2 = "Charge your phone fully and switch it on."
solution3 = "Delete some apps, you need a minimum of at least 5 GB of free memory to run the phone correcly.\nYou are probably out of memory."
sol4 = "Take out everything from the phone and put it in a bag of rice for 24-36 hours to let the rice absorb the water."
sol5 = "Reset your phone."
sol6 = "You need a screen replacement. Get it fixed!"
sol7 = "You need to get your buttons replaced!"
sol8 = "Get a screen replacement or contact your phone provider to get a phone replacement."
sol9 = "You need to update your phone software and apps."
sol10 = "You dont need to do anything. Your phone doesnt have any problems."
sol11 = "Please update your phone software."
if input("Did you buy your phone recently? ") == 'yes':
if input("Did your drop your phone? ") == 'yes':
if input("Did it become wet when you dropped it? ") == 'yes':
print(sol4)
else:
print(sol5)
else:
if input("Has your phone ever been to slow?" ) == 'yes':
print(sol5)
else:
if input("Have you got more than 30 apps?? ") == 'yes':
print(solution3)
else:
if input("Is your phone older than two years?") == 'yes':
print(no_warranty)
else:
print(warranty)
else:
print(warranty)
So my question is, how can i complete this code and how can i link questions to more questions?
Thanks!

Invalid Syntax error is because your code is not indented properly.
In python you have to indent the code the right way to make it work since there is no ; in python to end the code line:
e.g for nested code blocks:
{
Block 1
....{
....Block 2
{
....Block 3
}
}
}
Here the 4 dots represent 4 space characters.
for your code you can try like this:
if input("Did you buy your phone recently? ") == 'yes':
if input("Did your drop your phone? ") == 'yes':
if input("Did it become wet when you dropped it? ") == 'yes':
print(sol4)
else:
print(sol5)
....
Always remember, while using python always proprly indent you code otherwise it will throw invalid syntax error.

import time, webbrowser
while True:
print('Hello, welcome to the phone broke hotline. Please follow the questions and only use 1 word answers.')
time.sleep(1.25)#program will stop for 1.25 seconds
print('What phone model do you have?.')
Q1=input().lower() #makes it all lower case
if Q1[0]=='i' or Q1[0]=='s' or Q1[0]=='n' :
if Q1[1]=='p' or Q1[1]=='a' or Q1[1]=='o' :
if Q1[2]=='h' or Q1[2]=='m' or Q1[2]=='k' :
yes='y'
y='yes'
no='n'
n='no'
print('You have chosen ' + '' + Q1+ '' + '')
prob=input('Did your ' + '' + Q1+ '' + ' get wet?\n').lower()
if prob == yes or prob == y:
print("place the phone in a ziplock bag with dry, uncooked rice for a couple of hours and if that doesn't work please contact the nearest phone repair shop")
time.sleep(1)
print()
break
elif prob == no or prob == n:
print('Did your screen crack?')
prob2=input().lower()
if prob2 == yes or prob2 == y:
print ('Go to this link to buy new phone parts.\n https://www.replacebase.co.uk/mobile-phone-parts/')
webbrowser.open('https://www.replacebase.co.uk/mobile-phone-parts/')
time.sleep(1)
print()
break
elif prob2 == no or prob2 == n:
print('Is your ' + '' + Q1+ '' + ' unresponsive?')
prob3a=input().lower()
if prob3a == yes or prob3a == y:
prob3b=input('Is Your ' + '' + Q1+ '' + ' off?\n').lower()
if prob3b == yes or prob3b == y:
print("Turn your " + '' + Q1+ '' + " on and if it wont turn on put it on charge and if that doesn't work contact your nearest phone repair shop")
print()
break
elif prob3b == no or prob3b == n:
print('Go to your nearest phone repair shop')
print()
break
elif prob3a == no or prob3a == n:
print('Has your ' + '' + Q1+ '' + ' overheated')
prob4=input().lower()
if prob4 == yes or prob4 == y:
print('place in a cool area for a couple of hours')
print()
break
elif prob4 == no or prob4 == n:
print('Your ' + '' + Q1+ '' + ' is fine. Thank You for using our services today.')
print()
print(' ...........')
time.sleep(1)
break

Related

How do I stop this from repeating?

I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?

How do I make my code return outside loop? Could someone please fix my code?

I hope you are doing well!
I am making a code for my free time.
I just have a small issue with it.
After you buy a sword in my game, I put "break" so that it brings you to the else statement.
(Just put my code into a console such as replit or pycharm and you will understand)
But when I put my break, it ends my code!
I would want it to instead write everything after this part:
else:
print("\033[1;37;40mYou exit the shop.")
print("After leaving the shop, you head home.")
Here is my code:
import time
def coins_left(player_name, coins):
print(player_name + "\033[1;37;40m, you currently have " + str(coins) + " Coins!")
CharacterHealth = 100
Coins = 1000
Sword = "Diamond" or "Metal" or "Wooden"
Shop = ["Shop"]
print("Hello! Welcome to my game! This is an extremely fun action game! I hope you enjoy!\n")
time.sleep(2)
name = input("Please enter your username.\nUsername: \033[1;32;40m")
response = input("\033[1;37;40mHello, " + name + ". Would you like to enter the shop?(yes/no)\nSelection: \033[1;32;40m")
if (response == "Yes") or (response == "yes"):
while True:
answer = input("\n\033[1;37;40mYou have %s coins. Would you like to buy:\n(a) Diamond sword [Costs 900]\n(b) Metal Sword[500]\n(c) Wooden sword[200]\n(d) Back\nSelection: \033[1; 32; 40 m" % Coins)
if (answer == "A") or (answer == "a"):
Sword = "Diamond"
print(name + ", you have bought a " + str(Sword) + " Sword!")
Coins -= 900
coins_left(name, Coins)
break
elif (answer == "B") or (answer == "b"):
Sword = "Metal"
print(name + ", you have bought a " + str(Sword) + " Sword!")
Coins -= 500
coins_left(name, Coins)
break
elif (answer == "C") or (answer == "c"):
print(name + ", you have bought a " + str(Sword) + " Sword!")
Coins -= 200
coins_left(name, Coins)
break
elif (answer == "D") or (answer == "d"):
print("You exit the shop.\n")
break
else:
print("\033[1;37;40mYou exit the shop.")
print("After leaving the shop, you head home.")
Thank you so much for helping me through this process! I hope you can fix this!
Have a great day!
It looks like you are misunderstanding how if-else statements works. Since your print statements are inside the else statement they will only execute if the user had entered "yes" or "Yes". If you want the print statements to execute only if the user had entered anything else, this would work as expected.
However, if you simply want them to be run whenever they "leave" or don't enter the shop you can simply leave them outside any conditional, or even add a boolean value to make sure that they actually entered the shop beforehand:
shop_entered = False
if (response == "Yes") or (response == "yes"):
shop_entered = True
# do shop things...
if shop_entered:
print("\033[1;37;40mYou exit the shop.")
print("After leaving the shop, you head home.")
When you break your loop you are telling the program to stop the loop and execute the code following the loop; however, since there is no code following the loop, the if branch of the conditional is finished, and python will execute anything following the conditional (in this case anything that follows the else). Since there is no other code, your program exits without any more code being run.
If you add a print statement at then end or your script, something like print("thanks for playing!"), you will see "thanks for playing!" printed to the console after everything else is run.

(Python) ELSE is being executed even when IF has been satisfied?

Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )

'int' object not subscriptable error

while 1 == 1:
import csv
from time import sleep
import sys
bill = 0
with open('list2.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
GTINs = []
products = []
prices = []
for row in readCSV:
GTIN = row[0]
product = str(row[1])
price = float(row[2])
GTINs.append(GTIN)
products.append(product)
prices.append(price)
x = 1
print("Welcome to the GTIN shop!")
while x == 1:
try:
sleep(1)
print("Please input the 8 digit GTIN code")
sleep(0.5)
GTIN0 = GTIN[0]
GTIN1 = GTIN[1]
GTIN2 = GTIN[2]
GTIN3 = GTIN[3]
GTINx = input("--> ")
The error brought up here is that on the lines GTIN0 = GTIN[0] etc, the 'int' object not subscriptable, I can't work out how to fix it, it used to work before.
For reference, here is "list2.txt".
45112454,Milk,1.29
55555555,Bread,0.49
87595376,Milkshake,1.99
The next error comes up here (continuing from last segment):
GTINx = input("--> ")
if GTINx == GTIN0:
product1 = products[0]
price1 = prices[0]
x = 2
elif GTINx == GTIN1:
product1 = products[1]
price1 = prices[1]
x = 2
elif GTINx == GTIN2:
product1 = products[2]
price1 = prices[2]
x = 2
elif GTINx == GTIN3: (this one is just here for if another one is added)
product1 = products[3]
price1 = prices[3]
x = 2
else:
print("Have another go")
except:
print("ERROR - Try Again")
To retrieve milk, the code is 7. For bread the code is 8, and for milkshake, the code is 9. I have no idea where python got these numbers from...
while x == 3:
try:
sleep(1)
print("So you would like", number, product1, "?")
sleep(0.5)
confirmation = input("Please enter \"YES\" or \"NO\": --> ")
if confirmation == ("YES") or ("Yes") or ("yes"):
x = 4
elif confirmation == ("NO") or ("No") or ("no"):
x = 1
else:
sleep(0.5)
print("Have another go")
except:
print("ERROR - Try Again")
So, this was supposed to end that loop, and send them back to the start if they said no (relooped via while 1 == 1:) but, it acts as if they said yes, no matter what was typed.
Next is a similar issue...
while x == 4:
try:
cost = price1 * number
bill = bill + cost
print("The cost is", cost)
sleep(5)
print("Would you like to purchase anything else?")
sleep(0.5)
anythingelse = input("Please enter \"YES\" or \"NO\": --> ")
sleep(1)
if anythingelse == ("YES") or ("Yes") or ("yes"):
x = 1
elif anythingelse == ("NO") or ("No") or ("no"):
x = 5
else:
sleep(0.5)
print("Have another go")
except:
print("ERROR - Try Again")
Again, it answers yes, no matter what is inputted.
Sorry for the spam, thanks for any help that I get.
For your loops if confirmation == ("YES") or ("Yes") or ("yes"):
That's never going to work in Python because you are basically asking if confirmation is equal to "YES" or if ("Yes") or if ("yes") ; and if ("Yes") is true because it's valid and not None or 0 or empty. You want:
if confirmation == ("YES") or confirmation == ("Yes") or confirmation == ("yes"):
There are other ways to do your or checking but I'm just going to correct what you have.
As the comments and other answers has pointed out, a better way of checking "yes" would be:
if confirmation.lower() == "yes"
Just turn the input to lower case and check the value.
As for your first issue. GTIN0 = GTIN[0] do you mean GTIN0 = GTINs[0]. Because GTIN is an int not something "subscriptable" just like what the error is telling you.
As for your second issue with GTIN0 and what not, see if the fix fixes it for you since the GTIN0 and so on, was never set correctly. Edit your question if it's still wrong after the fixes.
Also this line
elif GTINx == GTIN3: (this one is just here for if another one is added)
is not really correct for commenting (I'm guessing your commenting, use a # in front of comment lines)
elif GTINx == GTIN3: #(this one is just here for if another one is added)
In relation with the 'if' comparison issue, I would recommend you to firstly remove the Upper format from the string and then compare. It would be then more idiomatic and also youre problem would be solved:
if anythingelse.lower() == ("yes"):
x = 1
elif anythingelse.lower() == ("no"):
x = 5
else:
sleep(0.5)
print("Have another go")

How to delete used numbers in computer guessing game?

I am trying to create a computer vs computer guessing game and the problem is that the computer will guess the same number twice. I tried the .remove() with a variable but the computer would still guess where the variable was so I would get an error. I reverted the code back to where it worked somewhat.
print 'Get ready for some action!'
time.sleep(1)
firstname = raw_input('Enter in a name for computer 1... ')
time.sleep(1)
secondname = raw_input('Enter in a name for computer 2... ')
time.sleep(1)
howlittle = int(raw_input('Enter in the min... '))
time.sleep(1)
howmuch = int(raw_input('Enter in the max... '))
computernumber = random.randint(howlittle,howmuch)
print firstname + 'choses %s as its lucky number.' %computernumber
time.sleep(1)
print '%s is thinking...'%secondname
time.sleep(1)
firsts=random.randint(howlittle,howmuch)
if firsts == computernumber:
print 'The %s won!'%secondname
guessers = 0
computers=[]
while firsts != computernumber:
guessers += 1
if firsts == computernumber:
print 'The computer won in %s guesses'%guessers
elif firsts > computernumber:
firsts = random.randint(howlittle,firsts)
computers.append(firsts)
elif firsts < computernumber:
firsts = random.randint(firsts, howmuch)
computers.append(firsts)
print secondname + " took %s guesses to guess the number" %guessers
print computers
I am still adding features to it but I just needed to get this problem out of the way first. Thanks!
Add an if condition in your elif such that :
if number_guessed is in computer_guesses_list:
generate a random number again
Maybe the problem is that random.randint(a,b) returns a number x in [a,b], i.e. a <= x <= b.
So in your code, random.randint(howlittle,firsts) its possible for firsts to be returned, change it to random.randint(howlittle,firsts-1)
and random.randint(firsts,howmuch) to random.randint(firsts+1,howmuch)
You should have posted the code that isn't working.

Categories