DEV Community

André N. Darcie
André N. Darcie

Posted on

Python in one page

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

To focus on the language itself this guide not includes any built-in modules like math, random, datetime, json, re, random, etc

Getting Started

Coding

Make a simple hello world

print('Hello, World!') # Hello, World!
Enter fullscreen mode Exit fullscreen mode

Help

help(print)
# Prints the values to a stream, or to sys.stdout by default.
Enter fullscreen mode Exit fullscreen mode

User Input

name = input("Enter your name:")
print("Your name is: " + name)
Enter fullscreen mode Exit fullscreen mode

Run a python file
python helloworld.py

Comments

#This is a comment
print('Hello, World!')
Enter fullscreen mode Exit fullscreen mode

Variables

name = 'John'
age = 42

x, y, z = 1, 2, 3

print('Name: ' + name) # Name: John
Enter fullscreen mode Exit fullscreen mode

Data Types

# Text
string = 'Hello World'

# Numeric
integer = 20
float = 20.5
complex = 1j

# Sequence
list = ['apple', 'banana', 'cherry']
tuple = ('apple', 'banana', 'cherry') # Unchangeable
range = range(6)

# Mapping
dictionary = {'name' : 'John', 'age' : 36}

# Set - No duplicate members
set_value = {"apple", "banana", "cherry"}
frozenset_value = frozenset({"apple", "banana", "cherry"})

# Boolean
boolean = True

# Binary
bytes = b"Hello"
bytearray = bytearray(5)
memoryview = memoryview(bytes(5))

print(type(string)) # <class 'str'>
print(int('1')) # constructs an integer number

# Represents a null value
x = None
print(x) # None
Enter fullscreen mode Exit fullscreen mode

Strings

hello = 'Hello, World! '
print(hello[0]) # H
print(hello[-1]) # !
print(hello[2:5]) # llo
print(len(hello)) # '13' get string length
print(hello.strip()) # 'Hello, World!' removes whitespaces
print(hello.lower()) # hello, world!
print(hello.upper()) # HELLO, WORLD!
print(hello.replace("H", "A")) # Aello, World!
print(hello.split(",")) # ['Hello', ' World!']

# Membership Operators
print("Hello" in hello) # True
print("Hello" not in hello) # False

print('Hello, ' + 'World!') # Hello, World!
print("{0}, World!".format('Hello')) # Hello, World! 
Enter fullscreen mode Exit fullscreen mode

Arithmetic

x, y = 1, 2
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print(x % y) # Modulus
print(x ** y) # Exponentiation
print(x // y) # Floor division

x += 3 # Same as x = x + 3
Enter fullscreen mode Exit fullscreen mode

Comparison

x, y = 1, 2
print(x == y) # Equal
print(x != y) # Not equal
print(x > y) # Greater than
print(x < y) # Less than
print(x >= y) # Greater than or equal to
print(x <= y) # Less than or equal to

if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

# Assert is used when debugging code
assert x == 2 # AssertionError is raised
Enter fullscreen mode Exit fullscreen mode

Logical

x = 2
print(x == 2 and x > 42) # True
print(x == 2 or x > 42) # True
print(not(True)) # False
print(not(False)) # True
Enter fullscreen mode Exit fullscreen mode

Identity

x = 'Hello'
z = x
y = 'World'

print(x is z) # True
print(x is y) # False
print(x == y) # False
Enter fullscreen mode Exit fullscreen mode

Collections (Arrays)

list = ['hello', 'world']
print(list)
print(list[1])
print(list[-1])
print(list[2:5])
print(list[:4])
print(list[2:])
list[1] = "!"
print(thislist)

for x in thislist:
  print(x)

if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

print(len(thislist))

list.append("orange") # Adds an element
list.clear() # Removes all the elements
mylist = list.copy() # Returns a copy of the list
list.count() # Number of elements
list.extend(['apple']) # Add the elements of a list
list.index() # Returns the index
list.insert(1, "orange") # Adds an element at 
# the specified position
thislist.pop() # Removes the element
thislist.remove("banana") # Removes the first item
list.reverse() # Reverses the order
list.sort() # Sorts the list
del thislist[0]

mylist = thislist.copy()
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
thislist = list(("apple", "banana", "cherry"))
Enter fullscreen mode Exit fullscreen mode

Sets

thisset = {"apple", "banana", "cherry"}
thisset.add("orange") # Add an item
thisset.update(["orange", "mango"]) # Add multiple items
print(len(thisset))
thisset.remove("banana")
set3 = set1.union(set2)
set1.update(set2)
Enter fullscreen mode Exit fullscreen mode

Dictionaries

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]
print(thisdict)
thisdict["year"] = 2018

for x in thisdict.values():
  print(x)

for x, y in thisdict.items():
  print(x, y)

if "model" in thisdict:
  print("Yes")

thisdict["color"] = "red" # Adding an item
thisdict.pop("model") # Removes the item
thisdict.popitem()
Enter fullscreen mode Exit fullscreen mode

If ... Else

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

# Short Hand
if a > b: print("a is greater than b")
print("A") if a > b else print("B")
Enter fullscreen mode Exit fullscreen mode

Loops

# While
while i < 6:
  print(i)
  i += 1
  # break - can stop a loop
  # continue - continue with the next

# For
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

for x in range(6):
  print(x)

# Function continues execution immediately 
# after the last yield run
def number_generator(): 
    yield 1
    yield 2

for number in number_generator():  
    print(number)

# Output: 1 2
Enter fullscreen mode Exit fullscreen mode

Functions

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

my_function()

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

my_function("Emil")

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
my_function(child1 = "Emil", 
            child2 = "Tobias", 
            child3 = "Linus")

# Default Parameter Value
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function()

def my_function(x):
  return 5 * x

print(my_function(3))
Enter fullscreen mode Exit fullscreen mode

Lambda

# lambda arguments : expression
x = lambda a : a + 10
print(x(5))
Enter fullscreen mode Exit fullscreen mode

Classes and Objects

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
p1.age = 40 # Modify Object Properties

# Inheritance
class Student(Person):
  pass # a statement that will do nothing

# Now the Student class has the same properties 
# and methods as the Person class
x = Student("Mike", "Olsen")
x.printname()
Enter fullscreen mode Exit fullscreen mode

Iterators

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
  print(x)

# Create an Iterator
class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Enter fullscreen mode Exit fullscreen mode

Scope

# Global variable
def myfunction():
  global x = "hello"

myfunction()

print(x) # can be accessed outside the function

# Non Local Variable
def myfunc1():
  x = "John"
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2()
  return x

print(myfunc1())
Enter fullscreen mode Exit fullscreen mode

Modules

Save this code in a file named mymodule.py

def greeting(name):
  print("Hello, " + name)
Enter fullscreen mode Exit fullscreen mode
import mymodule
# import mymodule from greeting 
# (import specific parts of a module)

mymodule.greeting("Jonathan")

# Create an alias for mymodule called mx
import mymodule as mx

a = mx.greeting("Jonathan")
Enter fullscreen mode Exit fullscreen mode

Math

x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)

print(abs(-7.25))
print(pow(4, 3))
Enter fullscreen mode Exit fullscreen mode

Try Except

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")
Enter fullscreen mode Exit fullscreen mode

File Handling

file = open("hello.txt", "r")
# r - Read
# a - Append
# w - Write
# x - Create

print(file.read())
print(file.readline())
file.close()

# Using with statement 
with open('hello.txt', 'w') as file: 
    file.write('hello world !')

# no need to call file.close() when using with
Enter fullscreen mode Exit fullscreen mode

All keywords

import keyword
keyword.kwlist
[ 'False', 'None', 'True', 'and', 'as', 'assert',
 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'finally', 'for', 'from', 'global',
 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
 'with','yield' ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)