You are on page 1of 23

Introduction to Python

Programming
Indentation
• When you write a code in python remember to do the correct
indentation
• See the following fragment
Correctly indented python code fragment.
if 5>2:
print(“Five is greater than two”)
• Incorrect indentation of python program leads to an error
if 5>2:
print(“Five is greater than two”)
print('A')
print('B')
for i in range(5):
print('C')
print('D')
print('E')
Python Variables
• A variable is created the moment you assign a value to
it.
>>> x =5
>>> y = “Hello World”
>>> print(x)
>>> print(y)
In python no need of variable declaration as in other
languages.
The data type is automatically assigned when we
initialize the variable.
Casting
To cast the type of variables in python
>>> x=3
>>> x = str(x)
>>> y = int(4)
>>> z = float(5)
To get the type of a variables
>>> print(type(x))
 string can be in single quote (‘) or Double quote(“)
Python is case sensitive.
Q=34
q=“Sally”
 In python we can assign multiple values
example
x, y, z = “Orange”, “Banana”, “Cherry”
print(x)
print(y)
print(z)
 And one value to multiple variables
example
x = y = z = “Orange”
Unpacking a collection
Fruits = [“Orange”, “Banana”, “Cherry”]
x, y, z = fruits
this will assign the values of the list to the
variables x, y, and z.
Output variables
x = “awesome”
print(“Python is ”+ x)
X= “python is”
Y = “awesome”
Z = X+Y
print(Z)
Comments in Python
 Comments in python begin with # sign
example :-
#This is a comment
print(“Hello World”)
#This is a comment
#comments in python
# help the programmer
print(int(45.8))
Data types in python
Built in types
• Text type :- str
• Numeric types:- int, float, complex
• Sequence types:- list, tuple, range
• Mapping type:- dict
• Set types:- set, frozenset
• Boolean :- bool
• Binary types :- bytes, bytearray, memoryview.
Examples for each
Complex -----> x = 1j
List ----->x = [“Orange”, “Banana”, “Cherry”]
Tuple ----->x = (“Orange”, “Banana”, “Cherry”)
Range -----> x = range(5) output(0,5)
Dict ------> x = {"name" : "John", "age" : 36}
Set ------> x = {"apple", "banana", "cherry"}
Frozen set----> x = frozenset({"apple", "banana", "cherry"})
Boolean ----> x = True
Bytes ---->b "Hello“
Byte array----> x = bytearray(5)
Memory view----> x = memoryview(bytes(5))
Python strings
A = “””welcome to python programming
Python is fun
and awesome. “””
Print(A)
Use single quote ‘ or “ to assign multiline string.
Slicing a string
• Let us take
b = “Hello World”
• To print some parts of this string we can use slicing as follows :-
print(b[2:5]) ----> llo since 5 is not included
• Index starts from 0.
 Slice from start
print(b[ :5])
 Slice to end
print(b[2:])
Modifying strings
upper()
lower()
strip()----> to remove white spaces
replace() ---> replaces letters of the string
let a = (“Hello, World”)
a.replace(“H”, “J”)--> output= Jello World
split()--> a.split(,) results [‘Hello’, ‘Wolrd’]
String format in python
age=32
text=“My name is John, and I’m ”+ age X
instead we can use format()
text=“My name is John, and I’m {}”
print(text.format(age))
Example 2:-
Quantity=3
Item_No=576
Price=49.67
My_order= “I want {} pieces of item {} for {} Dollars.”
print = (My_order.format(Quantity,Item_No,Price))
Lists
 Use [] to create lists
Can contain different types, such as integer,
float, string.
Accepting user input
The input function is a simple way for your program to get information
from people using your program. Here is an example:
name = input('Enter your name: ') print('Hello, ', name)
The basic structure is
variable name = input(message to user) The above works for getting .
To get numbers from the user to use in calculations, we need to do
something extra. Here is an example:
num = eval(input('Enter a number: '))
print('Your number squared:', num*num)
The eval function converts the text entered by the user into a number.
One nice feature of this is you can enter expressions, like 3*12+5, and
eval will compute them for you.
Exercise
Write a python program that convert degree
Celsius to Fahrenheit temperature?
temp = eval(input('Enter a temperature in
Celsius: ')) f_temp = 9/5*temp+32 print('In
Fahrenheit, that is', f_temp) if f_temp > 212:
print('That temperature is above the boiling
point.') if f_temp < 32: print('That
temperature is below the freezing point.')
Contd..
Ask the user to enter a number x. Use the sep
optional argument to print out x, 2x, 3x, 4x,
and 5x, each separated by three dashes, like
below.
Enter a number: 7
7---14---21---28---35
Loops
• For loop
• The structure of a for loop is as follows:
for variable name in range( number of times to repeat ):
statements to be repeated
for i in range(10): print('Hello')
Example:-
for i in range(3): num = eval(input('Enter a number: '))
print ('The square of your number is', num*num)
print('The loop is now done.')
Exercise
• Write a program that prints to the screen the following output.
• Use for loop:
1 -- Hello
2 -- Hello
3 – Hello
for i in range(3):
print(i+1, '-- Hello')
guess the output of this fragments.
1. for i in range(4):
print('*'*6)
2. for i in range(4):
print('*'*(i+1))
Range function
range(10) 0,1,2,3,4,5,6,7,8,9
range(1,10) 1,2,3,4,5,6,7,8,9
range(3,7) 3,4,5,6
range(2,15,3) 2,5,8,11,14
range(9,2,-1) 9,8,7,6,5,4,3
Math
from random import randint
x = randint(1,10)
print('A random number between 1 and 10: ', x)
from math import sin, pi
print('Pi is roughly', pi)
print('sin(0) =', sin(0))
print(abs(-4.3))
print(round(3.336, 2))
print(round(345.2, -1))
If statements
from random import randint
num = randint(1,10)
guess = eval(input('Enter your guess: '))
if guess==num:
print('You got it!')
if guess==num:
print('You got it!')
else:
print('Sorry. The number is ', num)

You might also like