Introduction
We all know this: just the moment you begin to like your newly learned programming language, your boss comes around and wants you to work on something completely different. Sure, concepts are similar or even identical - but as we all know: each language has their own peculiarities and for getting started, you are mostly just interested in those and the syntax.
This post wants to achieve exactly that: giving you a brief overview of the most important syntax and concepts in Python as compact as possible.
General
- Python is an interpreted language.
- Python uses indentation instead of brackets, so format your code properly!
- Whitespaces matter
- No strong typing
Comments
# This is a comment
There is no intended way for a multiline comment like for example /* ... */
in Java. However, we can use docstrings in that case. Note, that here the indentation also matters!
def addNumbers(num1, num2, num3):
"""
A function that returns the sum of
3 numbers
"""
return num1 + num2 + num3
Variables
General
-
Creation
x = 5 y = "Hello k = 5.2
In case you have a long integer value (e.g. 1.000.000), you can also write it like this
1_000_000
. -
Casting
If you want to specify the data type, this can be done using casting:
y = str(3) x = float(7) z = int(5)
-
Type
Thetype
function returns the data type of the variable
print(type(y))
-
Illegal names
Variables can not start with a number, contain a letter or empty space:
2myvar = "John" my-var = "John" my var = "John"
-
Naming convention
The right way to name them is to use
snake_case
:
myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John"
Data types
Data type | Example |
---|---|
str | x = "Hello World" |
int | x = 20 |
float | x = 20.5 |
complex |
x = 2j (j is the imaginary part) |
bool |
x = True (true does not work!) |
bytes | x = b"Hello" |
Strings
-
Multiline
a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."""
-
Strings are arrays
Strings in Python are arrays of bytes representing unicode characters. Square brackets can be used to access elements of the string:
a = "Hello, World!" print(a[1])
-
Looping over Strings
Since strings are arrays, we can loop over the single characters using a
for
loop.
for x in "foo": print(x)
Getting the length:
len(a)
-
Check for a word
To check for a certain phrase or character in a string, we can use
in
:
txt = "The best things in life are free!" print("free" in txt) # Used in a if-case if "free" in txt: print("Yes, 'free' is present.")
-
Slicing
a = "Hello, World!" # Get the characters from position x to position y (not included) print(a[x:y]) # Get the characters from the start to position x (not included) print(a[:x]) # Get the characters from position x, and all the way to the end print(a[x:])
-
Splitting
# returns ['Hello', ' World!'] print(a.split(","))
-
Upper/Lower case
a.upper() a.lower()
-
Remove whitespace
a = " Hello, World! " # returns "Hello, World!" print(a.strip())
-
Replace
print(a.replace("H", "J")) # returns "Jalllo, World!"
-
Concatenation
c = a + " bla " + c0
But be careful with numbers!
# You can't do: age = 36 txt = "My name is John, I am " + age print(txt) # Instead: age = 36 print("My name is John, and I am" + format(age))
Operators
The standard ones and also
-
x ** y
→ Exponentiation -
x // y
→ Floor division (cuts after the comma, e.g.3 // 2 = 1
)
Conditional statements and loops
break
and continue
are supported.
# if
if b > a:
print("b is greater than a")
else:
print("Nix.")
# while
i = 1
while i < 6:
print(i)
i += 1
# for
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Data collections
There are no classical arrays (Array = List).
Data Type | Example | Particularities |
---|---|---|
list | x = ["apple","banana","cherry"] |
List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0] , the second item has index [1] etc. |
dict | x = {"name" : "John", "age" : 36} |
Key-Value-Pairs, ordered (from v3.7 on) |
set |
x = {"apple", "banana", "cherry"} x = frozenset({"apple","banana","cherry"})
|
A set is a collection which is both unordered and unindexed. Set items are unordered, unchangeable, and do not allow duplicate values. But: Once a set is created, you cannot change its items, but you can add new items. To prevent this, you can use a frozenset
|
tuple | ("apple", "banana", "cherry") |
Tuple items are ordered, unchangeable, and allow duplicate values. Tuples are unchangeable. Can only be accessed with foreach . |
Lists
Access items:
thislist[5]
Change item:
thislist[1] = "blackcurrant"
-
Inserting
- Append items:
thislist.append("orange")
- Insert at certain position:
thislist.insert(1, "orange")
-
Append elements from another list to the current list:
thislist.extend(anotherList)
The
extend()
method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
- Append items:
-
Removing
# remove specified item thislist.remove("banana") # remove specified index thislist.pop(1) # you can also leave away the index to remove the last element # or: del thislist[1] # empty the list thislist.clear() # delete entire list del thislist
-
Loop through a list
-
foreach
for x in thislist: print(x)
-
for
for i in range(len(thislist)): print(thislist[i])
-
-
Sorting
thislist.sort()
You can pass
reverse = True
as an argument. count()
→ Number of Elements in the List
Dicts
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
# or:
x = thisdict.get("model")
# return a list of all the keys in the dictionary:
x = thisdict.keys()
# add entry
thisdict["color"] = "white"
# remove entry
thisdict.pop("model")
# remove last item
thisdict.popitem()
Functions
def my_function(fname):
print(fname + " Doe")
return fname
my_function("John")
Function definitions cannot be empty, but if you for some reason have a definition with no content, put in the pass
statement:
def myfunction():
pass
Object orientation
-
Create a class
class MyClass: x = 5
-
Create an object
p1 = MyClass() print(p1.x)
-
__init__()
-Function (= Constructor)
class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name)
-
Inheritance
# Superclass class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) # Subclass class Employee(Person): pass
Top comments (0)