Skip to content

Python basics

Nikolina Djekic edited this page Apr 10, 2020 · 1 revision

Table of contents

Comments

# this is a comment

Importing Modules

From what import what as alias 

#sys, os, datetime often used 
# Alias if defined instead of writing datetime, you can wtite dt if specified 

Strings

print("string") 
print('string') 
print("""String 
multiple lines""") 
print("string 1 " + "is awesome") 

Advanced strings

[0] #first letter 
[-] #last letter 
.split() #splits words into list 
.join 
# escaping \
.strip() # strip spaces
print("Sentence {}".format(variable)) #concatenating

Math

  1. */+- all supported
  2. ** exponents
  3. % modulo
  4. // -dividing without leftovers

Variables & Methods

variable_name = value 
#Method call with dot . Ex. 
value.upper()
 
.upper()
.lower()
.title()
.len(variable) #broj karaktera
.int() #returns integer, does not round!
.float() # returns float
.type()

Functions

#defining functions
def function_name(params): 
    variables with indentation 

# Calling function 
function_name(params) 

Boolean Expressions

True, False

Relational operators

AND OR

Conditional Statements

if:
 else: 

if:
 elif:
 else: 

Lists

  1. []
  2. Live in brackets
  3. Can be changed
list_name = [list_items, "separated by comma"] 
# [index] - starts from 0 
# [start_index:end_index] 
# [start:] - everything after starting index 
# [:stop] - everything until stop index 
# [-1] - very last item 
.len() 
.append(what) #at end 
.pop(index) #delete last or (index) 

Tuples

  1. ()
  2. Unchangeable
  3. Can just be printed or read
tuple_name = (list_items, 'separated by comma') 

Dictionaries

  1. {}
  2. Key, value
var_name = {key:value, key:value, key: [values, values]} 
employees[key] = [value]  # adding
.update({"key": [values]}) # adding 
.get(key)  # returns value 

Looping

for x in list:
   print(x)

while condition: 
  # what_happens 
  iteraror ++ 

Sockets

  1. To connect 2 ports together
  2. Connecting ports and ip addreses
  3. Connect to open port etc.
s= socket.socket(socket.AD_INET, socket.SOCK_STREAM) 
Clone this wiki locally