function,python-2.7 , How to skip a function

How to skip a function


Tag: function,python-2.7

I am learning python and trying to make a little game. So my question is can you define a function but skip it and use it later. EX.

def func()

def func2()
    print "counting"

How would I skip func but still be able to print it later?


If I you're asking what I think you're asking, then yes. In fact, that's the whole point. Functions are sections of reusable code that you define first (they don't run when they're defined!) and then you call that function later.

For example, you can define a function, helloworld like this:

def helloworld():
    print "Hello, world!"

At this point in the program, nothing happens. You can then call the function like this:


At this point, "Hello, world!" will output to the console, and you can call the function as many times as you like!


Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

Is it possible to use $(this) in a function called from another function?

Sorry for the question title, I know it's not very well worded, but I couldn't really explain what I'm asking in a summary. I have a JQuery function tied to the click event of an element. For reasons that may well be flawed (other than making more sense to me...

Pass function call as a function argument

Code: def function1(a,b): return a-1,b-1 def function2(c,d): return c+1,d+1 print function1(function2(1,2)) Error: Traceback (most recent call last): File "C:\Users\sony\Desktop\Python\scripts\", line 6, in <module> print function1(function2(1,2)) TypeError: function1() takes exactly 2 arguments (1 given) [Finished in 0.1s with exit code 1] Why the above error? ...

JSLint won't recognize getElementById

JSLint gives errors with simple function, running on brackets with JSLint. Javascript: function soundSorry() { getElementById("player").play(); } Error codes: 2 Missing 'use strict' statement. getElementById("player").play(); 2 'getElementById' was used before it was defined. getElementById("player").play(); Any ideas?...

How to extract efficientely content from an xml with python?

I have the following xml: <?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="user23"> <document><![CDATA["@username: That boner came at the wrong time ????" HELP I'M DYING ]]></document> <document><![CDATA[Ugh ]]></document> <document><![CDATA[YES !!!! WE GO FOR IT. ]]></document> <document><![CDATA[@username Shout out to me???? ]]></document> </author> What is the most efficient...

Strange Behavior: Floating Point Error after Appending to List

I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

PySerial client unable to write data

I'm trying to write a python program which can communicate over a serial interface using PySerial module as follows: import serial if __name__ == '__main__': port = "/dev/tnt0" ser = serial.Serial(port, 38400) print print ser.isOpen() x = ser.write('hello') ser.close() print "Done!" But if I execute the above I get...

Identify that a string could be a datetime object

If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

Stopping list selection in Python 2.7

Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has...

Update input number variable onclick

I am trying to create a calculator style thing, where you put in how many years into a input, you hit submit and it gives you different results below without reloading the page. I have all the calculations working right now, but I just cant get the input number variable...

Python Popen - wait vs communicate vs CalledProcessError

Continuing from my previous question I see that to get the error code of a process I spawned via Popen in python I have to call either wait() or communicate() (which can be used to access the Popen stdout and stderr attributes): app7z = '/path/to/7z.exe' command = [app7z, 'a', dstFile.temp,...

How to remove structure with python from this case?
How to remove "table" from HTML using python? I had case like this: paragraph = ''' <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem molestiae consequuntur officiis corporis sint.<br /><br /> <table> <tr> <td> text title </td> <td> text title 2 </td> </tr> </table> <p> lorem ipsum</p> ''' how...

Python split by comma delimiter and strip

I am trying to open a file in python in read mode then write striped and split data to an output file. I am unsure how to split and strip the same data. Do I need to create a different line? Do I need to write the data out first?...

How to check for multiple attributes in a list

I am making a TBRPG game using Python 2.7, and i'm currently making a quest system. I wanted to make a function that checks all of the quests in a list, in this case (quests), and tells you if any of of the quests in the list have the same...

List of tuples from (a, all b) to (b, all a)

I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

from x(defined in program) import y(defined in program) python

I need some assitance since I really have no idea how I can fix this: x="test" y="test2" When I try to import y from x , it says that there is no file with the name "x" (from x import y) Is there any way to import test2 from test...

Counting bytes received by posix read()

I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

sum of Digits through Recursion

I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

How can I resolve my variable's unexpected output?

I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

PercentOfSum(fld, condfld) SSRS Equivalent

Crystal Reports has a built-in function PercentOfSum(fld, condfld) (documentation here). How can I achieve the same functionality in SSRS?

multiple iteration of the same list

I have one list of data as follows: from shapely.geometry import box data = [box(1,2,3,4), box(4,5,6,7), box(1,2,3,4)] sublists = [A,B,C] The list 'data' has following sub-lists: A = box(1,2,3,4) B = box(4,5,6,7) C = box(1,2,3,4) I have to check if sub-lists intersect. If intersect they should put in one tuple;...

Replace paragraph in HTML with new paragraph using Javascript

I am attempting to replace a p in my HTML doc with a paragraph created in Javascript. Once the page loads, two will be replaced with t. var two = document.getElementById("two"); document.onload = function myFunction() { var p = document.createElement("p"); var t = document.createTextNode("I am the superior text"); p.appendChild(t); document.getElementById("p");...

Count function counting only last line of my list

Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string[0] == 'k': cnt.append('k') elif string[0] == 'R': cnt.append('R') print cnt.count('R') if I am giving...

Use NamedTemporaryFile to read from stdout via subprocess on Linux

import subprocess import tempfile fd = tempfile.NamedTemporaryFile() print(fd) print( p = subprocess.Popen("date", stdout=fd).communicate() print(p[0]) fd.close() This returns: <open file '<fdopen>', mode 'w' at 0x7fc27eb1e810> /tmp/tmp8kX9C1 None Instead, I would like it to return something like: Tue Jun 23 10:23:15 CEST 2015 I tried adding mode="w", as well as delete=False, but...

Call known function (with parameters) in class whose name is defined by string variable

I have a bunch of classes of various names and each has a performLogic function that accepts a number of preset parameters (always the same): public final class DoSomeAction extends SetupAction { public void performLogic(param1, param2... I want a way where I can call it like this: String actionName =...

Stuck on Structs(c++)

Okay so this is what Ive been asked to do "make a struct called Coordinate that contains the latitude and longitude of a point on the surface of the Earth. The struct should also store a label or name for the coordinate (e.g., “Calgary”). Both the latitude and longitude member...

how to fetch a column in browse_record_list in orm browse method in openERP

I'm beginner in openERP. I'm trying to get a column in a table. While using ORM browse method and iterating that object i got the result in browse_record_list as browse_record(,21). I want to fetch that particular id 21 alone through that browse method but instead im getting same browse_record as...

Can't understand this Javascript function (function overloading)

I'm reading Secrets of Javascript Ninja and came across an example that I cannot fully understand. This same example was cited by some other user here before, but their doubts are different than mine. Here is the example: function addMethod(object, name, fn) { var old = object[name]; object[name] = function(){...

Python code not executing in order? MySQLdb UPDATE commits in unexpected order

I've got a Python 2.7 script I'm working on that retrieves rows from a MySQL table, loops through the data to process it, then is supposed to do the following things in this order: UPDATE the table rows we just got previously to set a locked value in each row...

Pandas Dataframe Complex Calculation

I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

Anaconda site-packages

After installing a package in an anaconda environment, I'll like to make some changes to the code in that package. Where can I find the site-packages directory containing the installed packages? I do not find a directory /Users/username/anaconda/lib/python2.7/site-packages...

Parsing Google Custom Search API for Elasticsearch Documents

After retrieving results from the Google Custom Search API and writing it to JSON, I want to parse that JSON to make valid Elasticsearch documents. You can configure a parent - child relationship for nested results. However, this relationship seems to not be inferred by the data structure itself. I've...

How does ((a++,b)) work? [duplicate]

This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

python - how to properly evaluate a value from a system command

I'm just learning python (using 2.7.8) and i'm trying to figure out what is the best way to evaluate the output of a system command. I've read to use subprocess. For example, I need to run this IF statment and evaluate for anything > 0, then process it. Example of...

jQuery - Value in Function

My array: = "Thiago"; = "01/01/1990"; I want a function like this: function myFunc( array, fieldToCompare, valueToCompare ) { if( array.fieldToCompare == "Thiago" ) alert(true); } myFunc( myArray, name, "Thiago" ); is it possible?...

How to skip a function

I am learning python and trying to make a little game. So my question is can you define a function but skip it and use it later. EX. def func() print"1,2,3,4" func() def func2() print "counting" func() func2() How would I skip func but still be able to print it...

SQL average age comparison function returns null

So, I'm working in MySQL, writing a function that averages the ages of women and men from a table and compares them, and returns which is greater. Dates are in the format of YYYY-MM-DD, and I'm using DATEDIFF(). The function appears to work correctly, but when I run the script,...

Python initialize strings as variable

I have a calculation schema as string calc = "((k+m+46)/2)" and some strings containing variable like m = 2 k = m*2 all only strings. Now I want to initialize them into Python. my goal is it to calculate with the calculating schema the varible values. calc should return 26...

Selecting and removing a html select option without selecting by index or ID, using vanilla JavaScript

I need to remove an option on a select box, and I've figured out a potential solution in the code below, but it doesn't feel particularly 'safe' (if another developer decided to add an option to the backend, the option will re-appear). Is there a better way of achieving this...

C++ need help figuring out word count in function. (Ex. Hello World = 2)

I'm figuring out the algorithm on this function and it keeps crashing at runtime, here's the code snippet: int wordCounter(char usStr[]) { int index= 0, punct= 0; while(usStr[index]!= '\0') //If it's not the end of the sentence if(usStr[index]== ' ') //If it finds a space index++; while(usStr[index]== '\0') //If it's...

How can I minimize this function in R?

I'm attempting to write a formula that will determine a value of a that minimizes the function output myfun (i.e. a-fptotal). MWE: c <- as.matrix(c(.25,.5,.25)) d <- as.matrix(c(10000,12500,15000)) e <- 700 f <- 1.1 tr <- .30 myfun <- function(a) { b <- max(a-e,0) df <- data.frame(u1=c(c*b*.40),u2=c(c*b*.60)) df$year <- 1:nrow(df)...

Is there a way to say for every x values, do this?

Before I start, I am new to Python, so any low-level description would be incredibly helpful! I have a list of lets say 60 values (representing one hour, from 8:00-9:00) and I want to run average, maximums, minimums, and standard deviation for each set of 15. (I already have the...

I need to make sure that only certain characters are in a list?

I have this to get input and put it in a list: def start(): move_order=[raw_input("Enter your moves: ").split()] And I only want the characters A, D, S, C, H (it's for a game >_>) to be allowed. I've tried using the regular expressions stuff: if re.match('[ADSCH]+', [move_order]) is False: print...

How do I copy a row from one pandas dataframe to another pandas dataframe?

I have a dataframe of data that I am trying to append to another dataframe. I have tried various ways with .append() and there has been no successful way. When I print the data from iterrows. I provide 2 possible ways I tried to solve the issue below, one creates...

Calling function and passing arguments multiple times

I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

Parse text from a .txt file using csv module

I have an email that comes in everyday and the format of the email is always the same except some of the data is different. I wrote a VBA Macro that exports the email to a text file. Now that it is a text file I want to parse the...

session value in javascript cannot be set

I am quite new to javascript, I wonder why my session value in javascript wont be set to 1 even I tried. When call this function again, the value of the session will change again. My javascript code as below. <script type="text/javascript"> function Confirm() { alert(<%=Session["Once"]%> != 1); var value...

Slicing a Python OrderedDict

In my code I frequently need to take a subset range of keys+values from a Python OrderedDict (from collections package). Slicing doesn't work (throws TypeError: unhashable type) and the alternative, iterating, is cumbersome: from collections import OrderedDict o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) # want to...

Why does `for lst in lst:` work? [duplicate]

This question already has an answer here: Why can I use the same name for iterator and sequence in a Python for loop? 6 answers The following code lst = ['foo', 'bar', 'baz'] for lst in lst: print lst gives me this output foo bar baz I would expect...

What is the difference between <> and == in python?

In [142]: (MON,TUE,WED,THR,FRI,SAT,SUN)<>range(7) Out[142]: True In [143]: (MON,TUE,WED,THR,FRI,SAT,SUN)==range(7) Out[143]: False ...