January 28, 2025

Tirth's Blog

My technical notes

Python primer to revise Python language elements.

Following Python code gives basic understanding about language elements. This way anyone can quickly refresh the basic syntax for elements. 

 

# This is basic Python primer program that will be used to understand
# language’s basic elements and structures.
# INDENTATION

for i in range(5):
  print(i)
print('done')

for i in range(5):
  print(i)
  print('done')

# Strings

print('this is string');
print("this is also string");

# Variable
var1=10;
var2='ten';

#comment single line
""" this is

multi line
comment
"""

#printing
print('Hello World');
print('Value is ', var1);
print('Value is ', var2);

# data structures
#dictionary -- associative array
a2 = {'one':1, 'two':2, 'three':3}

# lists -- ordered arrays
a3=[101,4,7,50,32]

# lists can be accessed via index.
print(a3[0]);
print(a3[-1]);
print(a3[3]);
print(a3[4]);
print(a3[3:5]);
print(a3);

#tuples like lists but they cannot be changed once created. they are creared with parenthesis.
a4=(3,7,10);

# individual values in tuple can be assigned to variables like :
v1,v2,v3=a4

print('v1=', v1);
print('v2=', v2);
print('v3=', v3);

# The value in a single entry tuple like "(13,)" can be assigned to a variable by putting a comma
# after the variable name like:
v1,=(13,)

#if the assignment is
v1=(13,)
print(v1);

# then v1 will contain the whole tuple"(13,)"

### Objects

# Everything in python is an object. as a3 list we have before, that is an object.
print(a3);
a3.append(25);
print(a3);

# Flow control if-elif-else statement, "or" "and", "=="
v=1
if v == 2 or v == 4:
  print('Even')
elif v == 1 or v == 3:
  print('odd')
else:
  print('Unknown Number')

##Loops
for i in range(10):
  print(i)
a5=['Aa', 'Bb', 'Cc']
for c in a5:
  print(c)

## functions, Functions may or may not return values.
#A function may be defined as:
def myfunc(p1, p2):
  "Hello : add two numbers"
  print(p1, p2)
  return p1 + p2
v10=myfunc(10,2)
print(v10)

#Functions are also objects and have attributes.
#The inbuilt __doc__ attribute can be used to find the function description:
print(myfunc.__doc__)

#Modules
#Sub-files can be included in Python scripts with an import statement.
#Many predefined modules exist, such as the os and the sys modules.

import os
import sys

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © All rights reserved. | Newsphere by AF themes.