Python

From ScienceZero
Revision as of 12:17, 2 October 2017 by Avi (Talk | contribs) (Generating random values)

Jump to: navigation, search

Application

File Header

#!/usr/bin/python

Comments

These begin with the # character

Libraries

these go under the file header and in the format of

import libraryname

or

from libraryname import sublibraryname

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

Arithmetic functions

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)

Generating random values

import random

print random.randint(1, 5)	#prints a random whole number between 1 and 5

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")	#\r\n creates a new line, so whatever is written next will be on a new line
outputfile1.close()

Strings

Combining strings

print "abc" + "123"