22 February 2017

Python | Basic Syntax And Rules

Indentation

  • Very important! in Python indentation is relevant! see this examples:
  • Indentation is correct!
    Wrong indentation gives different result

Operators

  • To check if one variable is exist in another variable, use in
  • To check if a variable is equal to a specific value, use is
  • in and is
  • In python, 5 ** 3 means 5 to the power of 3 and it will return 125 as a result
  • In python and most of programing languages, \n means 'new line'. But how if we want to print out a path like this "C:\Arkad\Desktop\notepad"? if you write print("C:\Arkad\Desktop\notepad") you'll get this result:
  • \n means newline
    To avoid this, put 'r' before the quote sign. like this print(r"C:\Arkad\Desktop\notepad")
    put 'r' before the quote sign
  • In Python you can do 'multiplication' operations with strings name = "John" and name * 5 this will return "John John John John John"
  • To create an array or a list, variable = [12 , 15 , 10 ]
  • To add elements to a list, variable + [10 , 9]
  • how to add items to a list
  • In Python, colon operator like this variable[0:2] will return the first and second elements of the list. it means index '2' is not included. This is different to e.g. Matlab where an array is started with number '1' and the colon operator include the number coded

String format

  • The number inside the curly brackets refers the index of the arguments inside the round brackets. '0' means the first argument etc.
  • '{2}' means 'third argument'

Looping

  • For loop in Python can be very flexible. Look at this code: