0% found this document useful (0 votes)
17 views

Python For Java Developers Cheat Sheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python For Java Developers Cheat Sheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python for JAVA Developers: Basics V 1.2 Referring python 3.7.

1 Basic Syntax You declare multiple variables by separating each variable name
with a comma.

1.1 End of Statements a, b = True, False

Unlike the Java, to end a statement in Python, we don’t have to type


in a semicolon, you simply press Enter . But semicolons can be
2.2 Assigning Values
used to delimit statements if you wish to put multiple statements
on the same line. a = 300

message1 = ’Hello World!’


message2 = "Python gives no missing semicolon error!" The same value can be assigned to multiple variables at the same
time:
# Instead of System.out.print, we use print
print (message1) # print ’Hello World!’ on the console output a = b = c = 1

print ("Hello"); print ("Python!"); # usage of the semicolon


And multiple variables can be assigned different values on a single
line:
1.2 Code Blocks and Indentation a, b, c = 1, 2, "john"

One of the most distinctive features of Python is its use of inden-


This is the same as:
tation to mark blocks of code. Consider the following if-statement
from our non-zero number checking program: a = 1

JAVA b = 2
c = "john"
if (0 == value) {
System.out.print("Number is Zero");
} else {
System.out.print("Number is non-Zero."); 3 Data Types
}

Python sets the variable type based on the value that is assigned to
System.out.print("All done!");
it. Unlike JAVA, Python will change the variable type if the variable
value is set to another value.
Python
var = 123 # This will create a number integer assignment
if 0 == value:
var = ’john’ # the ‘var‘ variable is now a string type.
print(’Number is Zero’)
else:
print(’Number is non-Zero.’)
3.1 Numbers
print(’All done!’)
Most of the time using the standard Python number type is fine.
Python will automatically convert a number from one type to an-
To indicate a block of code in Python, you must indent each
other whenever required. We don’t require to use the type casting
line of the block by the same amount. The two blocks of code in
like JAVA.
our example if-statement are both indented four spaces, which is
a typical amount of indentation for Python.
Type Java Python Description
2 Variables int int a = 11 a = 11 Signed Integer
long long a = 1712L a = 1712L (L) Long integers
2.1 Declaration float float a = 19.91 a = 19.91 (.) Floating point values
complex --- a = 3.14J (J) integer [0 to 255]
Variables are created the first time a value is assigned to them.
There is no concept of the declaration of the data type in python.

number = 11
string = "This is a string"

© 2019 Akash Panchal - www.medium.com/@akashp1712


3.2 String Java ArrayList Python list

Create string variables by enclosing characters in quotes. Python list = new ArrayList() list=[]
uses single quotes 0
double quotes ” and triple quotes ””” list.add(object) list.append(object)
to denote literal strings. Only the triple quoted strings ””” will list.get(i) list[i]
automatically continue across the end of line statement. list.size() len(list)
list2= list.clone() list2=list[:]
firstName = ’Jane’
lastName = "Doe"
message = """This is a string that will span across multiple
lines. Using newline characters and no spaces for the
next lines."""
3.5 Tuple
Key Methods:

A tuple is another useful variable type similar to list and can contain
Java Python
heterogeneous values. Unlike the list, a tuple is immutable And is
charAt() find() like a static array.
indexOf() index()
A tuple is fixed in size and that is why tuples are replacing
length() len()
array completely as they are more efficient in all parameters.
replace() replace()
toString() str() Tuple can be used as an alternative of list(python/Java) OR
trim() rstrip(), lstrip() Array(Java) with respect to the use cases. i.e, If you have a
dataset which will be assigned only once and its value should not
Python String comparison can be performed using equality (==)
change again, you need a tuple.
and comparison (<, >, !=, <=, >=) operators. There are no special
methods to compare two strings. Tuple variables are declared by using parentheses () follow-
ing the variable name.
3.3 Boolean A = () # This is a blank tuple variable.
B = (1, 23, 45, 67) # creates a tuple of 4 numbers.
Python provides the boolean type that can be either set to False or
C = (2, 4, ’john’) # can contain different variable types.
True. In python, every object has a boolean value. The following D = ("A", B, C) # can contains other tuple objects as well.
elements are false:

• None

• False
3.6 Dictionary
• 0

• Empty collections: “”, (), [], Dictionaries in Python are lists of Key: Value pairs. This is a very
powerful datatype to hold a lot of related information that can be
All other objects are True. Note that, In JAVA null is not false associated through keys. Dictionary in Python can be the Alter-
while in python None is. native of the Map in JAVA. But again a Dictionary in python can
contain heterogeneous key as well as value.
3.4 List room_num = {’john’: 121, ’tom’: 307}
room_num[’john’] = 432 # set the value associated with the
The List is one of the most powerful variable type (data structure!)
’john’ key to 432
in Python. A list can contain a series of values. Unlike JAVA, the print (room_num[’tom’]) # print the value of the ’tom’ key.
list need not be always homogeneous. A single list can contain room_num[’isaac’] = 345 # Add a new key ’isaac’ with the

strings, integers, as well as objects. Lists are mutable. associated value


print (room_num.keys()) # print out a list of keys in the
List variables are declared by using brackets [] following the
dictionary
variable name. print (’isaac’ in room_num) # test to see if ’issac’ is in the
dictionary. This returns true.
A = [] # This is a blank list variable.
B = [1, 23, 45, 67] # creates an initial list of 4 numbers.
hotel_name = {1: "Taj", "two": "Woodland", "next": 3.14} #
C = [2, 4, ’john’] # can contain different variable types.
this is totally valid in python
D = ["A", B, C] # can contains other list objects as well.

Key Methods: Key Methods:

© 2019 Akash Panchal - www.medium.com/@akashp1712


Java HashMap Python Dictionary 5 Conditionals
Map myMap = new HashMap() my_dict = { }
clear() clear() 5.1 if
clone() copy()
containsKey(key) key in my_dict var1 = 250
if 250 == var1:
get(key) get(key)
print ("The value of the variable is 250")
keySet() keys()
put(key, value) my_dict[key] = value
remove(key) pop(key)
size() len(my_dict) 5.2 if..else

4 Operators var1 = 250


if 0 == var1:
MyLayerColor = ’vbRed’
4.0.1 Operator Precedence MyObjectColor = ’vbBlue’
else :
Operator Precedence is same as that of JAVA, let’s revise it in
MyLayerColor = ’vbGreen’
python. Arithmetic operators are evaluated first, comparison oper- MyObjectColor = ’vbBlack’
ators are evaluated next, and logical operators are evaluated last.
Arithmetic operators are evaluated in the following order of print (MyLayerColor)

precedence.

JAVA Python Description 5.3 if..elif..elif..else


NOT AVAILABLE ** Exponentiation
var1 = 0
- - Unary negation
if 0 <= var1:
* * Multiplication print ("This is the first " + str(var1))
/ / Division elif 1 == var1:
% % Modulus arithmetic print ("This is the second " + str(var1))
elif 2 >= var1:
+ + Addition
print ("This is the third " + str(var1))
- - Subtraction else:
print ("Value out of range!")
Logical operators are evaluated in the following order of prece-
dence.

JAVA Python Description 5.4 Multiple conditions


! not Logical negation
skill1 = "java"
& & Logical conjunction
skill2 = "python"
| | Logical dis-junction
∧ ∧ Logical exclusion if skill1 == "java" and skill2 == "python":
&& and Conditional AND print ("Both the condition satisfy")

|| or Conditional OR
if skill1 == "java" or skill2 == "python":

Comparison operators all have equal precedence; that is, they print ("At least One condition satisfies")

are evaluated in the left-to-right order in which they appear.

JAVA Python Description


6 Looping
< < Less than
> > Greater than 6.1 For Loop
<= <= Less than or equal to
Python will automatically increments the counter (x) variable by 1
>= >= Greater than or equal to
after coming to end of the execution block.
== == Equality
!= != Inequality for x in range(0, 5):
print ("It’s a loop: " + str(x))
equals is Object equivalence

Note: == in python is actually .equals() of Java. Increase or decrease the counter variable by the value you
specify.

© 2019 Akash Panchal - www.medium.com/@akashp1712


# the counter variable j is incremented by 2 each time the codes = {’INDIA’: ’in’, ’USA’: ’us’, ’UK’: ’gb’}
loop repeats for key, value in codes.iteritems():
for j in range(0, 10, 2): print (key, ’corresponds to’, value)
print ("We’re on loop " + str(j))
# Note: key, value are just the variable names.
# the counter variable j is decreased by 2 each time the loop
repeats
for j in range(10, 0, -2):
print ("We’re on loop " + str(j))
8 The End

You can exit any for loop before the counter reaches its end That’s all Folks.
value by using the break statement. This ebook is made using Overleaf.
The source can be found on ‡.

6.2 While Loop Thanks to ¯ Piyush Joshi for all the guidance for this project.

Simple example of while loop.

var1 = 3
while var1 < 37:
var1 = var1 * 2
print (var1)
print ("Exited while loop.")

Another example of while loop with break statement.

while True:
n = raw_input("Please enter ’hello’:")
if n.strip() == ’hello’:
break

7 Iterations

7.1 Iterating a List

friends = [’Huey’, ’Dewey’, ’Louie’]


for friend in friends:
print (’Hello ’, friend)
print (’Done!’)

7.2 Iterating a Tuple

tup = (’alpha’, ’beta’, ’omega’)


for val in tup:
print (val)

7.3 Iterating a Dictionary

codes = {’INDIA’: ’in’, ’USA’: ’us’, ’UK’: ’gb’}


for key in codes:
print (key, ’corresponds to’, codes[key])

# Note: key is just a variable name.

The above will simply loop over the keys in the dictionary, rather
than the keys and values.
To loop over both key and value you can use the following:

© 2019 Akash Panchal - www.medium.com/@akashp1712

You might also like