Menu-Submenu

Getting Started with Python


Getting Started with Python


#) Few Python information
  • Guido van Rossum The invetor of Python
  • Chevron prompt Python Interpreter (for Interactive Python in Commandline) Ctrl+Z or quit or >>> exit() )
  • Atom.io Programmer Text Editor


 #) Checking Python Version: this opens chevron prompt
> python --version
> python3 –version (on Mac OS)



#) Running a python script/code
> cd my_code_dir (on Windows OS)
> python first_script.py OR     > first_script.py



Elements of Python
#) - Sentence structure as Valid syntax patterns- Vocabulary / Words   as Variable names / identifiers and Reserved words
(Different kinds of syntax with combination of Variables, Operator, Constant, Function)
- Story structure as Constructing a program for a purpose,
Program Steps or Program Flow with various statements
Statements like: Sequential, Conditional, Repeated/Loop, Stored & reused steps/Function


#) Comments in Python
Symbol '#' is used at beginning to start a comment


#) Constants
  • Constants are fixed values such as:  Numbers, Letters and Strings (in single or double quotes)


 #) Reserved Words
False True and assert
break class      if def
elif else return for
global try import in
is while not or
finally continue


None as del except
from lambda pass raise
nonlocal with yield


#) Variables
x = 12.2 means 12.2 assigned to x


Rules for variable 
  • Must start with letter or underscore
  • Must consist letters, numbers and underscores
  • Case sensitive (lowercase, UPPERCASE, Camelcase are different)
  • Mnemonic technique for sensible variable name


 #) Sentences or Lines may contain either
  • Assignment statement
  • Assignment with expression
  • Function statement
  • combination of Variable Operator Constant Function

Assignment statement
variable = expression on right-hand side

#) Numeric Expressions
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder or Modulo

Operator Precedence / Order of Evaluation
Parenthesis   , Power ,   Multiplication/Division/Modulo   , Addition/Subtraction , Left-to-Right


  • In Python, variables, literals and constants have a "type"
  • Python knows what "type" everything is
>>> iii = 3 + 1
>>> print(iii) o/p => 4
>>> sss = 'hello ' + 'world!'
>>> print(sss) o/p => hello world!
>>> print('hello','there') o/p => hello there 
>>> type(1) o/p => <class 'int'>
>>> type(iii) o/p => <class 'int'>
>>> type('hello') o/p => <class 'str'>
>>> type(sss) o/p => <class 'str'>
>>> sss = sss + 1 o/p => TypeError Traceback


#) Types of Numbers
  • Integers are whole numbers
  • Floating point numbers have decimal parts
  • other number types variations of float and integer


  • Floating point number has more range, but less precision (compare to Integer numbers)
>>> type(1.0) o/p => <class'float'>
>>> fff = 98.6
>>> type(fff) o/p => <class'float'>



#) Type Conversions
  • When there is an integer and float point in an expression, then integer is implicitly converted to a float
  • explicit conversion is done with built-in functions: int(), float()


 >>> print(99 + 100) o/p => 199
>>> print(float(99) + 100) o/p => 199.0
>>> iii = 42 
>>> type(iii) o/p => <class'int'>
>>> fff = float(iii)
>>> printf(fff) o/p => 42.0
>>> type(fff) o/p => <class'float'>



#) Integer Division
  • Integer division produces a floating point result (in Python 3)
[ While in Python 2, Division was different , which just produces quotient. This is one of the bigger non-upwards-compatible changes in Python 3]


>>> print(10 / 2) o/p => 5.0
>>> print(9 / 2) o/p => 4.5
>>> print(99 / 100) o/p => 0.99
>>> print(10.0 / 2) o/p => 5.0
>>> print( 9 / 2.0) o/p => 4.5
>>> print(99.0 / 100.0) o/p => 0.99


#) String Conversions
  • Functions to convert between strings and integers: int() and float()
  • Python generate error when string doesn't contain numeric character to convert


>>> sss = '123'
>>> type(sss) o/p => <class'string>
>>> print(sss + 1) o/p => TypeError Traceback
>>> iii = int(sss)
>>> type(iii) o/p => <class'int>
>>> print(iii + 1) o/p => 124
>>> sss = 'hello world'
>>> iii = int(sss) o/p => ValueError Traceback


  • Comma in print() automatically produces the space



#) Comparison Operators
Python Meaning
< Less than
<= Less than or Equal to
== Equal to
>= Greater than or Equal to
> Greater than
!= Not equal


is similar to but more powerful than ==   Especially used for comparison with None/True/False
is not similar to but more powerful than !=    Especially used for comparison with None/True/False


  • These logical operators and returns True/False






#) 'None' in Python
  • Python has a None type with only constant 'None'.
  • It distinctly detects different than numbers.
  • It is like a flag, but different than True / False.
  • It indicates absence of value or lack of value.



 #) User Input
input(): function to pause & read data from the user, returns a string
>>> name = input("Enter your name: ")
>>> print('Welcome' , name , "to here") o/p => Welcome Alice to here



Converting User Input
>>> sss = input('Enter a number to double: ')
>>> iii = int(sss) * 2
>>> print("It's double number is" , iii) o/p => It's double number is 56


>>> xh = input("Enter Hours: ")
>>> xr = input("Enter Rate: ")
>>> xp = float(xh) * float(xr)
>>> print("Pay:" , xp)





#) Block of code with <indent> in Python 
  • <indent> can be of any length, but 4 spaces are preferable.
  • Continuous <indent> statements make a block of code
  • Either to use spaces or tab, but not both together. (ATOM editor has setting to converts tabs into spaces while saving file with ".py" extension)


 Conditional Steps
 if x < 10:
<indent> print("x value is", x)
<indent> print("x is Smaller than 10")

Repeated Steps / Loops
n = 5 (start)
while n > 0: (check)
<indent> print(n)
<indent> n = n - 1 (change)


 file_name = input('Enter filename: ')
file_handle = open(file_name)
for line in file_handle:
<indent> print("Line content -> " + line)



#) Conditional Statement


One-way decision :
if x < 0 :
print("Negative")



Two-way decisions :
if x > 2 :
print("Bigger")
else :
print("Smaller")



Multi-way/Nested decisions :
if x < 2 :
print("small")
elif x < 10 :
print("Medium")
else :
print("LARGE")


Multi-elif Multi-way decisions :
if x < 2 :
print("small")
elif x < 10 :
print("Medium")
elif x < 20 :
print("Big")
elif x < 40 :
print("LARGE")
else :
print("HUGE")
    


No-Else Multi-way decisions :
if x < 2 :
print("small")
elif x < 10 :
print("Medium")

#) Try/Except Structure
  • For error handling, surround a section of code with 'try - except'
  • If code in the 'try' works properly (without any traceback), then 'except' is skipped
  • If code in the 'try' fails (with a traceback), then it jumps to the 'except' section



without try-except
sss = "Hello bob"
iii = int(sss) o/p => ValueError Traceback here without heading further
print('Number 1:' , iii)


sss = "123"
iii = int(sss)
print('Number 2:' , iii)


  
with try-except
sss = "Hello bob"
try:
iii = int(sss) <= on Traceback within 'try', skipped further sequential statements & execute 'except' block
print("Conversion done")
except:
iii = -1
print("Reset value")
print('Number 1:' , iii)

sss = "123"
try:
iii = int(sss) <= on Traceback within 'try', skipped further sequential statements & execute 'except' block
print("Conversion done")
except:
iii = -1
print("Reset value")
print('Number 2:' , iii)



#) Store (and reuse) Steps or Functions
  • Reusable code
  • Functions are things for storing & reusing. A Function is some stored code to use, which takes some input and produces an output.
  • Naming conversions for function names are same as for variables, and must avoid things like reserved words & etc
  • There is no output/execution of any function, until it is called/invoked

Writing own Functions
  • Create a new function using the 'def' keyword followed by optional parameters in parentheses
  • Indent the body of function
  • This defines the function, but doesn't execute the body of the function unless it is called/invoked

Function (with optional arguments)
def func():
print("Hello")
print("Fun")


func()
print("Again")
func()

Function with arguments OR Parameters to Function
  • Parameters are alias of passed arguments

def greet(lang):
if lang == 'es':
print('Hola')
elif lang == 'fr':
print('Bonjour')
else:
print('Hello')
        
>>> greet('en') o/p => Hello
>>> greet('es') o/p => Hola
>>> greet('fr') o/p => Bonjour


Function with return value
def max(inp):
statements #p
statements #q
Use of inp
statements #r
statements #s
return 'w'
    
>>> big = max('Hello world')
>>> print(big)


def greet():
return "Hello"
print(greet() , "Alice") o/p =>Hello Alice
print(greet() , "Bob") o/p =>Hello Bob

Function with Multiple Parameters/Arguments
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x) o/p => 8








#) Repeated Steps
  • Iteration variable is important part of any loop (which needs to be changing within body of loop, most of the time)

Indefinite Loop with 'while'
n = 5
while n > 0 : <= n is iteration variable
print(n)
n = n - 1
print(n)



Finite Loop with 'for'
for i in [5, 4, 3, 2, 1] : <= Simple definite loop using 'for'
printf(i)
arr = ['ABC', 'XYZ', 'PQR']
for str in arr :
print('String is' , str)

#) Breaking Out of a Loop
break statement : it is the loop test within body of a loop, that ends the current loop and jumps to statement immediately following that loop


while True:
line = input('> ')
if line == 'done' :
break
print(line)
print('Done!')



continue statement : ends the current iteration and jumps to the top of the loop to start next iteration
while True:
line = input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print(line)
print('Done!')



Reference:

  1. https://www.coursera.org/learn/python Programming for Everybody (Getting Started with Python)
  2. https://www.py4e.com/ PY4E - Python for Everybody
  3. http://www.pythonlearn.com/ Python for Everybody: Exploring Data in Python3