0% found this document useful (0 votes)
94 views23 pages

Python Basics: Strings, Operators, and Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views23 pages

Python Basics: Strings, Operators, and Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Python 3.x
Strings

>>> print('hello')
hello
>>> print("abc'xyz")
abc'xyz
>>> print('''this is
a
multi
line
string''')

this is
a
multi
line
string
>>>

Escape sequences

>>> print('\'hello\'')

'hello'

>>> print('\\hello\\')

\hello\

>>> print('abc\nxyz')

abc

xyz

>>> print('abc\txyz')

abc xyz

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
2

Raw strings

>>> print(r'abc\txyz')

abc\txyz

>>> print(R'abc\nxyz')

abc\nxyz

String concatenation

>>> 'abc''xyz'

'abcxyz'

Format method

>>> x = 10

>>> y = 20

>>> print('value of x is {0} and value of y is {1}'.format(x,y))

value of x is 10 and value of y is 20

>>> 22/7

3.142857142857143

>>> '{0:.4}'.format(22/7)

'3.143'

>>> '{0:*^11}'.format('hello')

'***hello***'

>>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')

'Swaroop wrote A Byte of Python'

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
3

Logical and physical lines

>>> s = 'This is a string. \

This continues the string.'

>>> print(s)

This is a string. This continues the string.

>>> i = 5

>>> print\

(i)

>>> i = 5; print(i);

Operators and expressions

>>> 2+5
7
>>> 2.0+5
7.0
>>> 'a'+'b'
'ab'
>>> 9-5.0
4.0
>>> 9-4
5
>>> 3*2
6
>>> 'ab'*4
'abababab'
>>> 2**7
128
>>> 3**3
27

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
4

>>> 4/2
2.0
>>> 7/3
2.3333333333333335
>>> 7//2
3
>>> 10%2
0
>>> 10%3
1
>>> 3%5
3
>>> 10%4
2
>>>
>>> 2<<2
8
>>> 3<<1
6
>>> 3>>1
1
>>> 5>>1
2
>>> 5&3
1
>>> 5|3
7
>>> 5^3
6
>>> ~5
-6
>>> 5<2
False

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
5

>>> 5<8
True
>>> 3>=2
True
>>> 5==5
True
>>> 8!=7
True
>>> 8!=8
False
>>> True or False
True
>>> 2<5 and 8>5
True
>>>

Shortcut for math operation and assignment

>>> x =5
>>> x+= 3
>>> x
8
>>> x-=2
>>> x
6
>>> x*=3
>>> x
18

Evaluation order

>>> 2*5+2
12
>>> 2*(5+2)
14

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
6

>>> 2**3*2+3
19
>>> 4/2+5%3*2
6.0

Sample python programs

1. A program to find the area and the perimeter of a rectangle

length = 5

width = 2

area = length*width

print('Area is', area)

print('Perimeter is', 2*(length+width))

2. A program to convert a temperature value given in Celsius to


Fahrenheit

c = 25

f = (1.8 * c) +32

print(f)

3. A program to find the circumference and area of a circle when the


radius is given

r = 10

pi = 22/7

c = 2*pi*r

a = pi*(r**2)

print('Circumference = ', c)

print('Area = ', a)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
7

4. A program to find the volume and the surface area of a sphere when
the radius is given

r = 10

pi = 22/7

v = (4/3) * pi * (r**3)

a = 4* pi*(r**2)

print('Volume = ', v)

print('Area = ', a)

5. A program to find the volume of a cylinder when the radius and the
height are given

r = 8

pi = 22/7

h = 15

v = pi*(r**2)*h

print('Volume = ', v)

6. A program to find the slope and the intersection of a straight line


when the coordinates of two points are given

x1=2

y1=2

x2=4

y2=4

m = (y2-y1)/(x2-x1)

c = y1-(m*x1)

print('Slope = ',m)

print('intersection = ',c)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
8

7. A program to find the minimum number of different notes and coins


needed to pay a given amount

a = int(input("Enter the amount: "))

print('1000 notes- ',a//1000)

a%=1000

print('500 notes- ',a//500)

a%=500

print('100 notes- ',a//100)

a%=100

print('50 notes- ',a//50)

a%=50

print('20 notes- ',a//20)

a%=20

print('10 coins- ',a//10)

a%=10

print('5 coins- ',a//5)

a%=5

print('2 coins- ',a//2)

a%=2

print('1 coins- ',a)

8. Program to find the length of the hypotenuse (side opposite the


right angle of a right triangle) of a right triangle ( right-angled
triangle) when the lengths of other two legs (sides adjacent to the
right angle) are given.

x=3

y=4

z = (x**2 +y**2)**(0.5)

print(z)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
9

9. A program to print “child” or “adult” according to the age value


entered by the user

age = int (input ('Enter your age: '))

if age<18 :

print('Child')

else :

print('Adult')

A better solution for the above problem.

age = int (input ('Enter your age: '))

if age>=0 and age<18 :

print('Child')

elif age>= 18 and age<=100:

print('Adult')

else :

print('Wrong age value')

10. A program to print the largest value when two numbers are
entered

a= int (input ('Enter number 1: '))

b= int (input ('Enter number 2: '))

if a>b :

print (a)

else :

print (b)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
10

11. A program to print the largest value when three numbers are
entered.

a= int (input ('Enter number 1: '))

b= int (input ('Enter number 2: '))

c= int (input ('Enter number 3: '))

if a>b :

if a>c:

print (a)

else:

print (c)

elif b>c :

print (b)

else :

print (c)

12. A program to print the letter grade when marks are entered.

Marks Grade

75-100 A

60-75 B

45-60 C

30-45 S

0-30 F

m = int( input ('Enter marks: '))

if m>=75 and m<=100:

print ('A')

elif m>=60 and m<75:

print ('B')

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
11

elif m>=45 and m<60:

print ('C')

elif m>=30 and m<45:

print ('S')

elif m>=0 and m<30:

print ('F')

else:

print('wrong marks value')

13. A program to print numbers from 1 to 10.(using the while loop)

i=1

while i<=10:

print (i)

i=i+1

print ('loop end')

14. A program to calculate the sum of 1 to 10

i =1

tot =0

while i<=10:

tot=tot+i

i=i+1

print (tot)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
12

15. A program to calculate the sum of 10 numbers entered from the


keyboard.

total = 0

count = 1

while count<=10:

no = int(input("Enter number : "))

total=total+no

count = count + 1

print (total)

16. A program to calculate the sum of 10 numbers and stops if the


user enters -1.(use of break statement)

total = 0

count = 1

while count<=10:

no = int(input("Enter number : "))

if no == -1:

break

total=total+no

count = count + 1

print (total)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
13

17. A program to calculate sum of 10 numbers and stops if the user


enters -1. Also ignores negative numbers. (use of break and continue
statements)

total = 0

count = 1

while count<=10:

no = int(input("Enter number : "))

if no == -1:

break

if no<0:

print ("Negative number")

continue

total = total+no

count = count + 1

print (total)

18. A program to enter a series of numbers and stops entering if

-1 is entered. Then print the total.(Logic control loop)

total = 0

no = int(input("Enter number : "))

while no != -1:

total = total+no

no = int(input("Enter number : "))

print (total)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
14

19. A program to enter a series of numbers and stops by entering


(-1). If the user enters 10 numbers then it also stops using the
break statement. Then display the total.

total = 0

count = 0

no = int(input("Enter number : "))

while no != -1:

count = count + 1

total=total+no

if count == 10:

break

no = int(input("Enter number : "))

else:

print("-1 entered")

print (total)

20. A program to print from 1 to 9 using a for loop.

for num in range(1,10):

print (num)

21. A program to print 1 to 10, odd numbers

for num in range(1,10,2):

print (num)

22. A program to print a given list of numbers.

data = [10,40,50,70]

for num in data:

print(num)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
15

23. Reading a string letter by letter and print.

data = "computer"

for letter in data:

print (letter)

24. Printing multiplication tables.

no = 6

for r in range(1,13):

print (no, "x", r, "=", no*r)

Lists

>>> x = [5,1,-2,-9,7,10,12,8]

>>> x

[5, 1, -2, -9, 7, 10, 12, 8]

>>> x[0]

>>> len(x)

>>> x[len(x)-1]

>>> x[-1]

>>> x[2]

-2

>>> for i in range(len(x)):

print(i,end = " ")

0 1 2 3 4 5 6 7

>>> for i in range(len(x)):

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
16

print(x[i],end = " ")

5 1 -2 -9 7 10 12 8

>>> x[1:4]

[1, -2, -9]

>>> [Link](12)

>>> x

[5, 1, -2, -9, 7, 10, 12, 8, 12]

>>> [Link]()

>>> x

[12, 8, 12, 10, 7, -9, -2, 1, 5]

>>> x[1:1]

[]

Tuples

>>> a = 4,1,8,6,-1

>>> a

(4, 1, 8, 6, -1)

>>> len(a)

>>> a[1]

>>> a[-1]

-1

>>> [Link](12)

Traceback (most recent call last):

File "<pyshell#5>", line 1, in <module>

[Link](12)

AttributeError: 'tuple' object has no attribute 'append'

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
17

Dictionaries

>>> x = {'a':10,'b':5,'c':3,'d':-1,'e':-4,'f':12}

>>> x

{'a': 10, 'b': 5, 'c': 3, 'd': -1, 'e': -4, 'f': 12}

>>> x['a']

10

>>> x['f']

12

>>> x['e']+= 6

>>> x

{'a': 10, 'b': 5, 'c': 3, 'd': -1, 'e': 2, 'f': 12}

>>> del x['d']

>>> x

{'a': 10, 'b': 5, 'c': 3, 'e': 2, 'f': 12}

>>> x['g'] = 17

>>> x

{'a': 10, 'b': 5, 'c': 3, 'e': 2, 'f': 12, 'g': 17}

Sets

>>> x = set([5,1,4,9,6,3,7,2])

>>> y = set([1,7,3,2])

>>> z = set([-1,10,12,20,4,6,2,7])

>>> x

{1, 2, 3, 4, 5, 6, 7, 9}

>>> y

{1, 2, 3, 7}

>>> z

{2, 4, 6, 7, 10, 12, 20, -1}

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
18

>>> x&z

{2, 4, 6, 7}

>>> x|z

{1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 20, -1}

>>> x&y

{1, 2, 3, 7}

>>> x-y

{9, 4, 5, 6}

>>> 9 in x

True

>>> 12 in x

False

>>> [Link](1)

>>> x

{2, 3, 4, 5, 6, 7, 9}

Functions

25. Function to print a logo

def printSomething():

print('******************')

print('Advanced Level ICT')

print('******************')

printSomething()

printSomething()

printSomething()

printSomething()

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
19

26. Function to print a largest value when two numbers are entered

def printLargest(a,b):

if a>b:

print (a)

else:

print (b)

printLargest(3,5)

printLargest(4,1)

27. Local variables with functions

def func(x):

print ('x in the function is ', x)

x =2

print ('x in the function is ', x)

x = 30

func(x)

print ('x in the main program is ', x)

28. Using the ‘global’ statement to access variables defined outside the function

def func():

global x

print ('x is ', x)

x = 2

print ('Global x value is changed to ', x)

x =50

func()

print ('Value of x is', x)

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
20

29. Using default arguments

def defaultArgs(word,number=3):

print (word*number)

defaultArgs('hello')

defaultArgs('hi',5)

30. Using keyword arguments

def func(a,b=5,c=10):

print ('a is', a, 'and b is', b, 'and c is', c)

func(3,7)

func(25,c=24)

func(c=50,a=100)

31. Using the return statement

def getMax(a,b):

if a>b:

return a

else:

return b

x = getMax(4,7)

print (x)

print (getMax(-3,-4))

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
21

strip() and split()

>>> x = ' hello '

>>> x

' hello '

>>> [Link]()

'hello'

>>> x = 'computer'

>>> [Link]('c')

'omputer'

>>> [Link]('r')

'compute'

>>> [Link]('u')

'computer'

>>> data = 'Amila,75,45,89'

>>> data

'Amila,75,45,89'

>>> dl = [Link](',')

>>> dl

['Amila', '75', '45', '89']

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
22

File Handling
32. Open a file to read the content.

f = open('[Link]', 'r')

txt = [Link]()

print (txt)

[Link]()

33. Reading comma separated values

f = open ("[Link]","r")

record = [Link]()

while record:

data = [Link]().split(",")

print (data)

record = [Link]()

[Link]()

File content: -

Amila,33,22,85

Kasun,34,66,69

Asela,33,66,78

Bimal,55,33,92

Saman,44,55,85

34. Write data to a file

f = open ("[Link]","w")

s = 'Sri Lanka'

[Link](s)

[Link]()

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science
23

35. Storing comma separated values taken from the keyboard

f = open ("[Link]","w")

for r in range(5):

name = input("Enter name : ")

m1 = input("Marks 1: ")

m2 = input("Marks 2: ")

m3 = input("Marks 3: ")

record = name + ", "+m1+','+m2+','+m3+'\n'

[Link](record)

[Link]()

Pubudu Wijekoon
[Link]. Sp.(Hons) in IT, [Link]. in Computer Science

Common questions

Powered by AI

The evaluation order in arithmetic expressions follows the standard operator precedence rules, which can significantly impact the result if not properly managed. In Python, operators are evaluated from highest to lowest precedence. For example, '*', '/', and '%' have higher precedence than '+' and '-', so expressions like '2*5+2' will evaluate as '(2*5)+2', resulting in '12' . Parentheses can be used to alter this order and ensure specific computations are executed first, as in '2*(5+2)', which yields '14'. Understanding and using precedence correctly is crucial for avoiding logical errors in complex arithmetic calculations.

Escape sequences in Python strings, such as '\n' for a newline or '\t' for a tab, allow for the inclusion of special characters by using backslashes. For example, 'abc\nxyz' results in output where 'xyz' appears on a new line . Raw strings, defined by prefixing the string with 'r' or 'R', interpret backslashes as literal characters instead of escape indicators. Therefore, 'r'abc\txyz'' would output 'abc\txyz', preserving the backslashes . Raw strings are significant when working with file paths or regular expressions where backslash usage is frequent.

The format method in Python allows for advanced string formatting by replacing placeholders with specified values. It supports positional and keyword arguments, as well as formatting options such as padding and alignment. For example, 'value of x is {0} and value of y is {1}'.format(x, y)' dynamically inserts the values of 'x' and 'y' into the string . F-strings, a feature introduced in Python 3.6, enhance this by allowing expressions to be embedded directly inside string literals, enclosed in curly braces, providing a more concise syntax. For instance, f'value of x is {x} and value of y is {y}' does the same with better readability.

Indentation in Python is crucial as it defines block structures for control flow statements like loops and conditionals. Unlike many other programming languages that use braces or keywords to denote blocks, Python uses indentation to identify code blocks. For example, the lines within a 'for' loop or an 'if' statement must be indented under the respective control statement. This requirement emphasizes readability and enforces a uniform coding style. Improper indentation can lead to syntax errors or unintended execution flow . Thus, indentation serves as the primary method to indicate grouped statements that should be treated as a single logical block.

Python sets support typical mathematical set operations such as union, intersection, and difference, which can be used to perform efficient data manipulation. The union operator '|' combines elements from two sets, shown by 'x|z', which results in a set containing all distinct elements from both sets . Intersection '&' finds common elements, as in 'x&z', resulting in elements present in both sets. The difference '-' excludes shared elements, demonstrated by 'x-y', removing common elements of 'y' from 'x' . These operations are crucial in scenarios like data analysis for filtering and merging datasets, and deduplication tasks.

Arithmetic operators in Python include basic operations such as addition '+', subtraction '-', multiplication '*', division '/', and modulus '%', which are used for numerical computations. For example, '9 - 5.0' results in '4.0', and '10 % 3' gives '1' . Bitwise operators, on the other hand, perform operations at the bit level: '&' (AND), '|' (OR), '^' (XOR), '~' (NOT), '<<' (left shift), and '>>' (right shift). These are often used in low-level programming tasks such as network protocol implementation and encryption algorithms. For instance, '5 & 3' results in '1', and '2 << 2' results in '8' . Both types of operators play crucial roles in different computational tasks ranging from simple mathematics to complex system programming.

Logical lines in Python refer to lines of code that are executed together as a single statement. These may span multiple physical lines through the use of a backslash '\' at the end of each physical line to indicate continuation . For example, 's = 'This is a string. \ This continues the string.'' is treated as a single logical line . Physical lines, on the other hand, are lines of text as entered by the programmer in the script file. Logical lines can be compared to sentences in a paragraph, while physical lines are akin to separate lines of text. Proper understanding ensures correct code execution and syntax error avoidance.

Python dictionaries handle key-value relationships by using a hash table structure to map keys to their corresponding values. This allows for fast retrieval, modification, and storage of data. Keys in a dictionary are unique and immutable (e.g., strings, numbers), while values can be of any data type. For example, updating a value involves a simple syntax like 'x['e'] += 6', which modifies the stored value . The fast lookup and dynamic nature of dictionaries make them ideal for tasks involving associative arrays, configuration settings, and when fast access to elements is critical, enhancing efficiency in data management and manipulation tasks.

Python lists and tuples differ primarily in mutability and intended use cases. Lists are mutable, meaning their elements can be modified, deleted, or added. For example, elements can be appended or reversed, as shown by 'x.append(12)' modifying the list . Tuples, however, are immutable, meaning once they are created, their elements cannot be changed, as attempting 'a.append(12)' raises an AttributeError . This immutability makes tuples useful for fixed-size collections of items that should not change, such as geographic coordinates, while lists are preferable for collections requiring dynamic modification.

Python uses a scope resolution system known as LEGB (Local, Enclosing, Global, Built-in) to determine the accessibility of variables in different contexts. Local variables are those defined within a function and are only accessible in that function. Global variables are defined at the top level of a script or module and can be accessed throughout the program unless shadowed by a local declaration. Using the 'global' keyword within a function allows modification of a global variable from inside a function. For example, redefining a global variable 'x' within a function requires 'global x; x = 2' , ensuring Python's interpreter recognizes the intended modification of the globally declared 'x'.

You might also like