Skip to main content

/docs/images/banner.jpg

Python

Basics

Variables

x = 10
y = 15
print(x + y)

output

25

Comments

# This is a comment
print("Hello, World!")

output

Hello, World!

Data Types

x = 5
print(type(x))

output

<class 'int'>

Casting

x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Strings

a = "Hello, World!"
print(a)
print(a[1]) # print character at index 1

output

Hello, World!
e

If statement

a = 33
b = 200
if b > a:
print("b is greater than a")

output

b is greater than a

Elif

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

output

a and b are equal

Loops

While loop

i = 1
while i < 6:
print(i)
i += 1

output

1
2
3
4
5

For loop

syntax: for x in range(start,stop,step)

i = 1
for i in range(6):
print(i)

output

1
2
3
4
5

Nested loop

i = 1
j = 1
for i in range(2):
for j in range(2):
print(i, j)

output

0 0
0 1
1 0
1 1

Break statement

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

output

1
2
3

Functions

def my_function():
print("Hello from a function")

my_function()

output

Hello from a function

Functions with arguments

def my_function(fname):
print("Hello "+fname)

my_function("Name")

output

Hello Name

Functions with return

def my_function(x):
return 5 * x

print(my_function(3))

output

15