Was bedeutet % in python
hallo, die frage mag etwas dumm erscheinen, aber wenn ich in google sowas wie "python %" oder "python rechenzeichen" eingebe, kommt irgendwie nichts nützlichen. wenn jetzt z.b bei einem code sowas vor kommt wie "if x % y == 0:" was bedeutet dann dieses prozent?
4 Antworten
Das ist der modulo operator
http://docs.python.org/2/reference/expressions.html
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
Das ist der "Modulo"-Rechenoperator. Ihr habt in der Grundschule bestimmt schriftliche Division gehabt, und da ihr noch nicht mit Dezimalzahlen rechnen konntet, habt ihr sehr wahrscheinlich mit Rest gerechnet. Zu deinem Beispiel:
if x % y==0
Wenn x geteilt durch y den Rest 0 ergibt (also 7/7, 56/8, alles was eine Ganzzahldivision ist die aufgeht) wird die Anweisung dahinter ausgeführt. Vorrausgesetzt du vergisst den Doppelpunkt hinter der if-Anweisung nicht :)
Das % steht für Modulo. Soll soviel heissen wie "Rest aus einer Ganzzahldivision". In deinem Beispiel wird geprüft ob die Zahl x durch die Zahl y "teilbar" ist. Also ob der Rest 0 ergibt. Ein Beispiel für eine Ganzzahldivision mit Rest:
7 % 4 = 3
Wenn du mehr darüber wissen willst: http://de.wikipedia.org/wiki/Division_mit_Rest oder google nach Modulo
Der Rest einer Division mit Rest.