I'm new to using the main() part in Python3.
Error thrown:
python3 Artificial_snake_anti_venom.py
File "Artificial_snake_anti_venom.py", line 67
def main(): snake_families = get_all_snake_families() all_antivenoms = create_all_antivenoms(snake_families) save_antivenoms_file(all_antivenoms.txt) show_user_message() if __name__ == "__main__":
^
SyntaxError: invalid syntax
Code:
#!/usr/bin/python
# Creating Synthetic Snake Antivenom
import random
# Create a function that can generate antivenom serum from snake venom
def make_antivenom(snake_venom):
# Create a loop that can iterate through the snake venom and be used to create the antivenom
antivenom_serum = []
for element in snake_venom:
# Create a sample of each element in the snake venom
sample = random.sample(element, len(element))
# Append each sample to a serum stored in the list
antivenom_serum.append(sample)
# Return the complete antivenom serum once all samples have been appended
return antivenom_serum
# Call the function
antivenom_serum = make_antivenom()
def make_antivenom():
antivenom_serum = []
# Append polyvalent antivenom
polyvalent_serum = create_polyvalent_antivenom()
antivenom_serum.append(polyvalent_serum)
# Append a range of species specific antivenom
for snake_species in get_all_snake_species():
species_specific_serum = create_species_specific_antivenom(snake_species)
antivenom_serum.append(species_specific_serum)
# Append a range of polyspecific antivenom
for snake_family in get_all_snake_families():
polyspecific_serum = create_polyspecific_antivenom(snake_family)
antivenom_serum.append(polyspecific_serum)
return antivenom_serum
# Create a polyvalent antivenom serum
def create_polyvalent_antivenom():
# code to create polyvalent antivenom
# Create a species specific antivenom serum
def create_species_specific_antivenom(snake_species):
# code to create species specific antivenom
# Create a polyspecific antivenom serum
def create_polyspecific_antivenom(snake_family):
# code to create polyspcecific antivenom
# Get a list of all snake species
def get_all_snake_species():
# code to get all snake species
# Get a list of all snake families
def get_all_snake_families():
# code to get list of all snake families here
pass
# Create dictionary with all antivenoms for snake species
def create_all_antivenoms(): # code to generate antivenoms based on snake families pass # Loop over created antivenoms and save to file
def save_antivenoms_file(): # loop over antivenom dict and save to file
pass
# Display message to user
def show_user_message(): print("All snake antivenoms have been generated!")
# Call main function
def main(): snake_families = get_all_snake_families() all_antivenoms = create_all_antivenoms(snake_families) save_antivenoms_file(all_antivenoms.txt) show_user_message() if __name__ == "__main__":
main()
What I have done so far.
checked for empty spaces.
moved main() to new line.
tried changing all_antivenoms to all antivenoms.txt with and without quotes.
It is in the right directory; has been chmod +x.
All results are the same.
python3 Artificial_snake_anti_venom.py
File "Artificial_snake_anti_venom.py", line 67
def main(): snake_families = get_all_snake_families() all_antivenoms = create_all_antivenoms(snake_families) save_antivenoms_file(all_antivenoms.txt) show_user_message() if __name__ == "__main__":
^
SyntaxError: invalid syntax
Did you intend to have the progressively increasing indentation?
Try first of all having all the def statements aligned to the left.
For example, this:
# Create a polyvalent antivenom serum
def create_polyvalent_antivenom():
# code to create polyvalent antivenom
# Create a species specific antivenom serum
def create_species_specific_antivenom(snake_species):
# code to create species specific antivenom
# Create a polyspecific antivenom serum
def create_polyspecific_antivenom(snake_family):
# code to create polyspcecific antivenom
Did you intend to write this:
def create_polyvalent_antivenom():
pass
def create_species_specific_antivenom(snake_species):
pass
def create_polyspecific_antivenom(snake_family):
pass
There is no need to write a comment describing what a function will do, when it is little more than restating the name of the function. That is what a good function name is aimed at achieving.
Usually we write a pass statement, which does nothing, for any function where we have not yet written the code.
It is conventional not to squash statements onto the end of the line that defines a function
Instead of:
def main(): snake_families = get_all_snake_families() all_antivenoms = create_all_antivenoms(snake_families) save_antivenoms_file(all_antivenoms.txt) show_user_message() if __name__ == "__main__":
main()
Try
def main():
snake_families = get_all_snake_families()
all_antivenoms = create_all_antivenoms(snake_families)
save_antivenoms_file(all_antivenoms.txt)
show_user_message()
if __name__ == "__main__":
main()
Related
Tried Importing Name from File1 to File 2 so it can be used in Char1 creation but error as it state index out of range
Any ideas how can i get the name and roles from file 1 and input it in file 2 ?
Tested with File 1 that the name i input will get saved in the Name List when i tried printing it out but when i shift it over to File 2 its an empty list
File 1:
import pygame
import pygame_menu
import play
import PSB_Game
import random
Roles = [['WARRIOR'], ['TANK']]
Name = []
S_Role = []
def get_name(name):
Name.append(name)
print("my name is", name)
print(Name)
def get_role(role):
S_Role.append(role)
print('role is',role)
print(S_Role)
def main():
pygame.init()
surface = pygame.display.set_mode((800, 550))
menu = pygame_menu.Menu('Welcome', 800, 550, theme=pygame_menu.themes.THEME_BLUE)
menu.add.text_input('Character 1 Name:', onreturn= get_name)
menu.add.dropselect('Role:', Roles, onchange= get_role)
menu.mainloop(surface)
pass
if __name__ == "__main__":
main()
File 2:
import PlayerCreate
def main():
Char1 = warrior(200, 260, PlayerCreate.Name[0], 100, 5, 3, 'Warrior')
Char1_health_bar = HealthBar(100, screen_height - bottom_panel + 40, Char1.hp, Char1.max_hp)
run = True
while run:
clock.tick(fps)
#draw background
draw_bg()
#draw_panel
draw_panel()
Char1_health_bar.draw(Char1.hp)
#draw warrior
Char1.update()
Char1.draw()
#player action
if Char1.alive == True:
if current_Warrior == 1:
action_cooldown += 1
if action_cooldown >= action_wait_time:
#look for player action
# #attack
Char1.attack(Warrior1)
current_Warrior += 1
action_cooldown = 0
wanted to create a turn based battle game with the input for user for the char name and print them out
Problem
The problem occurs because you use the if __name__ guard that prevents the running of an entire script when it is imported. Running the PlayerCreate script on its own will run all the code, but only the unguarded parts of the script get executed when it is imported. Running the second script only will result in the creation of the global variables PlayerCreate.Roles, PlayerCreate.Name and PlayerCreate.S_Role and import the functions from the PlayerCreate script. The PlayerCreate.Name list is empty because that is how you instantiated it.
Solution
Changing the function name main into create in the PlayerCreate script and calling the function inside your main function of file 2 would be the cleanest solution. Otherwise, if you want the entire PlayerCreate script to be ran directly when it is imported, you could remove the if __name__ guard.
I have two modules in pygame. One (game_manager) in charge of creating the game and all the activities you can do there. Another (window_manager) in charge of updating the game window and drawing all the elements.
While refactoring the code to create new game modes I ran into a problem.
I want to pass a variable DECK_PLAYER from game_manager to window_manager:
# IN GAME_MANAGER.py
TABLERO = []
DECK_PLAYER = []
<some code>
def set_tablero(size):
global TABLERO
global DECK_PLAYER
TABLERO = class_board.crear_tablero(size)
DECK_PLAYER = class_cards.create_decks()
def get_deck_player():
global DECK_PLAYER
print("get_deck_player() -> ", DECK_PLAYER)
return DECK_PLAYER
if __name__ == "__main__":
board_size = 3
CLOCK.tick(30)
set_tablero(board_size)
print("get_deck_player() -> ", get_deck_player())
game_init()
both of the prints so far print the correct result, DECK_PLAYER as a list with elements. But if I call
# IN WINDOW_MANAGER.py
deck_p = game_manager.get_deck_player()
print(deck_p)
this print returns an empty list ([]), and I don't understand why. Shouldn't get_deck_player return the current value of the variable?
SOLVED IT:
as I was running game_manager as main, the call from window_manager should be:
import __main__
deck_p = __main__.get_deck_player()
to get the correct value of the variable
I'm pretty sure this has been answered, but I can't seem to locate it.
What I want is a python script for Blender that creates a custom tab that contains a button. When that button is pressed, it prints the value of an integer and increments it, so that when you press the button again, it shows an incremented value. Everything seems to work, except for the incremental part.
Here is the code I am using at the moment:
===
import bpy
from bpy.props import (IntProperty,)
from bpy.types import (Panel, Operator, AddonPreferences, PropertyGroup,)
def main(context):
my_number += 1
print(str(my_number))
class MySettings(PropertyGroup):
my_number = IntProperty(
name="Int property",
description="This is an integer.",
default = 1
)
class AddOne(bpy.types.Operator):
"""This is an operator"""
bl_idname = "op.add_one"
bl_label = "Increment by 1"
def execute(self, context):
main(context)
return {'FINISHED'}
class CreatePanel(bpy.types.Panel):
bl_label = "Render Setup Panel"
bl_idname = "OBJECT_PT_hello"
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'TOOLS'
bl_category = "Increment by 1 Tab"
def draw(self, context):
layout = self.layout
obj = context.object
row = layout.row()
row.operator("op.add_one")
def register():
bpy.utils.register_class(AddOne)
bpy.utils.register_class(MySettings)
bpy.utils.register_class(CreatePanel)
def unregister():
bpy.utils.unregister_class(AddOne)
bpy.utils.unregister_class(MySettings)
bpy.utils.unregister_class(CreatePanel)
if __name__ == "__main__":
register()
===
However, when I press the button 'Increment by 1', I get the following error:
"local variable 'my_number' referenced before assignment"
The point of this exercise is just to create an integer variable, store it, then increment it's value and print it out.
EDIT: I added the actual code, rather than an image of it.
The variable my_number is defined in the class MySettings - it can only be accessed through that class, whether that is inside a method that is also part of the class (self.my_number) or directly as a property that is part of an instance of the class (settings_instance.my_number).
You need to find a place outside of the operator and panel to store persistent variables. Adding a custom property to the object or scene types are common options. As you are showing your panel in the node editor, maybe you will want to add it to the material to keep it specific to a material, instead of global to the scene. You define these properties in the addons register() and remove them in unregister().
def register():
bpy.types.Scene.my_settings = bpy.props.PointerProperty(type=MySettings)
def unregister():
del bpy.types.Scene.my_settings
Then in your operator (or main() function) and your panel you can access the variable through the context paramater.
context.scene.my_settings.my_number += 1
Putting that together into your example, with a label to show the value -
import bpy
from bpy.props import (IntProperty,)
from bpy.types import (Panel, Operator, AddonPreferences, PropertyGroup,)
def main(context):
context.scene.my_settings.my_number += 1
print(str(context.scene.my_settings.my_number))
class MySettings(PropertyGroup):
my_number: IntProperty(
name="Int property",
description="This is an integer.",
default = 1
)
class AddOne(Operator):
"""This is an operator"""
bl_idname = "op.add_one"
bl_label = "Increment by 1"
def execute(self, context):
main(context)
return {'FINISHED'}
class CreatePanel(Panel):
bl_label = "Render Setup Panel"
bl_idname = "OBJECT_PT_hello"
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'UI'
bl_category = "Increment by 1 Tab"
def draw(self, context):
layout = self.layout
obj = context.object
row = layout.row()
row.operator("op.add_one")
row = layout.row()
row.label(text='Value is: '+str(context.scene.my_settings.my_number))
def register():
bpy.utils.register_class(AddOne)
bpy.utils.register_class(MySettings)
bpy.utils.register_class(CreatePanel)
bpy.types.Scene.my_settings = bpy.props.PointerProperty(type=MySettings)
def unregister():
bpy.utils.unregister_class(AddOne)
bpy.utils.unregister_class(MySettings)
bpy.utils.unregister_class(CreatePanel)
del bpy.types.Scene.my_settings
if __name__ == "__main__":
register()
You will find blender.stackexchange a better place to ask for blender specific python help.
Generally this problem "local variable 'my_number' referenced before assignment" comes when you have 'my_number' variable in code and you had not initialized that variable at top of your code or before using that variable do one thing .
Declare my_number=0 and then do your calculation on my_number variable .
I am trying to instantiate more then one object in a single class. I am trying to instantiate them in the class instead of the main function. I am new to python, so trying to learn. Example, I have this piece of code, my input file is a text file with all strings. I want to instantiate the object when my regex in region is true and/or sub-region is true. I want to instantiate them there and NOT in the main function. How can I do that? since every time I run my code I can have zero or one or two objects:
class Tracker(object):
def __init__(self):
self.region = ""
self.subregion = ""
def updateRegion(self,input):
if self.endingRegion:
self.region = ""
if self.endingSubRegion:
self.subregion = ""
#Regions
temp = re.search(r'CLI Command: \'(.*)\'', input)
if temp:
self.region = temp.group(1)
print self.region
#SubRegions
temp = re.search(r'Equipped Type \(if different\)',input)
if temp:
self.subregion = "Equipped Type"
print self.subregion
def main():
with open ('/home/thamer/TS_ncren202_XRS-20_20150624_12.0.R6.txt','r') as f:
tracker = Tracker()
for line in f:
tracker.updateRegion(line)
region = tracker.getRegion()
subregion = tracker.getSubRegion()
if __name__ == '__main__':
main()
I am trying to write the program battleship. I have two gameboard matrices: one for player, one for computer. These are defined outside of main because I want them to be global variables because several functions manipulate/read them. I am using Python 2.6.1.
#create player game board (10x10 matrix filled with zeros)
playerBoard = [[0]*10 for i in range(10)]
#create computer game board (10x10 matrix filled with zeros)
computerBoard = [[0]*10 for i in range(10)]
Then I define the main function.
#define main function
def main():
global playerBoard
global computerBoard
#keepGoing is true
keepGoing = True
#while keepGoing is true
while keepGoing:
#call main menu function. Set to response.
response = mainMenu()
#if response is 1
if response == "1":
#begin new game
#call clearBoards function
clearBoards()
#call resetCounters function
resetCounters()
#call placeShips function (player)
playerBoard = placeShips(playerBoard, "player")
#call placeShips function (computer)
computerBoard = placeShips(computerBoard, "computer")
#call guessCycler function
guessCycler()
#if response is 2
if response == "2":
#keepGoing is false
keepGoing = False
Despite my declaration of global playerboard and global computerBoard within main PyScripter still says those are local variables. I don't understand this. How can I make sure they are global?
Documents I have already looked at:
Using global variables in a function other than the one that created them
Changing global variables within a function
http://www.python-course.eu/global_vs_local_variables.php
I definitely think you should reconsider if you need them to be global - You don't .-)
The cheap way, is do declare your stuff and the pass them on as parameters to the function
def MyFunc(board1):
print board1
board1 = "Very weak horse"
MyFunc(board1)
The real way to do it is to create a class and then access them using self
class MySuperClass():
def __init__(self):
self.horse = "No way up"
def myRealCoolFunc(self):
print self.horse
uhhh = MySuperClass()
uhhh.myRealCoolFunc()