For beginner Python programmers, the main ones are that the print statement of Python 2.x is now a printfunction in Python 3, the raw_input function in Python 2.x is replaced by the input function in Python 3, and an integer division such as 2/3 in Python 2.x is now a real division in Python 3.
So be aware that there are some significant differences between Python 3 and earlier versions.
The following tutorials help you to learn Python 3 programming language by basicly.
Python 3 Tutorials
The first Python program has only one executable line.
Program 1: Print “Hello World”
1 2 3 |
print("Hello World!") |
Python 3 Input
Input means getting data into your program from an input device (usually the keyboard).
Python needs a place to store whatever value is input. These storage places are known as variables, and have to have a name.
In the Python 3 statement below, the variable’s name is text.
1 2 3 |
text = input("Enter some text ") |
The above Python statement, when executed (i.e. run) will output to the screen whatever is within the quote marks. This text is sometimes refered to as a “Enter some thing:”. Python then waits for you to enter something from the keyboard.
Type in some text and then press the Enter key on the keyboard. Whatever you typed in before you hit the Enter key is stored into the variable called text. text is the variable where the input data is stored.
The Assignment symbol =
The purpose of the assignment symbol is to place whatever you typed in, into the variable on its left.
1 2 3 |
text = input("Enter some text ") |
Built-in functions
input(), int() and float() , str() are built-in Python functions. They can be used at any time in any Python statement.
Data types of input values
You can always check the data type of any variable by using the type() built-in function.
1 2 3 4 5 6 7 8 9 10 |
a = "10" b = '99' c = a + b print (c) print (type(c)) c = int(c) print (c) print (type(c)) |
Program 2: Print given text
1 2 3 4 5 6 |
#Print given text text = input("Enter some text: ") print("This is what you entered:") print(text) |
Program 3: Note that \n within quote marks a new line to be printed
1 2 3 4 5 6 7 8 |
text = input("Enter some text #Print given text text = input("Enter some text: ") print("This is what you entered:") print(text)\nHere:") print("This is what you entered:") print(text) |
Program 4: Use variable
1 2 3 4 5 6 |
message = "Enter a some text " text = input(message) print("This is what you entered:") print(text) |
Program 5: Calculate the Average of 3 Numbers
1 2 3 4 5 6 7 8 9 10 11 |
#Calculate the Average of 3 Numbers number1 = float(input("Enter the first number: ")) number2 = float(input("Enter the second number: ")) number3 = float(input("Enter the third number: ")) total = number1 + number2 + number3 average = total / 3 print("The average is: ") print(average) print("The average is ",average) |
Program 6: Calculate the Average of Numbers in a Given List
1 2 3 4 5 6 7 8 9 10 |
#Calculate the Average of Numbers in a Given List number=int(input("Enter the number of elements to be inserted: ")) array=[] for i in range(0,number): elem=int(input("Enter element: ")) array.append(elem) avg=sum(array)/number print("Average of elements in the list",round(avg,2)) |
Program 7: Calculate the average of 3 numbers using “while”
1 2 3 4 5 6 7 8 9 10 11 |
#calculate the average of 3 numbers using "while" total = 0.0 count = 0 while count < 3: number = float(input("Enter a number: ")) count = count + 1 total = total + number average = total / 3 print("The average is " + str(average)) |
Examples of use of arithmetic operators
Program 8: Using operands
1 2 3 4 5 6 7 8 9 10 |
print(1 + 2) print(6 - 3) print(4 * 10) print(6 / 3) print(9 % 3) print(6 // 2) # floor division: always truncates fractional remainders print(-10) print(3**5) # three to the power of 2 |
Program 9:
1 2 3 4 5 6 7 8 9 10 |
print(1.0 + 2.0) print(6.0 - 3.0) print(3.0 * 4.0) print(9.0 / 3.0) print(6.0 % 3.0) print(6.0 // 2.0) # floor division: always truncates fractional remainders print(-15.0) print(3.0**5.0) # three to the power of 2 |
Examples of use of Boolean expressions
Program 10: Python stores true as integer 1, and false as integer 0 but outputs ‘true’ or ‘false’ from print statements
1 2 3 4 5 6 7 8 |
print(5 > 10) print(2 < 16) print(5 == 5) print(7 <= 7) print(7 >= 7) print(10.0 != 10) |
Program 11: string objects and string assignments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
print("Hello out there") print('Hello') a1 = "Hello out there" print(a1) a2 = 'Hello' print(a2) b1 = 'Hello' b2 = "World" c = b1 + b2 print(c) |
Program 12: Convert the integer to a string first to concatenate a string and an integer
1 2 3 4 5 6 7 8 9 |
a = 'Hello' b = " World" c = a + b print(c) d = c + str(10) print(d) |
Program 13: Round up a floating point number to the nearest integer
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Round up a floating point number to the nearest integer x = 2.6 print(x) x = round(x) print(x) # compare the above with x = 2.6 x = int(x) print(x) |
Program 14: Round a float number to 2 decimal places, and output that number as € currency printed with a comma after the number of thousands
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
number = 5274.2578 print(number) number = round(number,2) print(number) # the above line rounds the number to 2 decimal places thousands = number / 1000 print(thousands) thousands = int(thousands) print(thousands) remainder = number % 1000 print(remainder) formatted_output = "€" + str(thousands) + "," + str(remainder) print(formatted_output) |
Program 15: Converting one data type to another
1 2 3 4 5 6 7 8 |
#Converting one data type to another number1 = input("Enter first number:") print(number1, type(number1)) number1 = int(number1) print(number1, type(number1)) |
Program 16: Displaying an object’s memory location
1 2 3 4 5 6 7 8 |
#Displaying an object's memory location number1 = input("Enter first number:") print(number1, type(number1), id(number1)) number1 = int(number1) print(number1, type(number1), id(number1)) |
if statement
An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else statement following if.
Syntax
The syntax of the if…else statement is −
1 2 3 4 5 6 |
if expression: statement(s) else: statement(s) |
Program 17: Displaying boolean values
1 2 3 4 5 6 |
#Displaying boolean values number = 10 isPositive = (number > 0) print(isPositive) |
Program 18: Combining boolean expressions with and
1 2 3 4 5 6 |
#Combining boolean expressions with and age = 25 salary = 55000 print((age > 21) and (salary > 50000)) |
Program 19: The if statement
1 2 3 4 5 6 7 |
a = 'world' if a == 'world': print('It is world') else: print('It is not world') |
Program 20: The if statement with multiple statements
1 2 3 4 5 6 7 8 9 |
x = 'April' if x == 'April': print('Hi April\n') print("Nice weather we're having") print('Have a nice day!') else: print('not April') |
Program 21: The if statement with multiple statements
1 2 3 4 5 6 7 8 9 10 11 |
#The if statement with multiple statements x = 'April' if x == 'May': print('Hi April\n') print("Nice weather we're having") print('Have a nice day!') else: print('not April') print('Not having a good day?') |
Program 22: A nested if example (an if statement within another if statement)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#A nested if example (an if statement within another if statement) score = input("Enter score: ") score = int(score) if score >= 80: grade = 'A' else: if score >= 70: grade = 'B' else: grade = 'C' print("\n\nGrade is: " + grade) |
Program 23: A nested if example – using if/else
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#A nested if example - using if/else score = input("Enter score: ") score = int(score) if score >= 80: grade = 'A' else: if score >= 70: grade = 'B' else: if score >= 55: grade = 'C' else: if score >= 50: grade = 'Pass' else: grade = 'Fail' print("\n\nGrade is: " + grade) |
Program 24: A nested if example – using if/elif/else
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#A nested if example - using if/elif/else score = input("Enter score: ") score = int(score) if score > 80 or score == 80: grade = 'A' elif score > 70 or score == 70: grade = 'B' elif score > 55 or score == 55: grade = 'C' elif score > 50 or score == 50: grade = 'Pass' else: grade = 'Fail' print("\n\nGrade is: " + grade) |
Program 25: Demo of DeMorgan’s Laws
a Not And is equivalent to an Or with two negated inputs or a Not Or is equivalent to an And with two negated inputs
1 2 3 4 5 6 7 |
#Demo of DeMorgan's Laws x = int(input("Enter a value for x: ")) y = int(input("Enter a value for y: ")) print((not(x < 15 and y >= 3))) print((x >= 15 or y < 3)) |
Program 26: Decision using two conditions linked with an and or an or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#Decision using two conditions linked with an and or an or age = input("Enter your age: ") age = int(age) have_own_car = input("Do you own your own car (y/n): ") if (age > 21) and (have_own_car == 'y'): print("You are over 21 years old and own your own car") if (age > 21) and (have_own_car == 'n'): print("You are over 21 years old and you do NOT own your own car") if (age == 21) and (have_own_car == 'y'): print("You are 21 years old and you own your own car") if (age == 21) and (have_own_car == 'n'): print("You are 21 years old and you DO NOT own your own car" ) if (age < 21) and (have_own_car == 'y'): print("You are younger than 21 and you own your own car") if (age < 21) and (have_own_car == 'n'): print("You are younger than 21 and you DO NOT own your own car" ) salary = float(input("Enter your annual salary, (e.g. 50000): ")) if (salary > 50000) or (age > 21): print("you can join our club because you earn more than $50000 OR you are over 21 (or both)") else: print("you need to be earning more than 50000 OR be over 21 (or both) to join our club") |
Python while Loop Statements
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is −
1 2 3 4 |
while expression: statement(s) |
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
Program 27: Examples of while loops
1 2 3 4 5 6 7 |
x = 1 while x < 5: print('Hi World') x = x + 1 print('done') |
Program 28: Examples of while loops
1 2 3 4 5 6 7 8 9 |
x = 1 while x < 5: print('Hi World') x = x + 1 print('I love World') print('done') print('gone') |
Program 29: Examples of while loops – the infinite loop
1 2 3 4 5 6 7 8 9 10 11 12 |
#Examples of while loops - the infinite loop x = 1 while x: print('Hi world') x = x + 1 print('I love world') print('Press the Ctrl key and the C key together') print('to interrupt this program...') print('done') print('gone') |
Program 30: Examples of while loops – another infinite loop
1 2 3 4 5 6 7 8 9 |
#Examples of while loops - another infinite loop while 1: print('Hello World! ') print('Press the Ctrl key and the C key together') print('to interrupt this program...') print('done') print('gone') |
Program 31: Example of break to end an infinite loop
1 2 3 4 5 6 7 8 9 10 11 |
#Example of break to end an infinite loop while 1: print('Hello') answer = input('Press y to end this loop') if answer == 'y': print('Can it break?') break print('Have a ') print('nice day!') |
Program 32: Example of continue to end an infinite loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#Example of continue to end an infinite loop while 1: print('Hello') answer = input('Press y for continue back ') if answer == 'y': print('You will continue back now! ') continue answer = input('Had enough yet? ') if answer == 'y': break print('Have a ') print('nice day!') |
Program 33: ‘sentinel-controlled’ while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# initialization phase totalScore = 0 # sum of scores numberScores = 0 # number of scores entered # processing phase score = input( "Enter score, (Enter 0 to end): " ) # get one score score = int( score ) # convert string to an integer while score != 0: # 0 is used as a sentinel ( a lookout or sentry value ) totalScore = totalScore + score numberScores = numberScores + 1 score = input( "Enter score, (Enter 0 to end): " ) score = int( score ) # termination phase if numberScores != 0: # division by zero would be a run-time error average = float( totalScore ) / numberScores print("Class average is", average) else: print("No scores were entered") |
Python for Loop Statements
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
1 2 3 4 |
for iterating_var in sequence: statements(s) |
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
Program 34: Example of the counter-controlled for loop
1 2 3 4 5 |
#Example of the counter-controlled for loop for c in range (10): print(c) |
Program 35: Example of the counter-controlled for loop
1 2 3 4 5 |
#Example of the counter-controlled for loop for c in range (5,10): print(c) |
Program 36: ‘continue’ with the for loop
1 2 3 4 5 6 7 |
#'continue' with the for loop for c in range (1,6): if c == 3: continue print(c) |
Program 37: ‘break’ with the for loop
1 2 3 4 5 6 7 |
#'break' with the for loop for c in range (1,6): if c == 3: break print(c) |
Program 38: Outputting strings and numbers in a single print statement
1 2 3 4 5 6 |
#Outputting strings and numbers in a single print statement d = 10 c = 75 print('Total is: ', d, 'dollars and', c, ' cents') |
Program 39: Outputting strings and numbers in a single printstatement using string formatting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#Outputting strings and numbers in a single printstatement #using string formatting. firstname = "Mary" lastname = 'Brown' print("My fullname is %s %s" % (firstname,lastname)) print() # printing decimal or integer numbers in a string x = 40 y = 15 print('The sum of %d and %d is %d' % (x, y, x + y)) print() # printing decimal or integer numbers in a string x = 40 y = 15 print('The sum of %i and %i is %i' % (x, y, x + y)) print() # printing floating point numbers in a string x = 20.253 y = 15.654 print('The sum of %f and %f is %f' % (x, y, x + y)) print() # printing floating point numbers to 2 decimal places x = 20.253 y = 15.654 print('The sum of %0.2f and %0.2f is %0.2f' % (x, y, x + y)) print() # printing floating point numbers to 3 decimal places x = 20.253 y = 15.654 print('The sum of %0.3f and %0.3f is %0.3f' % (x, y, x + y)) print() for number in range(18): print("The decimal number %d in hexadecimal is %x" % (number,number)) |
Program 40: Repeat a program at the user’s request
1 2 3 4 5 6 7 8 9 10 |
#Repeat a program at the user's request print("This is the start of the program") answer = 'y' while (answer == 'y' or answer == 'Y'): print("This is a statement from within the while loop") print("This is another statement from within the while loop") answer = input("Do you want to run this program again? y/n") print("Goodbye!") |
Program 41: Use a loop within a loop
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#Use a loop within a loop x = 1 while (x < 4): print() # prints a new line print("x = " + str(x),) # the , forces printing of the next item # to be on the same line x = x + 1 y = 1 while (y < 4): print("y = " + str(y),) # the , forces printing on the same line y = y + 1 |
Program 42: Use a loop within a loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#Use a loop within a loop x = 1 while (x < 3): print() # prints a new line print("x = " + str(x)) # the , forces printing of the next item # to be on the same line x = x + 1 y = 1 while (y < 3): print("y = " + str(y),) # the , forces printing on the same line y = y + 1 z = 1 while (z < 3): print("z = " + str(z),) # the , forces printing on the same line z = z + 1 print() # prints a new line |
Program 43: Use a loop within a loop
1 2 3 4 5 6 7 |
#Use a loop within a loop for i in range (1,6): for j in range (1,6): print("i: " + str(i) + " j: " + str(j) ) print() |
Program 44: Use a loop within a loop
1 2 3 4 5 6 7 8 |
#Use a loop within a loop for i in range (1,4): for j in range (1,4): for k in range (1,4): print("i: " + str(i) + " j: " + str(j) + " k: " + str(k)) print() |
Program 45: Using the built-in square root function math.sqrt
To use any math function, you have to include the statement: import math in your program – usually at the top, but can be anywhere.
1 2 3 4 5 6 7 |
import math print(math.sqrt(16)) print(math.sqrt(16.5)) x = 144 print(math.sqrt(x)) |
Program 46: Using the dir function to list out the names of available functions in the math module
1 2 3 4 5 |
import math print(math) print(dir(math)) |
Python – Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
- Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
- Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
- The first statement of a function can be an optional statement – the documentation string of the function or docstring.
- The code block within every function starts with a colon (:) and is indented.
- The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
1 2 3 4 5 6 |
def functionname( parameters ): "function_docstring" function_suite return [expression] |
By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
Program 47: Showing functions which have no return statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# Showing functions which have no return statement def greeting(): print("Hello") def many_greetings(n): for i in range(n): print("Hello Again!") def many_greetings_with_name(n,the_name): for i in range(n): print("Hello Again" + the_name + "!") greeting() greeting() greeting() print() # prints a blank line for i in range(2): greeting() print() # prints a blank line many_greetings(4) print() # prints a blank line x = int(input("How many greetings do you want?: ")) many_greetings_with_name(x," Mary") |
Program 48: Using a programmer-defined function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Using a programmer-defined function # start of function definition def cube( y ): return y * y * y # end of function definition # prints the cube of numbers 1 to 5 for x in range(1,6): print(cube(x)) # the last value of x is 5 print("last value of x is:",x) |
Program 49: Using two programmer-defined functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Using two programmer-defined functions def cube( y ): return y * y * y def doubleIt ( z ): return 2 * z print("1 to 5 cubed") for x in range(1,6): print(cube(x),) print() print() print("1 to 5 doubled") for x in range(1,6): print(doubleIt(x),) |
Program 50: Importing programmer-defined functions
Save codes as myFun.py
1 2 3 4 5 6 7 8 9 10 |
# myFun.py # Programmer-defined functions def cube( y ): return y * y * y def doubleIt ( z ): return 2 * z |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#Importing programmer-defined functions #IMPORTANT: myFun.py should be in the same folder as this file import myFun print("1 to 5 cubed") for x in range(1,6): print(myFun.cube(x),) print() print("1 to 5 doubled" ) for x in range(1,6): print(myFun.doubleIt(x),) |
Program 51: Function with no return statement
1 2 3 4 5 6 7 8 9 10 11 12 |
# Function with no return statement def times(x): for i in range(1,11): print("%d x %d = %d" % (i, x, i * x)) print("This is the 1 times tables:") times(1) print("This is the 2 times tables:") times(2) |
Program 52: Function with two return statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Function with two return statements def division(x,y): if (y == 0): print("division by zero not allowed") return else: print(" returning %f divided by %f " % (x, y)) return x / y print(" 5.0 / 2 returns:") result = division( 5.0 , 2 ) print(result) print(" 5.0 / 0 returns:") result = division( 5.0 , 0 ) print(result) |
Program 53: Function with no arguments
1 2 3 4 5 6 7 8 |
# Function with no arguments def greeting(): print("Hello there!") greeting() greeting() |
Program 54: Program with a Boolean function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Program with a Boolean function def isPositive(x): if (x >= 0): return True # 1 else: return False # 0 x = float(input("Enter a positive or negative number: ")) result = isPositive(x) print(result) print(isPositive(x)) |
Program 55: Polymorphic function
Polymorphism : the meaning of the operations depends on the objects being operated on. The * operator is said to be “overloaded”
1 2 3 4 5 6 7 8 9 10 11 |
# Polymorphic function def doubleIt(x): return (2 * x) y = 3 print(doubleIt(y)) z = "Hello " print(doubleIt(z)) |
Program 56: The scope of a variable
Local scope means the variable is only available in the function where it is defined. Global scope means the variable is available everywhere in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# The scope of a variable def my_function(num): print("n in function: ",num) print("number in function: ",number) number = 10 print("number in main program: ",number) my_function(number) print(num) # you cant use num variable in this scope # You will get an error, because num is not known outside of the function my_function. |
Python Lists
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.
The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.
Program 57: Creating and using a Python list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Creating and using a Python list result = [0,0,0,0,0,0,0,0] print(result) result[0] = 75 result[1] = 90 result[4] = 72 print(result) print(result[0]) print(result[1]) print(result[2]) print(result[3]) print(result[4]) print(result[5]) print(result[6]) print(result[7]) |
Program 58: Creating and printing an empty list
1 2 3 4 5 6 7 8 9 |
# Creating and printing an empty list list1 = [] print(list1) # the following statement would generate an error #print(list1[0]) |
Program 59: Appending to an empty list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Appending to an empty list list1 = [] print(list1) list1.append(67) print(list1[0]) list1.append("hello") print(list1) print(list1[0]) print(list1[1]) # the following statement would generate an out-of-range error #print(list1[2]) |
Program 60: List of lists
1 2 3 4 5 6 7 8 9 10 11 12 |
# List of lists list1 = [1,2,3] print(list1) list2 = [4,5,6] print(list2) list3=[list1,list2] print(list3) print(list3[0]) print(list3[1]) |
Program 61: Accessing the last item in a list
1 2 3 4 5 6 7 8 9 10 |
# Accessing the last item in a list list1 = [1,2,3,6,7,8,9,10] print(list1) print(list1[0]) print(list1[1]) print(list1[-1]) print(list1[-2]) |
Program 62: Deleting items from a list
1 2 3 4 5 6 7 8 9 |
# Deleting items from a list list1 = [1,2,3,4,5,6,7,8,9,10] print(list1) del list1[0] del list1[-1] print(list1) |
Program 63: Repeating lists
1 2 3 4 5 6 7 8 9 10 |
# Repeating lists list1 = [1,2,3] print(list1) print(list1 * 3) print(list1) list1 = list1 * 2 print(list1) |
Program 64: List indexing
1 2 3 4 5 6 |
# List indexing list1 = [10,9,8,7,6,5,4,3,2,1,0] print(list1[0:1],list1[5:7]) |
Program 65: Finding the length of a list
1 2 3 4 5 6 7 8 |
# Finding the length of a list list1 = ["Tomy","May",'Lindia','Barbrossa',1,2,3] list2 = [1,2,3,4] list3 = [] print(len(list1), len(list2), len(list3)) |
Program 66: Concatenating lists
1 2 3 4 5 6 7 8 9 10 11 12 |
# Concatenating lists list1 = [1,2,3] print(list1) list2 = [4,5,6] print(list2) list1 = list1 + list2 print(list1) list1 = list1 + list1 print(list1) |
Program 67: List iteration
1 2 3 4 5 6 7 |
# List iteration list2 = [1,2,3,"Hello",4,5] for i in list2: print(i, end=" ") |
Program 68: List membership
1 2 3 4 5 6 |
# List membership list2 = [1,2,3,"Hello",4,5] print("Hello" in list2) |
Program 69: Selection of list methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Selection of list methods list2 = ["B","C","A"] print(list2) list2.extend(["X","Y"]) # extends the list print(list2) list2.pop() # removes last item from the list print(list2) list2.pop() print(list2) list2.reverse() # reverses the order of the items in the list print(list2) list2.append("S") print(list2) list2.sort() # sorts the list into ascending order print(list2) list2.reverse() # reverses the order of the items in the list print(list2) |
Program 70: Sequential search of a list
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Sequential search of a list list1 = [21,25,24,22,65,1,44,51,78] numbertofind = int(input("Enter a number\n")) found = 0 for i in list1: if numbertofind == i: print(numbertofind, " at index: ",list1.index(numbertofind)) found = 1 if found == 0: print("Number not found") |
Program 71: Sequential search of a list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Sequential search of a list mylist = [21,25,24,22,65,1,44,51,78] n = len(mylist) print(n) for i in range(n): print(mylist[i], end=" ") search = int(input("\nPlease enter a number to search for: ")) print(search) found = False for i in range(n): if mylist[i] == search: found = True index = i print() if found == True: print(str(search) + " found at index " + str(index)) else: print(str(search) + " not found") |
Program 72: binarysearch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# binarysearch def binarysearch(mylist,target): left = 0 right = len(mylist) steps = 0 while (left < right-1): steps = steps + 1 mid = int((right+left)/2) number_at_mid = mylist[mid] print("Steps taken to find the number: ",steps) if (target == number_at_mid): return True if (target < number_at_mid): right = mid else: left = mid if (left >= right): return False if ( (left == (right-1)) and (mylist[left] == target) ): return True return False mylist = [11,27,36,44,51,22,65,1,78] print(mylist) mylist.sort() print(mylist) repeat = "y" while (repeat == "y" or repeat == "Y"): mytarget = int(input("Enter number to find: ")) if binarysearch(mylist,mytarget): print("Found!") else: print("NOT Found!") repeat = input("Another search? (y/n)") print("\n\nProgram ended") |
Program 73: biglist
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# biglist import random numberslist = [] number = 0 while number < 5000: value = random.randint(1,10000) if not(value in numberslist): numberslist.append(value) number = number + 1 print(numberslist) |
Program 74: Program which demonstrates a bubble sort on a list of 10 random integers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# Program which demonstrates a bubble sort on a list of 10 random integers import random # define the bubble sort function def sort(values): length = len(values) for time in range(0, length-1): for position in range(0, (length-time-1)): if values[position] > values[position+1]: temp = values[position] values[position] = values[position+1] values[position+1] = temp # generate a list of ten random numbers numbers = [] number = 0 while number < 10: value = random.randint(1,100) if not(value in numbers): numbers.append(value) number = number + 1 # show unsorted list, sort the list, and show sorted list print("Before:", numbers) sort(numbers) print("After :", numbers) |
Python Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.
Program 75: Strings
1 2 3 4 5 6 7 8 9 |
# Strings print(''' Life is Beautiful ''') |
Program 76: Using an apostrophe within a string and using double quote marks within a string
1 2 3 4 5 6 7 8 |
print("This is message") print("This is also message" ) # You can also print a " within a string enclosed in single quotes: print('double quote ", and "more"') |
Program 77: Multiplying numbers and multiplying strings
1 2 3 4 5 6 7 8 |
# Multiplying numbers and multiplying strings print(2 * 3) print(20 * 3) print("2" * 3) print("20" * 3) |
Program 78: String concatenation
1 2 3 4 5 |
# String concatenation print("Life " + "is " + ("Beautiful " * 3)) |
Program 79: String indexing
1 2 3 4 5 6 |
# String indexing s1 = "Hello, World" print(s1[0],s1[7]) |
Program 80: String slicing
1 2 3 4 5 6 7 |
# String slicing s1 = "Hello, World" print(s1[0:1],s1[5:7]) print(s1[6:9]) |
Program 81: Finding the length of a string
1 2 3 4 5 6 7 8 9 10 |
# Finding the length of a string s1 = "Hello" s2 = "World" s3 = "" print(len(s1),end=" ") print(len(s2),end=" ") print(len(s3)) |
Program 82: %s string formatting code
1 2 3 4 5 |
# %s string formatting code print('Python is a %s language.' % 'great') |
Program 83: Finding a string within a string
1 2 3 4 5 6 7 |
# Finding a string within a string s1 = 'Hello,World. Life is Beautiful' x = s1.find('is') print(x) |
Program 84: Changing a string within a string
1 2 3 4 5 6 7 8 9 10 11 |
# Changing a string within a string s1 = 'I like black hot coffee' print(s1) s2 = s1.replace('coffee','tea') print(s2) |
Program 85: Escape sequences within a string
1 2 3 4 5 6 |
# Escape sequences within a string s = 'I\nam\there' print(s) |
Program 86: Iteration and membership with strings
1 2 3 4 5 6 7 8 9 10 |
# Iteration and membership with strings s = 'I am here' for c in s: print(c, end=" ") print('a' in s, end=" ") print(' ' in s, end=" ") print('z' in s) |
Program 87: Demonstration of printing Unicode characters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Demonstration of printing Unicode characters str1 = "Hello\u2588out there" # solid block within text print(str1) str1 = '\u2588\u2588' #two full block characters print(str1) print() print() print('two lines of two full blocks, the number 17 and two full blocks:') str1 = '\u2588\u2588\u2588\u2588\u0020\u0020' + '17' + '\u2588\u2588\u2588\u2588' print(str1) str1 = '\u2588\u2588\u2588\u2588\u0020\u0020\u0020\u0020\u2588\u2588\u2588\u2588' print(str1) |
Opening and Closing Files
Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python’s built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.
Syntax
1 2 3 |
file object = open(file_name [, access_mode][, buffering]) |
Here are parameter details −
- file_name − The file_name argument is a string value that contains the name of the file that you want to access.
- access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
- buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Program 83: Program which uses a file
1 2 3 4 5 6 7 8 |
# Program which uses a file file = open('D:\\lib\\file.txt','r') # the line above opens D:\\lib\\file.txt for reading line = file.readline() # reads single line print(line) |
Program 88: Program which uses a file
1 2 3 4 5 6 7 8 9 10 |
# Program which uses a file file = open('D:\\lib\\file.txt','w') print(file) # prints out details about the file file.write("Today is Monday\n") file.write("Tomorrow is Tuesday") file.close() |
Program 89: Program which uses a file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Program which uses a file file1 = open('D:\\lib\\file1.txt','r') file2 = open('D:\\lib\\file2.txt','r') print(file1) # prints out details about the file string1 = file1.read() print(string1) file1.close() string2 = file2.read(5) print(string2) string2 = file2.read(5) print(string2) string2 = file2.read(5) print(string2) file2.close() |
Program 90: Program which uses a file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Program which uses a file file1 = open('D:\\lib\\file1.txt','r') file2 = open('D:\\lib\\file2.txt','w') while 1: text = file1.read(50) if text == "": break file2.write(text) file1.close() file2.close() |
Object Oriented
Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python’s object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.
However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed
Overview of OOP Terminology
- Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
- Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods. Class variables are not used as frequently as instance variables are.
- Data member − A class variable or instance variable that holds data associated with a class and its objects.
- Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
- Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
- Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
- Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
- Instantiation − The creation of an instance of a class.
- Method − A special kind of function that is defined in a class definition.
- Object − A unique instance of a data structure that’s defined by its class. An object comprises both data members (class variables and instance variables) and methods.
- Operator overloading − The assignment of more than one function to a particular operator.
Program 91: Create objects of the Person class and how to inspect the state of those objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Person(): '''Instantiates a Person object with given name. ''' def __init__(self, first_name, last_name): '''Initializes private instance variables _firstname and _lastname. ''' self._firstname = first_name self._lastname = last_name def __str__(self): '''Returns the state of the Person object. ''' return self._firstname + " " + self._lastname print(Person.__doc__) # prints the docstring for the class person1 = Person("May","Lindia") person2 = Person("Jane","Timoty") print(person1) print(person2) |
Program 92: Use accessor methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Use accessor methods class Person(): '''Instantiates a Person object with given name. ''' def __init__(self, first_name, last_name): '''Initializes private instance variables _firstname and _lastname. ''' self._firstname = first_name self._lastname = last_name def __str__(self): '''Returns the state of the Person object. ''' return self._firstname + " " + self._lastname def getFirstname(self): # accessor method '''Returns the instance variable _firstname. ''' return self._firstname def getLastname(self): # accessor method '''Returns the instance variable _lastname. ''' return self._lastname print(Person.__doc__) # prints the docstring for the class person1 = Person("May","Lindia") person2 = Person("Jane","Rome") print(person1) # calls the __str__ method implicitly on person1 object print(person2) # calls the __str__ method implicitly on person2 object print(Person.getFirstname.__doc__) # prints the docstring for the getFirstname method print(person1.getFirstname()) print(person1.getLastname()) print(person2.getFirstname()) print(person2.getLastname()) |
Program 93: Use accessor and mutator methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# Use accessor and mutator methods class Person(): '''Instantiates a Person object with given name. ''' def __init__(self, first_name, last_name): '''Initializes private instance variables _firstname and _lastname. ''' self._firstname = first_name self._lastname = last_name def __str__(self): '''Returns the state of the Person object. ''' return self._firstname + " " + self._lastname def getFirstname(self): # accessor method '''Returns the instance variable _firstname. ''' return self._firstname def getLastname(self): # accessor method '''Returns the instance variable _lastname. ''' return self._lastname def setFirstname(self,newFirstname): # mutator method '''Assign a value to the instance variable _firstname. ''' self._firstname = newFirstname def setLastname(self,newLastname): # mutator method '''Assign a value to the instance variable _lastname. ''' self._lastname = newLastname print(Person.__doc__) # prints the docstring for the class person1 = Person("May","Lindia") person2 = Person("Jane","Rome") print(person1) # calls the __str__ method implicitly on person1 object print(person2) # calls the __str__ method implicitly on person2 object print(Person.getFirstname.__doc__) # prints the docstring for the getFirstname method print(person1.getFirstname()) print(person1.getLastname()) print(person2.getFirstname()) print(person2.getLastname()) person1.setFirstname("Yummy") print(person1.getFirstname()) |
Source:
www.annedawson.net
www.tutorialspoint.com