Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
Related
I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())
The output of the JSON file has multiple responses like the one seen below
"response_code":1
"scan_date":"2011-07-27 03:44:56"
"permalink":"https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296"
"verbose_msg":"Scan finished, information embedded"
"total":43
"positives":19
The below code will get the value of "positives" in the JSON output and then print it to the file.
# DOES THE HASH EXISTS IN VT DATABASE?
if response == 0:
print(hash + ": UNKNOWN")
file = open(output,"a")
file.write(hash + " 0")
file.write("\n")
file.close()
# DOES THE HASH EXISTS IN VT DATABASE?
elif response == 1:
positives = int(json_response.get("positives"))
if positives >= 3:
print(hash + ": MALICIOUS")
file = open(output,"a")
file.write(hash + " " + str(positives))
file.write("\n")
file.close()
else:
print(hash + ": NOT MALICIOUS")
file = open(output,"a")
file.write(hash + " 0")
file.write("\n")
file.close()
else: print(hash + ": CAN NOT BE SEARCHED")
So the result of the current code will be something like the below
0136b7453cedf600d6f6aab7900901d3 19
I am trying to get the value of "permalink" in the JSON results and print it in the same output file. So the output must look like the below
0136b7453cedf600d6f6aab7900901d3 19 https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296
How do I achieve this?
Thanks
You can read it the same way you read the positive values.
elif response == 1:
positives = int(json_response.get("positives"))
permalink = json_response.get("permalink")
if positives >= 3:`enter code here`
print(hash + ": MALICIOUS" + " | URL:" + permalink)
file = open(output,"a")`enter code here`
file.write(hash + " " + str(positives))
file.write("\n")
file.close()
I am trying to get the below code to run in Python and I keep getting a error at the return n point. Can someone please look at the code and see where I messed up at?
while True:
n = input(prompt)
try:
n = float(n)
if n < n1 or n > n2:
print('Error. Input was out of range')
else:
break
except:
print('Error. Please enter a number')
return n
def main():
average = 0
count = 0
while(True):
name = input("Please enter a student name or '*' to finish: ")
if name == '*':
break
scores = 0
scores += getPosFloat('Please enter a score for ' + name + ': ', 0, 100)
scores += getPosFloat('Please enter another score for ' + name + ': ', 0, 100)
scores += getPosFloat('Please enter another score for ' + name + ': ', 0, 100)
print('The average score for ' + name+ ' is: %.2f' % (scores/3))
#please give the proper argument
average += getPosFloat('Please enter average score for ' + name + ': ', 0, 100)
count += 1
if count!=0:
print("The class average is: ",(average)/count)
main()
You can't return a value outside a function. (I'm assuming that is all the code you have since that is all you provided )
You are missing your function definition. It looks like you should have
def getPosFloat(prompt, n1, n2):
while True:
n = input(prompt)
try:
n = float(n)
if n < n1 or n > n2:
print('Error. Input was out of range')
else:
break
except:
print('Error. Please enter a number')
return n
before your main() There are still other errors, but that will get you started
I am making a quiz which can work with different difficulties and it works fine. The only thing is that its like my code ignores my if statement at the bottom. even when the variable 'w' = 9, which is when i have answered 9 questions, it still doesn't print the statement it just continues looping.
import csv
w = 0
score = 0
global q
with open("Computing.txt", "r") as file:
reader = csv.reader(file)
for row in reader:
dif_c = str(dif) + " "
if dif_c + str(q) + ")" in row[0]:
print (row[0].split(dif_c)[1])
print (row[1])
if dif == 1:
print (row[2])
input10 = input("Answer 'a' or 'b': ")
elif dif == 2:
print(row[2] + "\n" + row[3])
input10 = input("Answer 'a','b' or 'c': ")
elif dif == 3:
print(row[2] + "\n" + row[3] + "\n" + row[4])
input10 = input("Answer 'a','b','c' or 'd': ")
if input10 == row[dif + 2]:
print("Correct")
score = score + 1
w = w + 1
elif input10 != row[dif + 2]:
print("Incorrect")
w = w + 1
if w == 9:
print("Game over")
print("You got", r, "right out of 10")
while True:
quiz()
this is all the quiz function and i defined w and score as 0 within the function which i know wouldnt work but i have no clue how to fix it
Your 'if' condition to check 'w == 9' should be inside the 'for' loop and you need to break out of the 'for' loop based on that condition. Otherwise it will continue to loop.
Currently your 'if' check is outside the 'for' loop.
So it should be changed to something like this:
import csv
w = 0
score = 0
global q
with open("Computing.txt", "r") as file:
reader = csv.reader(file)
for row in reader:
dif_c = str(dif) + " "
if dif_c + str(q) + ")" in row[0]:
print (row[0].split(dif_c)[1])
print (row[1])
if dif == 1:
print (row[2])
input10 = input("Answer 'a' or 'b': ")
elif dif == 2:
print(row[2] + "\n" + row[3])
input10 = input("Answer 'a','b' or 'c': ")
elif dif == 3:
print(row[2] + "\n" + row[3] + "\n" + row[4])
input10 = input("Answer 'a','b','c' or 'd': ")
if input10 == row[dif + 2]:
print("Correct")
score = score + 1
w = w + 1
elif input10 != row[dif + 2]:
print("Incorrect")
w = w + 1
if w == 9:
print("Game over")
print("You got", r, "right out of 10")
break
I was taking a online class for Python and one of the tutorials is to create a battle system for a RPG. I finished the tutorial and felt that there was so much missing. One of the missing features was there is no option to go back to a players action which can lead to an infinite loop. I have coded a large section to include a way to go back by typing '0' and it works except for when there is no quantity for an item when selecting items and when there is no more MP for a spell. What happens in that case is when '0' is selected, the last entry on the array is automatically implemented. So lets say I have no MP and 'cura' is my last spell on the list, if I select '0' cura gets cased regardless. Can anyone tak a look at this small section I have included to see where the error is? I will include the entire code if needed.
while running:
print("====================\n")
print("NAME HP MP")
for player in players:
player.get_stats()
print("")
for enemy in enemies:
enemy.get_enemy_stats()
for player in players:
# check if player won
if defeated_enemies == 3:
print("\n" + bcolors.OKGREEN + "You Win!\n♫♫ Fanfare ♫♫" + bcolors.ENDC)
running = False
break
start = True
while start:
start = False
choice = player.choose_action()
index = choice - 1
if index == 0:
dmg = player.generate_damage()
enemy = player.choose_target(enemies)
enemies[enemy].take_damage(dmg)
print("\n" + player.name.replace(" ", "") + " attacked " + enemies[enemy].name.replace(" ", "") + " for", dmg, "points of damage.")
if enemies[enemy].get_hp() == 0:
print(bcolors.BOLD + bcolors.FAIL + enemies[enemy].name.replace(" ", "") + " HAS FALLEN!" + bcolors.ENDC)
del enemies[enemy]
defeated_enemies += 1
elif index == 1:
check_mp = True
while check_mp:
mag_choice = player.choose_magic()
magic_choice = mag_choice - 1
spell = player.magic[magic_choice]
magic_dmg = spell.generate_damage()
current_mp = player.get_mp()
if spell.cost > current_mp:
print(bcolors.FAIL + "\nNot enough MP. Please choose a different spell. Type 0 to go back." + bcolors.ENDC)
continue
else:
check_mp = False
if magic_choice == -1:
start = True
continue
player.reduce_mp(spell.cost)
if spell.type == "white":
player.heal(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " heals", player.name, "for", str(magic_dmg), "HP." + bcolors.ENDC)
if player.hp > player.maxhp:
player.hp = player.maxhp
elif spell.type == "black":
enemy = player.choose_target(enemies)
enemies[enemy].take_damage(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " deals", str(magic_dmg), "points of damage to " + enemies[enemy].name.replace(" ", "") + bcolors.ENDC)
if enemies[enemy].get_hp() == 0:
print(bcolors.BOLD + bcolors.FAIL + enemies[enemy].name.replace(" ", "") + " HAS FALLEN!" + bcolors.ENDC)
del enemies[enemy]
defeated_enemies += 1
elif index == 2:
choose_item = True
while choose_item:
itm_choice = player.choose_item()
item_choice = itm_choice -1
item = player.items[item_choice]["item"]
if player.items[item_choice]["quantity"] == 0:
print(bcolors.FAIL + "\nThere are no more " + str(item.name) +"s left. Please choose a different item. Type 0 to go back." + bcolors.ENDC)
continue
else:
break
if item_choice == -1:
start = True
continue
player.items[item_choice]["quantity"] -= 1
if item.type == "potion":
player.heal(item.prop)
print(bcolors.OKGREEN + "\n" + item.name + " heals", player.name, "for", str(item.prop), "HP." + bcolors.ENDC)
if player.hp > player.maxhp:
player.hp = player.maxhp
elif item.type == "elixer":
if item.name == "MegaElixer":
print("\n" + player.name.replace(" ", ""), "uses", item.name)
print(bcolors.OKGREEN + "HP and MP fully restored to all party members!" + bcolors.ENDC)
for i in players:
i.hp = i.maxhp
i.mp = i.maxmp
else:
player.hp = player.maxhp
player.mp = player.maxmp
print(player.name.replace(" ", ""), "uses", item.name)
print(bcolors.OKGREEN + player.name.replace(" ", "") + " HP and MP fully restored!" + bcolors.ENDC)
elif item.type == "attack":
enemy = player.choose_target(enemies)
enemies[enemy].take_damage(item.prop)
print(bcolors.FAIL + "\n" + item.name + " deals", str(item.prop), "points of damage to " + enemies[enemy].name.replace(" ", "") + bcolors.ENDC)
if enemies[enemy].get_hp() == 0:
print(bcolors.BOLD + bcolors.FAIL + enemies[enemy].name.replace(" ", "") + " HAS FALLEN!" + bcolors.ENDC)
del enemies[enemy]
defeated_enemies += 1
else:
continue