Difference between revisions of "Python"

From ScienceZero
Jump to: navigation, search
(Writing to a text file)
m (Combining strings)
Line 95: Line 95:
 
=Strings=
 
=Strings=
 
==Combining strings==
 
==Combining strings==
print "abc" + "123"
+
print "abc" + "123"
  
 
[[Category:Computing]]
 
[[Category:Computing]]

Revision as of 12:09, 2 October 2017

Application

File Header

#!/usr/bin/python

Comments

These begin with the # character

Libraries

Subroutines

These must be placed at the top, under the file header and library includes

def functionname(value):
	#do something
	return somevariable

Variables

There is no method to define a variable type, it is determined by the type of the first value it gets set to
a = 42 will create an int called a with value 42

Loops

Infinite

while True:
	#code to loop

While (check then run)

a = 0
while a < 10:
	a += 1

While (run then check)

while True:
    #code
    if i == 10:
       break	#this exits the while loop

For

for i in range(127,-1,-1):	#step from 127 to 0 by 1
	print i

Conditionals

Equal

if i == 10:
	print i

Not equal

if i != 10:
	print i

Greater than

if i > 10:
	print i

Less than

if i < 10:
	print i

Greater than or equal to

if i >= 10:
	print i

Less than or equal to

if i <= 10:
	print i

If Else

if i == 10:
	print i
else:
 	print "I isn't 10"

Math

a = b + 2	#addition
a = b - 2	#subtraction
a = b * 2	#multiplication
a = b / 2	#division
a = b % 2	#modulo division (divides b by 2, and returns the remainder)

Bitwise functions

a = b >> 2	#shift the bits of an int right by an amount of times (2 in this case)
a = b << 2	#shift the bits of an int left by an amount of times (2 in this case)
a = b | 2	#sets a to all the bits in b logical ORed with all the bits in 2
a = b & 2	#sets a to all the bits in b logical ANDed with all the bits in 2
a = a ^ 2	#sets a to all the bits in b logical XORed with all the bits in 2
a = ~ b	#sets a to all the bits in b switched (0s become 1, 1s become 0)

Files

Writing to a text file

with open("filename.txt", "w") as outputfile1:	#w for write, change to a for append to add to the bottom of an existing file
	outputfile1.write("Hello\r\n")
outputfile1.close()

Strings

Combining strings

print "abc" + "123"