Syntax Error in function - python

I'm trying to call my function overwatch. It should print out bastion and lucio.
My code looks right to me. However I'm getting a couple errors and I don't know why I'm getting an error.
def overwatch(hero1, hero2):
print("hello " + hero1 "and " hero2)
overwatch(bastion, lucio)

You missed two + signs and quotes around your string literals.
def overwatch(hero1, hero2):
print("hello " + hero1 + " and " + hero2)
overwatch('bastion', 'lucio')

First of all you want bastion and lucio as a string variable, so you need to use overwatch('bastion','lucio'). Furthermore in your print statement you need to add a plus-sign:
print("hello " + hero1 "and "+ hero2)

The Error, you are seeing is:
print("hello " + hero1 "and " hero2)
^
SyntaxError: invalid syntax
and the solution is easy:
you should edit your code:
1) print("hello " + hero1 + "and " + hero2)
2) overwatch("bastion", "lucio")

Related

Python notification

Is there a way for me to bring what is inside of 'a' into the message?
a = print("You have shown",top1.value,"and",top2.value)
notification.notify(title="Facial Expression" , message =" ", app_icon=None, timeout=3,)
The print() method does not return a value.
a = "You have shown " + top1.value + " and " + top2.value
print(a)
notification.notify(title="Facial Expression", message=a, app_icon=None, timeout=3,)

How to fix this AttributeError

I am trying to access a variable within a function in a class and print it. Whenever I try I keep getting the error: AttributeError: 'NoneType' object has no attribute 'job_ID'.
def driver():
q = my_queue.Queue_()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
print("The prority of the job is: " + q.new_item.job_priority)
print("The job type is: " + q.new_item.job_type)
if 'respond' in line:
q.dequeue()
print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
if 'active' in line:
q.active_jobs()
print("Total number of jobs: " + str(len(q.temp)))
print("Average priority: " + str(q.average))
if 'modify' in line:
q.modify(line)
print("Modified job " + q.current.job_ID)
The error is coming from the last print statement in this code.
This is the function within the class that is being used here:
def modify(self, x): # need to fix printing bug
self.current = self.head
while self.current != None:
if x[1] in self.current.get_data():
self.current.data[2] = x[2]
self.current.data[3] = x[3]
break
# print("Modified job " + current.job_ID)
else:
# print('The job details cannot be modified.')
pass
self.current = self.current.get_next()
The exit condition for the loop in the modify function that you have provided is self.current == None.
When you call modify() in this last conditional statement:
if 'modify' in line:
q.modify(line) // here
print("Modified job " + q.current.job_ID)
You are making q.current evaluate to None. Therefore, the reason why you are getting an AttributeError is because q.current is None, which has no such attribute called job_ID.
To fix your problem, you must ensure that q.current is not None before printing q.current.job_ID. I can't give you any help beyond this, since I don't know what the purpose of your program is.

Python: Limit number of process calls by os.system

I need to run programs parallel, 3 at a time. I tried the following but when programC finished before A and B, it does not work. How can I limit the number of running programs to, say, at most 3 at any time.
for i in range(10):
os.system("xterm -e program " + i + "a" + " &")
os.system("xterm -e program " + i + "b" + " &")
os.system("xterm -e program " + i + "c" + " ")
Here my solution, though I will select a better answer:
for i in range(10):
a = subprocess.Popen(["xterm -e program"+ i + " a" ],shell=True)
b = subprocess.Popen(["xterm","-e","program",i," b"])
c = subprocess.Popen(["xterm","-e","program",i," c"])
a.wait()
b.wait()
c.wait()

Python 3.1.1 - Assign random values to a function

I need a way to assign random values to a function, call the function and print the value to the screen.
When I run the code as it is, the enemy's attack and user's defense does not get recalculated. What can I do to have Python recalculate these variables every time the function is called?
import random
enemyName = "Crimson Dragon"
def dragonAtk():
return random.randint(5,10)
def userDef():
return random.randrange(8)
userHp = 100
userName = input("What is your name? ")
enemyAttackname = "Fire Blast"
def enemyAttacks():
global battleDmg
global userHp
global enemyAtk
global userDef
enemyAtk = dragonAtk()
userDef = userDef()
print (">>> " + enemyName + " attacks " + userName + " with " + enemyAttackname + "!")
if enemyAtk < userDef:
print (">>> " + userName + " successfully defended the enemy's attack!")
elif enemyAtk == userDef:
print (">>> " + userName + " successfully parried the enemy's attack!")
else:
battleDmg = enemyAtk - userDef
userHp -= battleDmg
print (">>> " + userName + " takes " + str(battleDmg) + " DMG! "\
+ userName + " has " + str(userHp) + " HP remaining!")
enemyAttacks()
input()
enemyAttacks()
input()
This is my result
What is your name? Murk
>>> Crimson Dragon attacks Murk with Fire Blast!
>>> Murk takes 6 DMG! Murk has 94 HP remaining!
Traceback (most recent call last):
File "C:\Users\Junior\Desktop\python projects\test", line 37, in <module>
enemyAttacks()
File "C:\Users\Junior\Desktop\python projects\test", line 22, in enemyAttacks
userDef = userDef()
TypeError: 'int' object is not callable
>>>
So, I see it ran once through enemyAttacks(), but the second time gave me an error. Not sure what to make of it. Any thoughts?
Here:
userDef = userDef()
You have overridden your function. Thus, when you call the function again, you are trying to call the function, but you have an integer instead (hence the error).
Rename your variable to another name so you don't override your function.

Python code formatting

In response to another question of mine, someone suggested that I avoid long lines in the code and to use PEP-8 rules when writing Python code. One of the PEP-8 rules suggested avoiding lines which are longer than 80 characters. I changed a lot of my code to comply with this requirement without any problems. However, changing the following line in the manner shown below breaks the code. Any ideas why? Does it have to do with the fact that what follows return command has to be in a single line?
The line longer that 80 characters:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
The line changed by using Enter key and Spaces as necessary:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg +
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
A multiline string would be more readable:
def __str__(self):
return '''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)
To maintain visually meaningful indentation levels, use textwrap.dedent:
import textwrap
def __str__(self):
return textwrap.dedent('''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price))
You can solve the problem by putting the expression in parenthesis:
def __str__(self):
return ("Car Type \n"+"mpg: %.1f \n" % self.mpg +
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price))
However, I'd consider writing it more like this: (code untested)
def __str__(self):
return """\
Car Type
mpg: %(mpg).1f
hp: %(hp).2f
pc: %(pc)i
unit cost: $%(cost).2f
price: $%(price).2f """ % self.__dict__
Python doesn't let you end a line inside an expression like that; the simplest workaround is to end the line with a backslash.
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg + \
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + \
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
In this case, the backslash must be the last character on the line. Essentially, it means "ignore the fact that there's a newline here". Or in other words, you're escaping the newline, since it would normally be a significant break.
You can escape an otherwise significant newline at any time with a backslash. It would be silly, but you could even do
def foo():
return \
1
so that foo() would return 1. If you didn't have the backslash there, the 1 by itself would cause a syntax error.
It require a little extra setup, but a data-driven approach (with a good dose of vertical alignment) is easy to grok and modify as a project evolves. And it indirectly eliminates the problem of long lines of code.
def __str__(self):
dd = (
("Car Type %s", ''),
(" mpg: %.1f", self.mpg),
(" hp: %.2f", self.hp),
(" pc: %i", self.pc),
(" unit cost: $%.2f", self.cost),
(" price: $%.2f", self.price),
)
fmt = ''.join("%s\n" % t[0] for t in dd)
return fmt % tuple(t[1] for t in dd)

Categories