#keyword: init python
Explore tagged Tumblr posts
Note
Hey!! Thanks for your time. So I was wondering how I would write the code for something where I want the chances of success to be based on a percentage. I'm trying to implement lottery tickets, and I need it to have a 0.09% chance of success. And also, how would I make it so you get a different response for each outcome? Like if you failed to get one, I want your buddy to say "aw that's too bad, maybe next time!" And if not I want everyone to freak out, plus the earnings to be added. Thank you!!
I return from the void now that everyone is migrating back from the land of the South African Muskrat! Yours is a rather involved answer to see all of it below the cut
The answer to your question, at least the percentage part, is a matter of the randint() function in the Python library. In this case, you want something to happen only 1 in so many times. For example, 1 in 10 is a 10% chance. To simulate this in code, you can have the interpreter pick a random(note this isn’t true randomness, but it’s good enough for a video game we aren’t making a cyber security system!) number between 1 and 10. If it comes out to one number and one number only, then you pass the check. This makes it a 10% chance, just like if you rolled a 10 sided die.
For your .09% chance(very rare!), it would be 1 in ~1,100 chance.(.090909...%). So if you have Python pick a number between 1 and 1,100 and check to see if it’s one specific number, then you’ll have your lottery win.
The easiest way to implement this in game is to record the results of the 1 in 1,100 chance inside a function wrapper so that you can call it multiple times and they can check lots of tickets.
init python: def Lottery_Ticket(): ticket_num = renpy.random.randint(1, 1100) return ticket_num
In order to use the randint() function from the random library, you just need to invoke it! It’s a part of Renpy’s library. So you’d type renpy.random.randint(1,1100) like above. :)
Once that is done in your game code itself you’ll put the logic for the winning number. Let’s say it’s 42, for meme reasons.
You could write in your game file:
label check_ticket: $ ticket = Lottery_Ticket() if ticket == 42: jump you_win else: jump you_lose
This simple logic sets the ticket equal to the result of the Lottery_Ticket function. It then checks if the number is exactly the winning number you chose. If so, it takes you to the winning section of your game code, if not, it falls through and says you lose.
Every time they buy a ticket, you can send them to this label, it will re-run the Lottery_Ticket function anew, picking a new random number, and see if they won.
Under your winning code, since you asked, this is where you’d put your characters reacting positively! Note the thing in brackets is the player character’s name as a variable being interpolated by the engine. If you let the player pick their own name, that’s how you’d get it into the script. If they have a set name, just type that instead.
label you_win: e “Oh my God! [PC_Name] you did it! e “It’s like a dream come true!” $ Inv.add(lottery_winnings) $ renpy.notify(”You added“ + str(lottery_winnings) + “ to your wallet!”)
As you see, I’m using to functions. One that comes with Ren’Py calls in the notify screen context through the function. It needs to be a string inside which is why I’ve turned the int representing the lottery winnings into a string here.(This assumes you have a variable called “lottery_winnings” that has a specific integer value! Please initialize one before the start of your game!) (example: $ lottery_winnings = 10000)
The second is me assuming that you have an Inventory class instance with a method called “add” that can add money into a wallet variable. To make something like that:
init python: class Inventory(python_object): def__init__(self, wallet = 0): self.wallet = wallet self.pocket = [] def add(num): self.wallet += num return self.wallet
Then you just need an instance of it:$ Inv = Inventory() (I wrote it with defaults, so you don’t need to pass any arguments to the instance when you make it, though you are welcome to pass an INTEGER to it when you instantiate it so that your character starts with a certain amount of money. :D )
Then you can call the method on the variable to add the earnings to their wallet. :)
There’s also an empty pockets list inside of the inventory you can use to store the string names of objects they also own. For something like that:
$ Inv.pocket.append(”apple”)
This will add a string called “apple” to the pocket list inside the inventory. Which you can use to check if they “own” an object by checking if it is in the list.
if ‘apple’ in Inv.pocket: .......
But that’s more detail for another time.
You need to put the class in an init python block before the game starts so that you can make an instance of it to manipulate later.
For not winning, just have the ‘you_lose’ label have the dialogue you wanted.
label you_lose: e “Aw, that’s too bad. Maybe next time!”
And then continue on with the rest of the game.
I hope everything here is clear and this helps. I know this ask came in ages ago, but I still think answering it will help Ren’Py users in the now. Remember: If your code won’t compile, and you don’t what to do; who you gonna call? The Ren’Py Help Desk!
#RenPy#Ren'Py#thehelpdesk#Renpyhelpdesk#keyword: python#keyword: init python#Python#Python Classes#Inventory Code#function: renpy.notify()#function: renpy.random.randint()#keyword: jump#keyword: label
14 notes
·
View notes
Text
python syntax cheat sheet working 0T0&
💾 ►►► DOWNLOAD FILE 🔥🔥🔥🔥🔥 int() → 15 truncate decimal part float("e8") → round(,1)→ rounding to 1 decimal (0 decimal → integer number). It's easy to learn and fun, and its syntax is simple yet elegant. Python is a popular choice for beginners, yet still powerful enough to to back some of the. Python CheatSheet. Basic syntax from the python programming language. Showing Output To User. The print function is used to display or print output. Basic rules to write Python syntax: Rule #1: Python is white-space dependent; code blocks are indented using spaces. Rule #2: Python language. 9 Work fast with our official CLI. Learn more. If nothing happens, download GitHub Desktop and try again. If nothing happens, download Xcode and try again. There was a problem preparing your codespace, please try again. Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance and issubclass as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments. Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary. If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'. Decorator that prints function's name every time the function is called. Decorator that caches function's return values. All function's arguments must be hashable. A decorator that accepts arguments and returns a normal decorator that accepts a function. MRO determines the order in which parent classes are traversed when searching for a method or an attribute:. Decorator that automatically generates init , repr and eq special methods. Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint. A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type. Unlike listdir , scandir returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it. A server-less database engine that stores each database into a separate file. Values are not actually saved in this example because 'conn. Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray. List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Sizes and byte order are always determined by the system. A thread-safe list with efficient appends and pops from either side. Pronounced "deck". Type is the root class. If only passed an object it returns its type class. Otherwise it creates a new class. Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type. Exception description, stack trace and values of variables are appended automatically. Array manipulation mini-language. It can run up to one hundred times faster than the equivalent Python code. Object that groups together rows of a dataframe based on the value of the passed column. Skip to content. Star Comprehensive Python Cheatsheet gto This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Branches Tags. Could not load branches. Could not load tags. Launching Xcode If nothing happens, download Xcode and try again. Launching Visual Studio Code Your codespace will open once ready. Latest commit. Git stats 2, commits. Failed to load latest commit information. Oct 2, View code. Use a capital letter for unsigned type. If array shapes differ in length, left-pad the shorter shape with ones: 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements: 3. If neither non-matching dimension has size 1, raise an error. Example For each point returns index of its nearest point [0. Contents 1. Also works on strings. Also works on dictionary and set. Replaces ones with matching keys. Accepts floats. Indices can be None. Fraction yes yes yes yes float yes yes yes complex yes yes decimal. Also group 0. London without DST. Also gettz. Raises ValueError. Could be too late to start deleting vars. Do not mix. Joins two or more pathname components. Also Path '. Also Path. Permissions are in octal. Returns its stdout pipe. Returns None on success. Also ':memory:'. Exits the block with commit or rollback. A multithreaded and non-lazy map. Starts a thread and returns its Future object. Full exception if full. Empty exception if empty. Also locals. BeautifulSoup html , 'html. ConnectionError : print "You've got problems with connection. Last point gets connected to the first. Draw frame draw. Rect , , 20 , 20 while all event. QUIT for event in pg. Rect x , y , width , height Floats get truncated into ints. Allows assignments. Surface width , height New RGB surface. Format depends on source. Pass None for default. BytesIO urllib. Clock while all event. Also plt. Sr is treated as a row. Uses 'left' by default. Use l. A Series is c. Also updates b 3 4 5 items that contain NaN. Func can return DF, Sr or el. All operations return a Sr. Text "What's your name? Input ], [ sg. About Comprehensive Python Cheatsheet gto Contributors You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window.
1 note
·
View note
Text
Interview questions(Python)
Q1. What are key features of Python?
Python is free and open-source
It is an object-oriented language
Easy to learn due to its clear syntax and readability
Easy to interpret, making debugging very easy.
Easily integrated with other languages like c++, java or more.
Q2. Difference between list and tuple
Q3. What is decorator?
A decorator is just a function that takes another function as an argument, add some kind of functionality and then returns another function. All this without altering the source code of original function.
Q4. What is difference between generator and iterator?
Q5. What is init keyword in python? (init.py and init function)
Q6. What is difference between module and package?
Q7. What is Range() and Xrange()?
Q8. What is generator?
Q9. What are inbuilt data types in python (or immutable or mutable data types)?
Q10. Difference between list and dict comprehension ?
Q11. How is memory managed in python?
Commonly asked question
Q12. What is ternary operator?
Q13. What is inheritance in python?
Q14. What is local and global variable?
Q15. What is continue, break and pass?
Q16. What is self keyword in python?(It is parameter to refer to current instance of the class)
Q17. What is pickling and unpickling?
Q18. Explain function of list, set, tuple or dictionary?
Q19. What is iterator?
Q20. Explain type conversion?
0 notes
Text
Python Tutorial
Python Syntax compared to other programming languages
Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
Comments
Comments start with a #
Multi Line Comments: triple quotes("""abcd""")
Variables
Global Variables
Data types
Casting
int(), float(), str()
Strings are Arrays
a = "Hello, World!" print(a[1])
Range of Indexes
print(thislist[2:5]) #the item in position 5 is NOT included
print(thislist[-4:-1]) #Negative indexing means starting from the end of the list. #-4 (included) to index -1 (excluded) #Remember that the last item has the index -1
Copy a List
list2 = list1.copy() (O) list2 = list1 (X) #You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
Dictionary
Loop Through a Dictionary
#keys for x in thisdict: print(x)
#values for x in thisdict: print(thisdict[x])
#values for x in thisdict.values(): print(x)
#both keys and values for x, y in thisdict.items(): print(x, y)
Removing Items
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict)
Copy a Dictionary
dict2 = dict1 (X) dict2 = dict1.copy() (O)
If ... Else
Loops
while
execute a set of statements as long as a condition is true.
for
range(2, 6) means values from 2 to 6 (but not including 6)
range(2, 30, 3) means incrementing the sequence with 3 (default is 1)
break
can stop the loop even if the while condition is true
continue
can stop the current iteration, and continue with the next loop iteration
pass vs continue
After executing pass, this further statement would be executed. After continue, it wouldn't.
E.g. >>> a = [0, 1, 2] >>> for element in a: ... if not element: ... pass ... print element ... 0 1 2 >>> for element in a: ... if not element: ... continue ... print element ... 1 2
else
can run a block of code once when the condition no longer is true
i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")
Functions
Passing Multiple Arguments to a Function
*args (arbitrary arguments)
It allows you to pass a varying number of positional arguments.
This way the function will receive a tuple of arguments.
# sum_integers_args.py def my_sum(*args): result = 0 # Iterating over the Python args tuple for x in args: result += x return result print(my_sum(1, 2, 3))
**kwargs
It allows you to pass a varying number of keyword arguments.
This way the function will receive a dictionary of arguments.
# concatenate.py def concatenate(**kwargs): result = "" # Iterating over the Python kwargs dictionary for arg in kwargs.values(): result += arg return result print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
Unpacking With the Asterisk Operators: * & **
E.g.)
Ordering Arguments in a Function
1) Standard arguments 2) *args arguments 3) **kwargs arguments
E.g.
Lambda
is a small anonymous function.
E.g.)
x = lambda a : a + 10 print(x(5))
Syntax
lambda arguments : expression
Why Use Lambda Functions
The power of lambda is better shown when you use them as an anonymous function inside another function.
E.g. #use the same function definition to make both functions, in the same program: def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) print(mytripler(11)) >>22 >>33
Class
Python is an object oriented programming language. A Class is like an object constructor, or a "blueprint" for creating objects.
E.g.)
Create a Class
class MyClass: x = 5
Create Object
p1 = MyClass() print(p1.x)
__init__()
All classes have a function called __init__(), which is always executed when the class is being initiated. __init__() is also called constructor used for instantiating an object.
E.g.)
class car(): def __init__(self, model, color): self.model = model self.color = color def show(self): print("Model is", self.model ) print("color is", self.color ) audi = car("audi a4", "blue") ferrari = car("ferrari 488", "green") audi.show() ferrari.show()
self
“self” represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python.
Classes vs Instances
The class = the blue print.
An instance = a virtual copy
“A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.”
https://www.codecademy.com/forum_questions/558cd3fc76b8fe06280002ce
https://www.tutorialspoint.com/python/python_classes_objects.htm
The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self.
__repr__()
The Meaning of Underscores in Python
https://dbader.org/blog/meaning-of-underscores-in-python
Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from and child class is the class that inherits from another class
Create a Parent Class
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) x = Person("John", "Doe") x.printname()
Create a Child Class
class Student(Person): pass x = Student("Mike", "Olsen") x.printname()
When you add the __init__() function into the Student class, the Student class will no longer inherit the parent's __init__() function. <=> The child's __init__() function overrides the inheritance of the parent's __init__() function.
super()
Python also has a super() function that will make the child class inherit all the methods and properties from its parent
E.g.)
class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.graduationyear = year x = Student("Mike", "Olsen", 2019)
Modules
Modules vs Packages vs Libraries in Python
Module
Simply put, a module in python is a .py file that defines one or more function/classes which you intend to reuse.
e.g.) import calendar print(calendar.TextCalendar(firstweekday=6).formatyear(2015))
‘calendar’ = module
‘TextCalendar’ = a class in the ‘calendar’ module
‘firstweekday=6′ = initiating(constructor)
‘formatyear’ = a method
Package
A Python package refers to a directory of Python module(s).
Library
Unlike C or C++, the term library does not have any specific contextual meaning in p\Python. When used in Python, a library is used loosely to describe a collection of the core modules.
Dates
datetime module
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
E.g.)
import datetime x = datetime.datetime.now() print(x) >>2019-12-17 20:42:59.640906
strftime() method
for formatting date objects into readable strings.
E.g.)
import datetime x = datetime.datetime(2018, 6, 1) print(x.strftime("%Y-%m-%d")) >>2018-06-01
(https://www.w3schools.com/python/python_datetime.asp)
JSON
JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.
Python has a built-in package called json, which can be used to work with JSON data.
import json
Parse JSON - Convert from JSON to Python
# some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"])
Convert from Python to JSON
# a Python object (dict): x = { "name": "John", "age": 30, "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y)
RegEx
https://www.w3schools.com/python/python_regex.asp
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.
Python has a built-in package called ‘re’, which can be used to work with Regular Expressions.
import re
Functions
findall()
Returns a list containing all matches
If no matches are found, an empty list is returned
e.g.)
import re txt = "1The 2 rain 3in Spain45" x = re.findall("\d+", txt) print(x) >>> ['1', '2', '3', '45']
search()
Returns a Match object if there is a match anywhere in the string
If there is more than one match, only the first occurrence of the match will be returned
If no matches are found, the value None is returned:
split()
Returns a list where the string has been split at each match
sub()
Replaces one or many matches with a string
e.g.)
import re txt = "The rain in Spain" x = re.sub("\s", "9", txt) print(x) # Replace every white-space character with the number 9 >>> The9rain9in9Spain
Metacharacters
Metacharacters are characters with a special meaning:
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:
Match Object
A Match Object is an object containing information about the search and the result.
If there is no match, the value None will be returned, instead of the Match Object.
The Match object has properties and methods used to retrieve information about the search, and the result:
.span()
returns a tuple containing the start-, and end positions of the match.
.string
returns the string passed into the function
.group()
returns the part of the string where there was a match
Try Except
https://www.w3schools.com/python/python_try_except.asp
code
try
The try block lets you test a block of code for errors.
except
The except block lets you handle the error.
finally
The finally block lets you execute code, regardless of the result of the try- and except blocks.
e.g.
try: print(1/0) except ZeroDivisionError as e: print("Error Code:", e) except ValueError as e: print('Error Code:', e) >> Error Code: division by zero
Raise
is used to raise an exception.You can define what kind of error to raise, and the text to print to the user.
code
x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
User Input
String Formatting
if __name__ == __main__
https://stackoverflow.com/questions/419163/what-does-if-name-main-do
https://dojang.io/mod/page/view.php?id=2448
When the Python interpreter reads a source file, it first defines a few special variables. like ‘__name__’
When Your Module Is the Main Program
the interpreter will assign the hard-coded string "__main__" to the __name__ variable
When Your Module Is Imported By Another
the interpreter will assign the file name of your module to the __name__ variable
https://www.w3schools.com/python/python_intro.asp https://stackoverflow.com/questions/9483979/is-there-a-difference-between-continue-and-pass-in-a-for-loop-in-python/36952166 https://www.geeksforgeeks.org/self-in-python-class/ https://www.geeksforgeeks.org/constructors-in-python/ https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ https://knowpapa.com/modpaclib-py/ https://realpython.com/python-kwargs-and-args/
0 notes
Text
Top 25 Python Interview Questions and Answers asked in Interview
Here the top 25 Python interview questions and answers to help you crack your Python Interview. If you want to learn Practical Python Training then please goes through this Python Classes in Pune.
Q1. What is the difference between list and tuples in Python?
LIST vs TUPLESLISTTUPLESLists are mutable i.e they can be edited.Tuples are immutable (tuples are lists which can’t be edited).Lists are slower than tuples.Tuples are faster than list.Syntax: list_1 = [10, ‘Chelsea’, 20]Syntax: tup_1 = (10, ‘Chelsea’ , 20)
Q2. What are the key features of Python?
Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x=”I’m a string” without error
Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private).
In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python
Python finds use in many spheres — web applications, automation, scientific modeling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.
Q3. What type of language is python? Programming or scripting?
Ans: Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language. To know more about Scripting, you can refer to the Python Scripting Tutorial.
Q4.How is Python an interpreted language?
Ans: An interpreted language is any programming language which is not in machine level code before runtime. Therefore, Python is an interpreted language.
Q5.What is pep 8?
Ans: PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.
Q6. How is memory managed in Python?
Ans:
Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
Q7. What is namespace in Python?
Ans: A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
Q8. What is PYTHONPATH?
Ans: It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
Q9. What are python modules? Name some commonly used built-in modules in Python?
Ans: Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.
Some of the commonly used built-in modules are:
os
sys
math
random
data time
JSON
Q10.What are local variables and global variables in Python?
Global Variables:
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables:
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
Example:
a=2
defadd():
b=3
c=a+b
print(c)
add()
Output: 5
When you try to access the local variable outside the function add(), it will throw an error.
Q11. Is python case sensitive?
Ans: Yes. Python is a case sensitive language.
Q12.What is type conversion in Python?
Ans: Type conversion refers to the conversion of one data type iinto another.
int() — converts any data type into integer type
float() — converts any data type into float type
ord() — converts characters into integer
hex() — converts integers to hexadecimal
oct() — converts integer to octal
tuple() — This function is used to convert to a tuple.
set() — This function returns the type after converting to set.
list() — This function is used to convert any data type to a list type.
dict() — This function is used to convert a tuple of order (key,value) into a dictionary.
str() — Used to convert integer into a string.
complex(real,imag) — This functionconverts real numbers to complex(real,imag) number.
Q13. How to install Python on Windows and set path variable?
Ans: To install Python on Windows, follow the below steps:
Install python from this link: https://www.python.org/downloads/
After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python.
Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
Look for the path variable, select its value and select ‘edit’.
Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_HOME%
Q14. Is indentation required in python?
Ans: Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
Q15. What is the difference between Python Arrays and lists?
Ans: Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type element whereas lists can hold any data type elements.
Example:
importarray as arr
My_Array=arr.array(‘i’,[1,2,3,4])
My_list=[1,’abc’,1.20]
print(My_Array)
print(My_list)
Output:
array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]
Q16. What are functions in Python?
Ans: A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.
Example:
defNewfunc():
print(“Hi, Welcome to Cyber Success”)
Newfunc(); #calling the function
Output: Hi, Welcome to Cyber Success
Q17.What is __init__?
Ans: __init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
Here is an example of how to use it.
classEmployee:
def__init__(self, name, age,salary):
self.name =name
self.age =age
self.salary =20000
E1 =Employee(“XYZ”, 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
Output:
XYZ
23
20000
Q18.What is a lambda function?
Ans: An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
Example:
a =lambdax,y : x+y
2. print(a(5, 6))
Output: 11
Q 19 What is self in Python?
Ans: Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
Q20. How does break, continue and pass work?
BreakAllows loop termination when some condition is met and the control is transferred to the next statement.ContinueAllows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loopPassUsed when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.
Q21. What does [::-1} do?
Ans: [::-1] is used to reverse the order of an array or a sequence.
For example:
importarray as arr
2. My_Array=arr.array(‘i’,[1,2,3,4,5])
3. My_Array[::-1]
Output: array(‘i’, [5, 4, 3, 2, 1])
[::-1] reprints a reversed copy of ordered data structures such as an array or a list. the original array or list remains unchanged.
Q22. How can you randomize the items of a list in place in Python?
Ans: Consider the example shown below:
fromrandom importshuffle
x =[‘Keep’, ‘The’, ‘Blue’, ‘Flag’, ‘Flying’, ‘High’]
shuffle(x)
print(x)
The output of the following code is as below.
[‘Flying’, ‘Keep’, ‘Blue’, ‘High’, ‘The’, ‘Flag’]
Q23. What are python iterators?
Ans: Iterators are objects which can be traversed though or iterated upon.
Q24. How can you generate random numbers in Python?
Ans: Random module is the standard module that is used to generate a random number. The method is defined as:
importrandom
2. random. Random
The statement random. Random () method return the floating point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
randrange (a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.
uniform (a, b): it chooses a floating point number that is defined in the range of [a, b). Iyt returns the floating point number
normalvariate (mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
The Random class that is used and instantiated creates an independent multiple random number generator.
Q25. What is the difference between range & xrange?
Ans: For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.
0 notes
Text
Original Post from Trend Micro Author: Trend Micro
By Daniel Lunghi and Jaromir Horejsi
We found new campaigns that appear to wear the badge of MuddyWater. Analysis of these campaigns revealed the use of new tools and payloads, which indicates that the well-known threat actor group is continuously developing their schemes. We also unearthed and detailed our other findings on MuddyWater, such as its connection to four Android malware families and its use of false flag techniques, among others, in our report “New MuddyWater Activities Uncovered: Threat Actors Used Multi-Stage Backdoors, False Flags, Android Malware, and More.”
One of the campaigns sent spear-phishing emails to a university in Jordan and the Turkish government. The said legitimate entities’ sender addresses were not spoofed to deceive email recipients. Instead, the campaign used compromised legitimate accounts to trick victims into installing malware.
Figure 1. Screenshot of a spear-phishing email spoofing a government office, dated April 8, 2019.
Figure 2. Email headers showing the origin of the spear-phishing email
Our analysis revealed that the threat actor group deployed a new multi-stage PowerShell-based backdoor called POWERSTATS v3. The spear-phishing email that contains a document embedded with a malicious macro drops a VBE file encoded with Microsoft Script Encoder. The VBE file, which holds a base64-encoded block of data containing obfuscated PowerShell script, will then execute. This block of data will be decoded and saved to the %PUBLIC% directory under various names ending with image file extensions such as .jpeg and .png. The PowerShell code will then use custom string obfuscation and useless code blocks to make it difficult to analyze.
Figure 3. Code snippet of obfuscated and useless code
The final backdoor code is revealed after the deobfuscation of all strings and removal of all unnecessary code. But first, the backdoor will acquire the operating system (OS) information and save the result to a log file.
Figure 4. Code snippet of OS information collection
This file will be uploaded to the command and control (C&C) server. Each victim machine will generate a random GUID number, which will be used for machine identification. Later on, the malware variant will start the endless loop, querying for the GUID-named file in a certain folder on the C&C server. If such a file is found, it will be downloaded and executed using the Powershell.exe process.
A second stage attack can be launched by commands sent to a specific victim in an asynchronous way, e.g., another backdoor payload can be downloaded and installed to targets that they are interested in.
Figure 5. The code in POWERSTATS v3 which downloads the second attack stage
We were able to analyze a case where the group launched a second stage attack. The group was able to download another backdoor, which is supported by the following commands:
Take screenshots
Command execution via the cmd.exe binary
If there’s no keyword, the malware variant assumes that the input is PowerShell code and executes it via the “Invoke-Expression” cmdlet
Figure 6. The code in POWERSTATS v3 (second stage) that handles the screenshot command
The C&C communication is done using PHP scripts with a hardcoded token and a set of backend functions such as sc (screenshot), res (result of executed command), reg (register new victim), and uDel (self-delete after an error).
Figure 7. In an endless loop, the malware variant queries a given path on the C&C server, trying to download a GUID-named file with commands to execute.
Other MuddyWater campaigns in the first half of 2019
The MuddyWater threat actor group has been actively targeting victims with a variety of tricks, and they seem to keep on adding more as they move forward with new campaigns. The campaign that used POWERSTATS v3 is not the only one we found with new tricks. We observed other campaigns that changed their delivery methods and dropped file types. Notably, these campaigns have also changed payloads and publicly available post-exploitation tools.
Discovery Date Method for dropping malicious code Type of files dropped Final payload 2019-01 Macros EXE SHARPSTATS 2019-01 Macros INF, EXE DELPHSTATS 2019-03 Macros Base64 encoded, BAT POWERSTATS v2 2019-04 Template injection Document with macros POWERSTATS v1 or v2 2019-05 Macros VBE POWERSTATS v3
Table 1. MuddyWater’s delivery methods and payloads in 2019 1H
In January 2019, we discovered that the campaign started using SHARPSTATS, a .NET-written backdoor that supports DOWNLOAD, UPLOAD, and RUN functions. In the same month, DELPHSTATS, a backdoor written in the Delphi programming language, emerged. DELPHSTATS queries the C&C server for a .dat file before executing it via the Powershell.exe process. Like SHARPSTATS, DELPHSTATS employs custom PowerShell script with code similarities to the one embedded into the former.
Figure 8. SHARPSTATS can be used to collect system information by dropping and executing a PowerShell script.
Figure 9. The code in DELPHSTATS that queries a certain directory on the C&C server. It’s where operators upload additional payload.
We came across the heavily obfuscated POWERSTATS v2 in March 2019. An earlier version of this backdoor decodes the initial encoded/compressed blocks of code, while an improved version appeared later on. The latter heavily uses format strings and redundant backtick characters. The function names in the earlier version were still somehow readable, but they were completely randomized in later versions.
Figure 10. Obfuscated POWERSTATS v2
After deobfuscation, the main backdoor loop queries different URLs for a “Hello server” message to obtain command and upload the result of the run command to the C&C server.
Figure 11. Deobfuscated main loop of POWERSTATS v2
Use of different post-exploitation tools
We also observed MuddyWater’s use of multiple open source post-exploitation tools, which they deployed after successfully compromising a target.
Name of the Post-Exploitation Tool Programming language/Interpreter CrackMapExec Python, PyInstaller ChromeCookiesView Executable file chrome-passwords Executable file EmpireProject PowerShell, Python FruityC2 PowerShell Koadic JavaScript LaZagne Python, PyInstaller Meterpreter Reflective loader, executable file Mimikatz Executable file MZCookiesView Executable file PowerSploit PowerShell Shootback Python, PyInstaller Smbmap Python, PyInstaller
Table 2. Tools used by MuddyWater campaigns over the years.
The delivery of the EmpireProject stager is notable in one of the campaigns that we monitored. The scheme involves the use of template injection and the abuse of the CVE-2017-11882 vulnerability. If the email recipient clicks on a malicious document, a remote template is downloaded, which will trigger the exploitation of CVE-2017-11882. This will then lead to the execution the EmpireProject stager.
Figure 12. Clicking on the malicious document leads to the abuse of CVE-2017-11882 and the execution of the EmpireProject stager.
Another campaign also stands out for its use of the LaZagne credential dumper, which was patched to drop and run POWERSTATS in the main function.
Figure 13. LaZagne has been patched to drop and run POWERSTATS in the main function. See added intimoddumpers() function. Note the typo in the function name – its INTI, not INIT.
Conclusion and security recommendations
While MuddyWater appears to have no access to zero-days and advanced malware variants, it still managed to compromise its targets. This can be attributed to the constant development of their schemes.
Notably, the group’s use of email as an infection vector seems to yield success for their campaigns. In this regard, apart from using smart email security solutions, organizations should inform their employees of ways to stay safe from email threats.
Organizations can also take advantage of Trend Micro Deep Discovery, a solution that provides detection, in-depth analysis, and proactive response to today’s stealthy malware and targeted attacks in real time. It provides a comprehensive defense tailored to protect organizations against targeted attacks and advanced threats through specialized engines, custom sandboxing, and seamless correlation across the entire attack lifecycle, allowing it to detect threats even without any engine or pattern updates.
View our full report to learn more about the other MuddyWater details we discovered.
The post MuddyWater Resurfaces, Uses Multi-Stage Backdoor POWERSTATS V3 and New Post-Exploitation Tools appeared first on .
#gallery-0-5 { margin: auto; } #gallery-0-5 .gallery-item { float: left; margin-top: 10px; text-align: center; width: 33%; } #gallery-0-5 img { border: 2px solid #cfcfcf; } #gallery-0-5 .gallery-caption { margin-left: 0; } /* see gallery_shortcode() in wp-includes/media.php */
Go to Source Author: Trend Micro MuddyWater Resurfaces, Uses Multi-Stage Backdoor POWERSTATS V3 and New Post-Exploitation Tools Original Post from Trend Micro Author: Trend Micro By Daniel Lunghi and Jaromir Horejsi We found new campaigns that appear to wear the badge of MuddyWater.
0 notes
Text
Flask 1.0 Changelog 우리말 번역
드디어 Flask 1.0이 출시되었네요 :) http://flask.pocoo.org/docs/1.0/changelog/ 를 우리말로 번역해봤습니다. 의역, 오역 많을 수 있으니 참고로만 봐주세요. 감사합니다.
Flask 1.0 Changelog
Python 2.6과 3.3 지원이 중단되었습니다.
의존성이 업데이트 되었습니다. (Werkzeug >= 0.14, Jinja >= 2.10, itsdangersou >= 0.24, Click >= 5.1)
명령줄에서 앱을 실행할 때 app.run을 생략했습니다. 디버깅하기에 혼란스러운 동작을 피할 수 있게 되었습니다.
JSONIFY_PRETTYPRINT_REGULAR 기본값을 False로 바꾸었습니다. 이제 기본 설정에서는 디버그 모드일떄만 jsonify() 결과값이 prettify입니다.
Flask.init이 host_matching 인자를 받습니다. 이 값을 url_map에 설정합니다.
Flask.init이 static_host 인자를 받습니다. static route를 정의할 때, 이 값을 host 인자로 넘깁니다.
send_file()이 attachement_filename에 유니코드를 지원합니다.
오류가 발생하면 url_for()의 _scheme 값을 handle_url_build_error()로 넘깁니다.
add_url_rule()이 provide_automatic_options 인자를 받습니다. 이 값은 OPTIONS method 추가를 불가능하게 하기 위해 씁니다.
MethodView 서브 클래스들이 부모 클래스들의 method handlers들을 상속 받습니다.
요청 초기에 세션을 오픈하는 동안 생기는 오류들을 앱의 오류 핸들러에서 처리 가능합니다.
Blueprint에 json_encoder, json_decoder 속성이 생겼습니다. 이 속성들은 앱의 encoder와 decoder를 오버라이드합니다.
Flask.make_response()가 유효하지 않은 Response Type들에 대해 ValueError 대신 TypeError를 발생시킵니다. 왜 해당 Type이 왜 유효하지 않은지 알려주기 위해 오류 메시지를 개선했습니다.
CLI에 'routes' 명령을 추가했습니다. 이 명령은 앱에 등록된 라우팅들을 보여줍니다.
세션 쿠키 도메인이 bare hostname(ex. localhost)이거나 IP면 경고를 보여줍니다. Chrome과 같은 일부 브라우저에서는 제대로 작동하지 않을 수 있습니다.
정확한 세션 쿠키 도메인으로 IP 주소를 허용합니다.
SERVER_NAME에�� SESSION_COOKIE_DOMAIN이 감지되면, SESSION_COOKIE_DOMAIN이 설정됩니다.
앱 factory 함수 create_app 혹은 make_app을 자동으로 감지합니다.
flask 명령으로 작업하기 위해 script_info 매개 변수를 사용하는 것은 Factory 함수가 필요 없습니다. 만약에 단일 인자나 script_info라는 이름으로 인자를 받으면, ScriptInfo 객체가 넘어갑니다.
앱 factory를 FLASK_APP로 설정할 수 있습니다. 필요하면 인자도 같이 넣을 수 있습니다. ex. FLASK_APP=myproject.app:create_app('dev').
FLASK_APP�� 로컬 패키지도 가리킬 수 있습니다. 로컬 패키지가 편집 가능한 상태가 아니어도 가능합니다. 물론 pip install -e를 설정하는게 선호되긴 합니다.
View 클래스 속성 provide_automatic_options가 add_url_rule()에서 감지되어, as_view()에 설정됩니다.
오류 핸들 시에 'blueprint, code', 'app, code', 'blueprint', 'exception', 'app exception'에 등록된 핸들러를 사용합니다.
요청 중에 세션에 접근할 경우 응답 Vary 헤더에 Cookie가 추가됩니다. (단, 세션이 삭제되지 않았어야 합니다.)
test_request_context()가 subdomain, url_scheme 인자를 받습니다. base URL을 만들 떄 이 값들을 사용합니다.
APPLICATION_ROOT 기본값을 '/'로 설정했습니다. 사실, 원래부터 값이 None이면 '/'로 작동하긴 했습니다.
TRAP_BAD_REQUEST_ERRORS가 디버그 모드에서 기본값으로 켜집니다. BadRequestKeyError 오류가 발생하면, 일반 모드에서는 일반적인 오류 메시지가 나오지만 디버그 모드에서는 메시지에 오류 키값이 들어있습니다.
TaggedJSONSerializer에 새로운 태그를 등록하는 것을 허용합니다. 이로 세션 쿠키에 다른 형식 저장을 지원합니다.
해당 요청이 아직 context stack에 들어가지 않았을때만 세션을 엽니다. stream_with_context() 제네레이터가 포함된 뷰에서 사용하는 것과 동일한 세션에 접근할 수 있습니다.
테스트 클라이언트 요청 메소드에 'json' keyword 인자를 추가했습니다. 주어진 객체를 JSON으로 덤프하고 적절한 Content type을 설정합니다.
요청 및 응답 클래스 모두에 적용되는 Mixin에 JSON처리를 추출했습니다. response에 is_json(), get_json() 메소드가 추가되어 JSON response 테스트가 더 쉬워집니다.
오류 핸들러 캐시를 제거했습니다. 이는 몇몇의 예외 처리에 상속 위계 문제를 일으켰습니다. MRO 통과를 피하려면 각 예외에 대해 명시적으로 핸들러를 등록해야합니다.
non-UTC datetime의 JSON 인코딩 버그를 고쳤습니다.
템플릿 자동 reloading은 이미 jinja_env에 접근했더라도 디버그 모드를 유지합니다.
다음 deprecated 코드들을 제거했습니다.
flask.ext - 확장들을 flask.ext namespace 말고 직접 import 해야합니다. ex. import flask.ext.sqlalchemy -> import flask_sqlalchemy
Flask.init_jinja_globals - Flask.create_jinja_environment()를 확장해서 사용하세요.
Flask.error_handlers - Flask.error_handler_spec으로 추적할 수 있습니다. 핸들러 등록은 Flask.errorhandler()를 쓰세요.
Flask.request_globals_class - Flask.app_ctx_globals_class를 쓰세요.
Flask.static_path - Flask.static_url_path를 쓰세요.
Request.module - Request.blueprint를 쓰세요.
Request.json - 이젠 deprecate 대상이 아닙니다.
EnvionBuilder 혹은 dict를 test_client.open에 넘기는 걸 지원합니다.
python-dotenv가 설치되어 있으면, flask 명령과 Flask.run()은 .env, .flaskenv 파일에서 ���경 변수를 가져올 것 입니다.
전체 URL을 테스트 클라이언트에 넘기면, PREFERRED_URL_SCHEME 대신에 URL의 스킴이 쓰입니다.
Flask.logger가 간단해졌습니다. LOGGER_NAME과 LOGGER_HANDLER_POLICY 설정을 없앴습니다. 로거 이름은 항상 flask.app입니다. 레벨은 첫번째 접근 때 설정됩니다. 매번 Flask.debug를 확인하지 않습니다. Flask.debug에 따라 형식은 한개만 쓰입니다. 아무 핸들러도 제거되지 않고, 어떤 핸들러도 설정되어있지 않은 경우에만 추가됩니다.
Blueprint 뷰 함수는 점(.)을 포함하면 안됩니다.
유효하지 않은 Range 헤더 요청에 의해 발생하는 ValueError 버그를 고쳤습니다.
개발 서버는 기본으로 스레드를 사용합니다.
silent=True로 설정을 가져오면 ENOTDIR 오류를 무시합니다.
개발 서버에 HTTPS를 쓰고 싶으면 --cert와 --key 옵션을 flask run에 넘기면 됩니다.
세션 쿠키에 SameSite 속성을 제어하는 용도로 SESSION_COOKIE_SAMESITE를 추가했습니다.
테스트 용도로 Flask CLI 명령어를 실행할 수 있는 Click runner를 생성할 수 있도록 test_cli_runner()를 추가했습니다.
서브도메인 매칭을 기본값으로 꺼놓았습니다. SERVER_NAME 설정이 암시적으로 이것을 켜진 않습니다. subdomain_matching=True를 Flask 생성자에 넘김으로써 켤 수 있습니다.
앱에 blueprint가 등록될 때 blueprint url_prefix에서 마지막 /(slash)가 제거됩니다(stripped).
silent가 True면 Request.get_json() 파싱에 실패했을때 결과를 캐시하지 않습니다.
Request.get_json()는 더이상 임의 인코딩을 수용하지 않습니다. 요청 JSON은 RFC 8259에 근거한 UTF-8이어야 합니다. (UTF-16, UTF-32도 자동 감지합니다.)
브라우저가 무시했을 수 있는 큰 쿠키에 대해 Werkzeug가 경고할 때 이를 제어하기 위해 MAX_COOKIE_SIZE와 Response.max_cookie_size를 추가했습니다.
작은 창에서 문서를 더 쉽게 볼 수 있게 theme을 업데이트했습니다.
튜토리얼 문서와 예시 프로젝트를 재작성했습니다. 새로운 유저들이 흔히 겪는 어려움을 돕기 위해 체계화된 접근을 했습니다.
0 notes
Note
Hello! I'm not sure if this blog is still active, but it's worth a shot. When doing something with multiple endings, how would you do a dating sim with multiple endings for each character, like a Good one and a Bad one?
Heya Isaacie! Better late than never I hope?
I did an initial treatment of the idea of multiple endings here. I’d go about it a little differently now, so I’ll give more detail about architecture for a game below.
The basic substance of your question is “how do I make the game interpret the difference between different states?”. If you’re using variables to keep track of things, all you need to do is have the game test if the player has met certain conditions in order to determine an outcome.
For a game with multiple romance-ables, it might work best to separate the romance paths into different files. Then, at the end of each romance file, have the conditionals for if something is a good or bad end. You can bring the player back into the MAIN file for things that are the same across all runs, and then have the game check to see which character they are romancing to go decide where to go.
This would work something like:Main story line ~> romance path chosen ~> go to character’s romance file ~> romance interaction #1 ~> back to main file ~> romance interaction #2 ~> ect.
In that case, it would be simplest to CALL the new file’s first label, then RETURN at the end of the romance scene after choices are made. This will put you back into the main script right where you last left off to do general same story line things. Then you can call the next label in from the romance file and return back, ect.
If the story never intersects again once a main love interest is chosen(think something like Katawa Shoujo) then you can just continue the story in those romance files. (You’ll probably want to set a variable like Romance_X = True in your files too if it affect the main plotline minimally, but you still want ppl to reference it in dialogue or something!)
At the end of the romance files you need some way to determine if they’ve done “good” or “bad” to see what ending they should get. You can do this by keeping track of how many “affection points” they got and deciding if they have below a certain value they get a “Bad End”.
Example:
label determine_ending: if Leo_love <= 10: jump bad_ending elif Leo_love .... .....
Ect for each scenario. This only works if they can only romance one person at a time. They get locked into a romance path(whether or not the rest of the game has story beats in common between routes) and so only one person needs to be checked.
But what if you wanna let them romance multiple ppl at once and see which one they got the farthest with?
For something like that you’ll need to put the affections in a dictionary, determine which one is the largest and then do the good/bad ending logic above.The logic would look something like this:
init python: John_love = 0 Mike_love = 0 Jimmy_love = 0 Sasha_love = 0(game play where you add affection with variable_name += number amount)(then a python block right before the end of the game)python: affection_dict = {"John": John_love, "Mike": Mike_love, "Jim": Jimmy_love, "Sasha": Sasha_love} love_holder = [] winner = None
for x in affection_dict.values(): love_holder.append(x) love_max = max(love_holder) for x in affection_dict: if affection_dict[x] == love_max: winner = x
Then at the end of your main file you’d type something like this:
if winner == “Sasha”: jump Sasha_endingselif winner == “Mike”: jump Mike_endings ....
Ect for each romanceable. Then you once again determine if they got a good or bad ending with them or not based on affection, which is separate from who they had the most affection with.(they could theoretically have 0, 0, 5, 9 and need a minimum of 10 for any non-bad end, if can even check to see if the max of the list is bigger than 10 and if not just have them giga fail with an ultimate bad end or something. You’d just add a line after love_max = max(love_holder) to say:
if love_max < 10: jump ultra_fail
They won’t even get to the rest of the code to pick the winner because it doesn’t matter lol.)
All that being said, the basic principals are:-have conditions that are failable-figure out what level of failure justifies a bad ending based on how your game plays-test the state of the game based on those conditions-use the result of that state testing to produce an end state result
I know this was long, and a very delayed answer, but I hope this helps you and others! Remember: If your code won’t compile and you don’t know why; who ya gonna call? The Ren’Py Help Desk!
#RenPy#Ren'Py#thehelpdesk#Renpyhelpdesk#multiple endings#keyword: call#keyword: return#keyword: jump#conditionals#keyword: python#keyword: init python#coding design
18 notes
·
View notes
Note
Is there a way to change the screen size?
This is a matter of the configuration of Renpy itself. This is commonly changed though and can be accessed through an init python block and the “config” namespace.
To change the resolution of the game you’d just need to type:
init python: config.screen_width = new integer config.screen_height = new integer
This needs to be done before the game’s start label and can be accomplished at the beginning of the renpy.gui file for your game, for example. You could also put it in the main file for your game but uh, try to stay organized please?
That’s all for this one. Remember: If your code won’t compile, and you don’t know why; who ya gonna call? The Ren’Py Help Desk!
#RenPy#Ren'Py#thehelpdesk#Renpyhelpdesk#keyword: init python#configuration#gui#the great return continues
6 notes
·
View notes