Вы находитесь на странице: 1из 2

Quick Start Python for Java Programmers

First things first: go through the Python tutorial. Yes, you will spend a few minutes of your life printing
out 1+1. But you will also discover some tricks that will save you time over the course of the semester.
It’s worth the investment.

In the spirit of helping people get a quicker start…here is an attempt at giving you some basic rules and
some gotchas to avoid.

A couple of things to realize upfront:

1. Python uses indenting rather than braces to indicate that a statement is inside a
method/loop/what-have-you
2. You can use either spaces or tabs to indent, but you *should not* mix them (it may result in
either errors or crazy misinterpretations of your code). When you copy things from webpages or
else where you may find you need to fix the indenting.
3. Semi colons aren’t required
4. There’s no difference between “ and ‘
5. There’s no static typing, so you don’t have to declare what something is, you just use it. Note:
there’s one exception here. If you want to use a global variable then you need to declare it (see
tutorial for more info)

A few basics:

Printing print “hello”


Assignment x=x+1
Lists list = [“a”, “b”, “c”, “d”]
x = list[0] ( to get the values inside)
Count loop for i in range (1,5):
print i
Iterating over a list for listItem in list:
print listItem
Conditionals if x < 3:
print “less than 3”
elif x ==4:
print “is 4”
else:
print “greater than 4”
While while x<3:
print “less than 3”
Things related to classes:

Defining a class class Blah(SuperClass):


def __init__(self):
# any initialization stuff goes here
var1 = 1 # local variable to init
self.var2 = 2 # class variable

def yourmethod( self, anyOtherParams):


# you always need self as the first param in a class method
# method implementation
Instantiating a class b = Blah()
Calling a method b.yourmethod(anyOtherParams)
Optional parameters def yourmethod( self, anyOtherParams=3):
# you can include a default value for parameters

If I call b.yourMethod() then anyOtherParams will be 3


If I call b.yourMethod(5) then anyOtherParams will be 5

The “self” is the python version of Java/C++ “this”. It needs to be


there in all of the declarations. But when you call a method, the
object the method is invoked on (e.g. b in the two examples
above) is passed as the first parameter automatically.

Вам также может понравиться