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
Python Print
The print
function in Python is used to display output to the console or terminal. Here is an example of how to use it:
Program1.py
1 2 3 | print("Hello World!") |
This will print the string “Hello, World!” to the console.
You can also use the print
function to print the value of a variable. For example:
Program2.py
1 2 3 4 | name = "John" print(name) |
This will print the string “John” to the console.
You can also use the print
function to print multiple values, separating them with a comma. For example:
Program3.py
1 2 3 4 5 | x = 10 y = 20 print(x, y) |
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.
The input
function in Python allows the user to enter input from the console or terminal. Here is an example of how to use it:
Program4.py
1 2 3 4 | text= input("Enter your name: ") print("Hello, " + 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.
This will prompt the user to enter their name, and then it will print a greeting using the name that the user entered.
The input
function returns a string, so if you want to use the input as a number (integer or float), you will need to convert it to the appropriate type. For example:
Program5.py
1 2 3 4 5 | age = input("Enter your age: ") age = int(age) # convert the input to an integer print("You are " + str(age) + " years old.") |
This will prompt the user to enter their age, and then it will convert the input to an integer and print a message using the age.
The Assignment symbol =
In Python, the assignment operator is the equals sign =
. It is used to assign a value to a variable. For example:
1 2 3 | x = 10 |
This assigns the value 10
to the variable x
.
You can also use the assignment operator to assign the value of an expression to a variable. For example:
1 2 3 | x = 2 * 3 |
This assigns the value 6
to the variable x
.
You can also use the assignment operator to assign the value of one variable to another variable. For example:
1 2 3 4 | x = 10 y = x |
This assigns the value of x
(which is 10
) to the variable y
.
It’s important to note that the assignment operator =
is different from the equality operator ==
, which is used to test if two values are equal. For example:
Program6.py
1 2 3 4 5 6 7 8 | x = 10 y = 20 if x == y: print("x and y are equal") else: print("x and y are not equal") |
This will print “x and y are not equal”, because x
is not equal to y
.
Built-in functions
input(), int() and float() , str() are built-in Python functions. They can be used at any time in any Python statement.
The input
function allows the user to enter input from the console or terminal. It returns a string, so if you want to use the input as a number (integer or float), you will need to convert it to the appropriate type using int
or float
.
The int
function converts a value to an integer. If the value is a floating-point number, it will be rounded down to the nearest integer.
The float
function converts a value to a floating-point number.
The str
function converts a value to a string. This can be useful if you need to concatenate a string with a number, for example.
Here are some examples of how these functions can be used:
Program7.py
1 2 3 4 5 6 7 8 9 10 | # get user input and convert it to an integer age = int(input("Enter your age: ")) # get user input and convert it to a float weight = float(input("Enter your weight: ")) # convert an integer to a string and concatenate it with another string message = "You are " + str(age) + " years old." |
Data types of input values
The type
function is a built-in function in Python that returns the data type of a value.
Here is an example of how to use it:
Program8.py
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)) |
This can be useful for debugging, or for checking the data type of a value before performing certain operations on it. For example, you might want to make sure that a value is a string before concatenating it with another string.
Program9.py: 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) |
In Python, the string "\n"
represents a newline character, which is a special character that causes the text that follows it to be displayed on a new line.
Here is an example of how to use it:
Program10.py
1 2 3 4 5 6 7 8 9 | 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)  |
To use a variable in Python, you first need to assign a value to the variable. This is done using the assignment operator =
. For example:
Program11.py
1 2 3 4 5 6 | message = "Enter a some text " text = input(message) print("This is what you entered:") print(text) |
You can also reassign a new value to a variable by using the assignment operator again. For example:
Program12.py
1 2 3 4 5 6 7 | x = 10 print(x) # prints 10 x = 15 print(x) # prints 15 |
It’s important to choose descriptive and meaningful variable names, as this will make your code easier to read and understand.
Program3.py : 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) |
This code calculates the average of three numbers that are entered by the user. Here’s how it works:
The code prompts the user to enter the first, second, and third numbers, and stores them in the variables number1
, number2
, and number3
.
The code adds the three numbers together and stores the result in the total
variable.
The code divides the total
by 3 to calculate the average, and stores the result in the average
variable.
The code prints the value of the average
variable using two different print statements.
Here’s what the output might look like if the user enters the numbers 15, 20, and 25:
Program14.py: Calculate the Average of Numbers in a Given List
This code calculates the average of a list of numbers that are entered by the user. Here’s how it works:
The code prompts the user to enter the number of elements to be inserted into the list, and stores it in the number
variable.
The code creates an empty list called array
, and then uses a for
loop to prompt the user to enter each element of the list. The elements are added to the list using the append
method.
The code calculates the sum of the elements in the list using the sum
function, and divides it by the number of elements to calculate the average. The result is stored in the avg
variable.
The code prints the value of the avg
variable, rounded to two decimal places using the round
function.
Here’s what the output might look like if the user enters the numbers 10, 20, and 30:
1 2 3 4 5 6 7 | Enter the number of elements to be inserted: 3 Enter element: 10 Enter element: 20 Enter element: 30 Average of elements in the list 20.0 |
Program15.py : 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)) |
This code calculates the average of three numbers that are entered by the user using a while
loop. Here’s how it works:
The code initializes the variables total
and count
to 0.0 and 0, respectively.
The code enters a while
loop that will continue to run as long as count
is less than 3.
Inside the loop, the code prompts the user to enter a number and stores it in the number
variable.
The code increments the value of count
by 1 using count = count + 1
.
The code adds the value of number
to the total
using total = total + number
.
After the loop has finished running 3 times, the code calculates the average by dividing total
by 3 and stores the result in the average
variable.
The code prints the value of average
, converted to a string using the str
function.
Here’s what the output might look like if the user enters the numbers 10, 20, and 30:
1 2 3 4 5 6 | Enter a number: 10 Enter a number: 20 Enter a number: 30 The average is 20.0 |
Examples of use of arithmetic operators
Program16.py : 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 |
This code demonstrates the use of several arithmetic operators in Python:
The +
operator is used to add two values together. In this case, it prints the value 3
.
The -
operator is used to subtract one value from another. In this case, it prints the value 3
.
The *
operator is used to multiply two values together. In this case, it prints the value 40
.
The /
operator is used to divide one value by another. In this case, it prints the value 2.0
.
The %
operator is used to calculate the remainder when one value is divided by another. In this case, it prints the value 0
.
The //
operator is used to perform floor division, which always truncates the fractional remainder. In this case, it prints the value 3
.
The -
operator can also be used to negate a value. In this case, it prints the value -10
.
The **
operator is used to raise a value to a power. In this case, it prints the value 243
.
Program17.py :
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 |
This code demonstrates the use of several arithmetic operators in Python, using floating-point numbers as the operands:
The +
operator is used to add two values together. In this case, it prints the value 3.0
.
The -
operator is used to subtract one value from another. In this case, it prints the value 3.0
.
The *
operator is used to multiply two values together. In this case, it prints the value 12.0
.
The /
operator is used to divide one value by another. In this case, it prints the value 3.0
.
The %
operator is used to calculate the remainder when one value is divided by another. In this case, it prints the value 0.0
.
The //
operator is used to perform floor division, which always truncates the fractional remainder. In this case, it prints the value 3.0
.
The -
operator can also be used to negate a value. In this case, it prints the value -15.0
.
The **
operator is used to raise a value to a power. In this case, it prints the value 243.0
.
Examples of use of Boolean expressions
Program18.py: 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) |
This code demonstrates the use of several Boolean operators in Python, which are used to test the truth or falsehood of a statement.
The >
operator is used to test if one value is greater than another. In this case, it prints False
because 5 is not greater than 10.
The <
operator is used to test if one value is less than another. In this case, it prints True
because 2 is less than 16.
The ==
operator is used to test if two values are equal. In this case, it prints True
because 5 is equal to 5.
The <=
operator is used to test if one value is less than or equal to another. In this case, it prints True
because 7 is equal to 7.
The >=
operator is used to test if one value is greater than or equal to another. In this case, it prints True
because 7 is equal to 7.
The !=
operator is used to test if two values are not equal. In this case, it prints False
because 10.0 is equal to 10.
You may also like: Python Code Examples
Program19.py: 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) |
This code demonstrates the use of string objects and string assignments in Python.
The print
function is used to print two string literals, which are strings that are written directly in the code. The first string is surrounded by double quotes, and the second string is surrounded by single quotes.
The code assigns the string “Hello out there” to the variable a1
and prints it.
The code assigns the string “Hello” to the variable a2
and prints it.
The code assigns the strings “Hello” and “World” to the variables b1
and b2
, respectively.
The code concatenates the two strings using the +
operator and assigns the result to the c
variable.
The code prints the value of the c
variable, which is the concatenation of the strings “Hello” and “World”.
The output of this code will be:
1 2 3 4 5 6 7 | Hello out there Hello Hello out there Hello HelloWorld |
Program20.py : 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) |
This code demonstrates how to concatenate a string and an integer in Python by first converting the integer to a string using the str
function.
The code assigns the strings “Hello” and ” World” to the variables a
and b
, respectively, and concatenates them using the +
operator. The result is assigned to the c
variable and printed.
The code concatenates the c
variable, which is a string, with the string representation of the integer 10
, which is obtained using the str
function. The result is assigned to the d
variable and printed.
The output of this code will be:
1 2 3 4 | Hello World Hello World10 |
Program21.py : 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) |
This code demonstrates two ways to round a floating-point number to the nearest integer in Python.
The code prints the value of the x
variable, which is 2.6.
The code uses the round
function to round the value of x
to the nearest integer and assigns the result back to the x
variable. The value of x
is then printed again.
The code uses the int
function to truncate the fractional part of the value of x
and assigns the result back to the x
variable. The value of x
is then printed again.
The output of this code will be:
1 2 3 4 5 | 2.6 3 2 |
Program22.py : 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) |
This code demonstrates how to round a floating-point number to two decimal places and format it as a currency value with a comma separating the thousands.
The code prints the value of the number
variable, which is 5274.2578.
The code uses the round
function to round the value of number
to two decimal places and assigns the result back to the number
variable. The value of number
is then printed again.
The code divides the value of number
by 1000 and assigns the result to the thousands
variable. The value of thousands
is then printed.
The code uses the int
function to truncate the fractional part of the value of thousands
and assigns the result back to the thousands
variable. The value of thousands
is then printed again.
The code calculates the remainder when number
is divided by 1000 and assigns the result to the remainder
variable. The value of remainder
is then printed.
The code concatenates the string “€”, the string representation of thousands
, a comma, and the string representation of remainder
using the +
operator. The result is assigned to the formatted_output
variable and printed.
The output of this code will be:
1 2 3 4 5 6 7 8 | 5274.2578 5274.26 5.2742578 5 274.26 €5,274.26 |
Program23.py: 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)) |
This code demonstrates how to convert one data type to another in Python.
The code prompts the user to enter a number and stores it in the number1
variable as a string. The value of number1
and its data type are printed.
The code uses the int
function to convert the string value of number1
to an integer and assigns the result back to the number1
variable. The value of number1
and its data type are printed again.
Here’s an example of what the output might look like if the user enters the number 10
:
1 2 3 4 5 | Enter first number: 10 10 <class 'str'> 10 <class 'int'> |
Program24.py: 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)) |
This code demonstrates how to display the memory location of an object in Python using the id
function.
The code prompts the user to enter a number and stores it in the number1
variable as a string. The value of number1
, its data type, and its memory location are printed.
The code uses the int
function to convert the string value of number1
to an integer and assigns the result back to the number1
variable. The value of number1
, its data type, and its memory location are printed again.
Here’s an example of what the output might look like if the user enters the number 10
:
1 2 3 4 5 | Enter first number: 10 10 <class 'str'> 1647013588304 10 <class 'int'> 140732085073840 |
The memory location is represented as a hexadecimal number, which is the address in memory where the object is stored. Note that the memory location of the object changes after it is converted to an integer, because a new object is created and the original string object is no longer referenced.
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) |
Program25.py : Displaying boolean values
1 2 3 4 5 6 | #Displaying boolean values number = 10 isPositive = (number > 0) print(isPositive) |
This code demonstrates how to display a boolean value in Python.
The code assigns the value 10
to the number
variable.
The code uses the >
operator to test if number
is greater than 0 and assigns the result to the isPositive
variable.
The code prints the value of isPositive
, which is a boolean value indicating whether number
is positive or not.
The output of this code will be:
1 2 3 | True |
Program26.py: 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)) |
This code demonstrates how to combine two boolean expressions using the and
operator in Python.
The code assigns the values 25
and 55000
to the age
and salary
variables, respectively.
The code uses the and
operator to combine two boolean expressions that test if age
is greater than 21 and if salary
is greater than 50000. The result is printed.
The output of this code will be:
1 2 3 | True |
The and
operator returns True
only if both of the expressions on either side of it are True
. If either of the expressions is False
, the and
operator returns False
.
Program27.py :Â 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') |
This code demonstrates the use of the if
statement in Python.
The if
statement tests if the value of the a
variable is equal to the string 'world'
. If the test is True
, the code inside the if
block is executed. If the test is False
, the code inside the else
block is executed.
In this case, the value of a
is 'world'
, so the test evaluates to True
and the code inside the if
block is executed. The output of this code will be:
1 2 3 | It is world |
Program28.py : 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') |
This code demonstrates how to use the if
statement with multiple statements in Python.
The if
statement tests if the value of the x
variable is equal to the string 'April'
. If the test is True
, the code inside the if
block is executed. If the test is False
, the code inside the else
block is executed.
In this case, the value of x
is 'April'
, so the test evaluates to True
and the code inside the if
block is executed. The \n
characters in the first print
statement are used to print a new line, so the output will be:
1 2 3 4 5 6 | Hi April Nice weather we're having Have a nice day! |
Program29.py : 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?') |
In this code, the if statement checks whether the value of x
is equal to 'May'
. If it is, it prints three lines of text. If it is not, it prints two lines of text.
The if
statement is followed by a condition, which is an expression that evaluates to either True
or False
. If the condition is True
, the indented block of code following the if
statement is executed. If the condition is False
, the indented block of code following the else
statement is executed.
In this case, since the value of x
is 'April'
, the condition x == 'May'
evaluates to False
, so the code in the else
block is executed. This will print the following lines of text:
1 2 3 4 | not April Not having a good day? |
Program30.py :Â 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) |
This code prompts the user to enter a score, which is then converted to an integer and stored in the score
variable.
The code then checks if the score is greater than or equal to 80. If it is, the grade is set to 'A'
. If the score is not greater than or equal to 80, the code enters the else
block and checks if the score is greater than or equal to 70. If it is, the grade is set to 'B'
. If the score is not greater than or equal to 70, the grade is set to 'C'
.
Finally, the code prints the grade.
Here’s an example of how the program could be run:
1 2 3 4 5 6 7 8 9 10 11 12 | Enter score: 85 Grade is: A Enter score: 65 Grade is: C |
Program31.py: 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) |
This code prompts the user to enter a score, which is then converted to an integer and stored in the score
variable.
The code then checks if the score is greater than or equal to 80. If it is, the grade is set to 'A'
. If the score is not greater than or equal to 80, the code enters the else
block and checks if the score is greater than or equal to 70. If it is, the grade is set to 'B'
. If the score is not greater than or equal to 70, the code enters the next else
block and checks if the score is greater than or equal to 55. If it is, the grade is set to 'C'
. If the score is not greater than or equal to 55, the code enters the next else
block and checks if the score is greater than or equal to 50. If it is, the grade is set to 'Pass'
. If the score is not greater than or equal to 50, the grade is set to 'Fail'
.
Finally, the code prints the grade.
Here’s an example of how the program could be run:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Enter score: 85 Grade is: A Enter score: 65 Grade is: C Enter score: 45 Grade is: Fail |
Program 32.py:Â 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) |
This code prompts the user to enter a score, which is then converted to an integer and stored in the score
variable.
The code then uses an if
–elif
–else
statement to check the score and assign a grade. The if
statement checks if the score is greater than 80 or equal to 80. If it is, the grade is set to 'A'
. If the score is not greater than or equal to 80, the code enters the elif
block and checks if the score is greater than 70 or equal to 70. If it is, the grade is set to 'B'
. This process continues until the score is checked against all of the conditions, or until a grade is assigned. If none of the conditions are met, the code in the else
block is executed and the grade is set to 'Fail'
.
Finally, the code prints the grade.
Here’s an example of how the program could be run:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Enter score: 85 Grade is: A Enter score: 65 Grade is: C Enter score: 45 Grade is: Fail |
Program 33.py:Â 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 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) |
This code prompts the user to enter a score, which is then converted to an integer and stored in the score
variable.
The code then uses an if
–elif
–else
statement to check the score and assign a grade. The if
statement checks if the score is greater than 80 or equal to 80. If it is, the grade is set to 'A'
. If the score is not greater than or equal to 80, the code enters the elif
block and checks if the score is greater than 70 or equal to 70. If it is, the grade is set to 'B'
. This process continues until the score is checked against all of the conditions, or until a grade is assigned. If none of the conditions are met, the code in the else
block is executed and the grade is set to 'Fail'
.
Finally, the code prints the grade.
Here’s an example of how the program could be run:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Enter score: 85 Grade is: A Enter score: 65 Grade is: C Enter score: 45 Grade is: Fail |
Program 34.py:Â 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 33 | #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")  |
This code prompts the user to enter their age and whether they own their own car. It then uses multiple if
statements to check the values of these variables and print different messages based on the combination of values.
The first set of if
statements use the and
operator to check if the age is greater than 21 and the user owns their own car, or if the age is greater than 21 and the user does not own their own car, or if the age is equal to 21 and the user owns their own car, or if the age is equal to 21 and the user does not own their own car, or if the age is less than 21 and the user owns their own car, or if the age is less than 21 and the user does not own their own car.
The second if
statement uses the or
operator to check if the salary is greater than $50000 or if the age is greater than 21. If either of these conditions is true, the message “you can join our club because you earn more than $50000 OR you are over 21 (or both)” is printed. If neither of these conditions is true, the message “you need to be earning more than 50000 OR be over 21 (or both) to join our club” is printed.
Here’s an example of how the program could be run:
1 2 3 4 5 6 | Enter your age: 25 Do you own your own car (y/n): y You are over 21 years old and own your own car you can join our club because you earn more than $50000 OR you are over 21 (or both) |
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 35.py: Examples of while loops
1 2 3 4 5 6 7 | x = 1 while x < 5: print('Hi World') x = x + 1 print('done') |
This code will print 'Hi World'
four times, followed by 'done'
.
The while
loop will continue to execute the code block inside of it as long as the condition x < 5
is True
. At the end of each iteration, the value of x
is incremented by 1, so the condition will eventually become False
, causing the loop to exit.
Here is the output of this code:
1 2 3 4 5 6 7 | Hi World Hi World Hi World Hi World done |
Program 36.py: 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') |
This code will print 'Hi World'
, followed by 'I love World'
, four times, followed by 'done'
, followed by 'gone'
.
The while
loop will continue to execute the code block inside of it as long as the condition x < 5
is True
. At the end of each iteration, the value of x
is incremented by 1, so the condition will eventually become False
, causing the loop to exit.
Here is the output of this code:
1 2 3 4 5 6 7 8 9 10 11 12 | Hi World I love World Hi World I love World Hi World I love World Hi World I love World done gone |
Program 37.py:Â 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') |
This code will create an infinite loop that will continue to print 'Hi world'
, 'I love world'
, 'Press the Ctrl key and the C key together'
, and 'to interrupt this program...'
indefinitely.
The condition for the while
loop is x
, which is initially True
because x
is assigned the value 1
. The while
loop will therefore continue to execute the code block inside of it indefinitely, unless the loop is interrupted by pressing the Ctrl+C
keys together.
To prevent the infinite loop, you can add a condition that will cause the loop to exit when a certain criteria is met. For example, you could add a break
statement to the loop to cause it to exit when a certain condition is met:
Program 38.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 | x = 1 while x: print('Hi world') x = x + 1 print('I love world') if x > 5: # Add this line break # Add this line print('Press the Ctrl key and the C key together') print('to interrupt this program...') print('done') print('gone') |
This modified version of the code will print 'Hi world'
and 'I love world'
five times, followed by 'done'
and 'gone'
.
Program 39.py:Â 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') |
This code will create an infinite loop that will continue to print 'Hello World!'
, 'Press the Ctrl key and the C key together'
, and 'to interrupt this program...'
indefinitely.
The condition for the while
loop is 1
, which is always True
, so the while
loop will continue to execute the code block inside of it indefinitely, unless the loop is interrupted by pressing the Ctrl+C
keys together.
To prevent the infinite loop, you can add a condition that will cause the loop to exit when a certain criteria is met. For example, you could add a break
statement to the loop to cause it to exit when a certain condition is met:
Program40.py
1 2 3 4 5 6 7 8 9 10 11 12 | x = 0 while 1: x += 1 print('Hello World! ') if x > 5: # Add this line break # Add this line print('Press the Ctrl key and the C key together') print('to interrupt this program...') print('done') print('gone') |
This modified version of the code will print 'Hello World!'
six times, followed by 'done'
Program 41.py:Â 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!') |
The break
statement will cause the program to exit the innermost loop that it is currently in. In this case, the break
statement will cause the program to exit the infinite while
loop when the user inputs ‘y’. The program will then continue to execute the statements following the loop.
Here is how the output of the program would look like:
1 2 3 4 5 6 7 | Hello Press y to end this loopy Can it break? Have a nice day! |
Program 42.py:Â 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!') |
The continue
statement will cause the program to skip the rest of the current iteration of the loop and continue with the next iteration. In this case, when the user inputs ‘y’, the program will skip the second input
statement and the break
statement and continue with the next iteration of the loop.
Here is how the output of the program would look like:
1 2 3 4 5 6 7 8 9 | Hello Press y for continue back y You will continue back now! Hello Press y for continue back y You will continue back now! ... |
The loop will continue indefinitely until the user inputs ‘y’ in response to the second input
statement, at which point the break
statement will be executed and the loop will exit. The program will then continue to execute the statements following the loop.
1 2 3 4 5 6 7 | Hello Press y for continue back n Had enough yet? y Have a nice day! |
Program 43.py: ‘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") |
In this program, the sentinel value 0
is used to signal the end of the input phase. The program prompts the user to enter a score, and the input is converted to an integer and stored in the variable score
. The while
loop then continues to execute as long as score
is not equal to 0
.
At each iteration of the loop, the value of score
is added to the running total totalScore
and the count of the number of scores entered is incremented by 1
. The program then prompts the user to enter the next score.
When the user enters 0
, the loop terminates, and the program enters the termination phase. In the termination phase, the program checks if any scores were entered by checking if numberScores
is equal to 0
. If numberScores
is not equal to 0
, the program calculates the average score by dividing totalScore
by numberScores
and prints the result. If numberScores
is equal to 0
, the program prints a message indicating that no scores were entered.
Here is an example of how the output of the program might look:
1 2 3 4 5 6 7 8 9 | Enter score, (Enter 0 to end): 85 Enter score, (Enter 0 to end): 95 Enter score, (Enter 0 to end): 75 Enter score, (Enter 0 to end): 70 Enter score, (Enter 0 to end): 80 Enter score, (Enter 0 to end): 0 Class average is 79.16666666666667 |
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 44.py: 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) |
In this program, the for
loop will iterate 10 times. At each iteration, the loop variable c
will take on the value of the current iteration number, starting from 0
and ending at 9
.
The range
function generates a sequence of numbers from 0
to 9
, and the for
loop iterates over this sequence.
The output of the program will be the numbers 0
through 9
printed on separate lines.
1 2 3 4 5 6 7 8 9 10 11 12 | 0 1 2 3 4 5 6 7 8 9 |
Program 45.py:Â 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) |
In this program, the for
loop will iterate 5 times. At each iteration, the loop variable c
will take on the value of the current iteration number, starting from 5
and ending at 9
.
The range
function generates a sequence of numbers from 5
to 9
, and the for
loop iterates over this sequence.
The output of the program will be the numbers 5
through 9
printed on separate lines.
1 2 3 4 5 6 7 | 5 6 7 8 9 |
Program 46.py: ‘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) |
In this program, the for
loop will iterate 5 times. At each iteration, the loop variable c
will take on the value of the current iteration number, starting from 1
and ending at 5
.
The range
function generates a sequence of numbers from 1
to 5
, and the for
loop iterates over this sequence.
If the value of c
is equal to 3
, the continue
statement is executed, which causes the program to skip the rest of the current iteration and continue with the next iteration. This means that the print
statement will not be executed when c
is equal to 3
, and the number 3
will not be printed.
The output of the program will be the numbers 1
, 2
, 4
, and 5
printed on separate lines.
1 2 3 4 5 6 | 1 2 4 5 |
Program 47.py: ‘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) |
In this program, the for
loop will iterate 5 times. At each iteration, the loop variable c
will take on the value of the current iteration number, starting from 1
and ending at 5
.
The range
function generates a sequence of numbers from 1
to 5
, and the for
loop iterates over this sequence.
If the value of c
is equal to 3
, the break
statement is executed, which causes the program to exit the for
loop. This means that the for
loop will terminate after the second iteration, and the print
statement will not be executed for the remaining iterations.
The output of the program will be the numbers 1
and 2
printed on separate lines.
1 2 3 4 | 1 2 |
Program 48.py: 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') |
In this program, the print
statement will output the string 'Total is: '
followed by the value of the variables d
and c
, which are 10
and 75
, respectively. The string 'dollars and'
and the string ' cents'
are also output.
The output of the program will be:
1 2 3 | Total is: 10 dollars and 75 cents |
Note that the print
function automatically inserts a space between the strings and variables being printed, so you do not need to manually add a space between the strings and variables.
Program 49.py: 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)) |
In this program, the print
function is used to output strings and variables using string formatting. String formatting allows you to embed variables within a string and specify how the variables should be formatted.
The %
operator is used to specify a placeholder for a variable in the string. The placeholder consists of a %
followed by a format specifier, which determines how the variable should be formatted. For example, %s
is used to specify a string placeholder, %d
is used to specify an integer placeholder, and %f
is used to specify a floating point placeholder.
The variables to be formatted are provided as a tuple after the string, and the tuple is placed inside the %
operator.
Here is the output of the program:
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 | My fullname is Mary Brown The sum of 40 and 15 is 55 The sum of 40 and 15 is 55 The sum of 20.253 and 15.654 is 35.907 The sum of 20.25 and 15.65 is 35.91 The sum of 20.253 and 15.654 is 35.907 The decimal number 0 in hexadecimal is 0 The decimal number 1 in hexadecimal is 1 The decimal number 2 in hexadecimal is 2 The decimal number 3 in hexadecimal is 3 The decimal number 4 in hexadecimal is 4 The decimal number 5 in hexadecimal is 5 The decimal number 6 in hexadecimal is 6 The decimal number 7 in hexadecimal is 7 The decimal number 8 in hexadecimal is 8 The decimal number 9 in hexadecimal is 9 The decimal number 10 in hexadecimal is a The decimal number 11 in hexadecimal is b The decimal number 12 in hexadecimal is c The decimal number 13 in hexadecimal is d The decimal number 14 in hexadecimal is e The decimal number 15 in hexadecimal is f The decimal number 16 in hexadecimal is 10 The decimal number 17 in hexadecimal is 11 |
Program 50.py: 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!") |
In this program, the while
loop will execute as long as the value of the variable answer
is either 'y'
or 'Y'
.
The loop will execute once initially, and at the end of each iteration, the program will prompt the user to enter 'y'
or 'n'
. If the user enters 'y'
, the loop will continue to execute. If the user enters 'n'
, the loop will exit and the program will continue to the next statement after the loop.
Here is an example of how the output of the program might look:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | This is the start of the program This is a statement from within the while loop This is another statement from within the while loop Do you want to run this program again? y/nn Goodbye! This is the start of the program This is a statement from within the while loop This is another statement from within the while loop Do you want to run this program again? y/ny This is a statement from within the while loop This is another statement from within the while loop Do you want to run this program again? y/nn Goodbye! |
Program 51.py: 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 |
In this program, the outer while
loop will execute 3 times, and at each iteration, it will print a new line and the value of x
. The inner while
loop will also execute 3 times, and at each iteration, it will print the value of y
on the same line as the value of x
.
The output of the program will be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | x = 1 y = 1 y = 2 y = 3 x = 2 y = 1 y = 2 y = 3 x = 3 y = 1 y = 2 y = 3 |
Program 52.py: 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 |
In this program, the outer while
loop will execute 2 times, and at each iteration, it will print a new line and the value of x
. The middle while
loop will also execute 2 times, and at each iteration, it will print the value of y
on the same line as the value of x
. The inner while
loop will execute 2 times at each iteration of the middle while
loop, and it will print the value of z
on the same line as the value of y
.
The output of the program will be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | x = 1 y = 1 z = 1 z = 2 y = 2 z = 1 z = 2 x = 2 y = 1 z = 1 z = 2 y = 2 z = 1 z = 2 |
Program 53.py: 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() |
In this program, the outer for
loop will iterate 5 times, and at each iteration, it will execute the inner for
loop. The inner for
loop will also iterate 5 times, and at each iteration, it will print a string containing the values of i
and j
.
The output of the program will be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | i: 2 j: 2 i: 2 j: 3 i: 2 j: 4 i: 2 j: 5 i: 3 j: 1 i: 3 j: 2 i: 3 j: 3 i: 3 j: 4 i: 3 j: 5 i: 4 j: 1 i: 4 j: 2 i: 4 j: 3 i: 4 j: 4 i: 4 j: 5 i: 5 j: 1 i: 5 j: 2 i: 5 j: 3 i: 5 j: 4 i: 5 j: 5 |
Program 54.py: 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() |
In this program, the outer for
loop will iterate 3 times, and at each iteration, it will execute the middle for
loop. The middle for
loop will also iterate 3 times, and at each iteration, it will execute the inner for
loop. The inner for
loop will iterate 3 times, and at each iteration, it will print a string containing the values of i
, j
, and k
.
The output of the program will be:
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 | i: 1 j: 1 k: 1 i: 1 j: 1 k: 2 i: 1 j: 1 k: 3 i: 1 j: 2 k: 1 i: 1 j: 2 k: 2 i: 1 j: 2 k: 3 i: 1 j: 3 k: 1 i: 1 j: 3 k: 2 i: 1 j: 3 k: 3 i: 2 j: 1 k: 1 i: 2 j: 1 k: 2 i: 2 j: 1 k: 3 i: 2 j: 2 k: 1 i: 2 j: 2 k: 2 i: 2 j: 2 k: 3 i: 2 j: 3 k: 1 i: 2 j: 3 k: 2 i: 2 j: 3 k: 3 i: 3 j: 1 k: 1 i: 3 j: 1 k: 2 i: 3 j: 1 k: 3 i: 3 j: 2 k: 1 i: 3 j: 2 k: 2 i: 3 j: 2 k: 3 i: 3 j: 3 k: 1 i: 3 j: 3 k: 2 i: 3 j: 3 k: 3 |
Program 55.py: 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)) |
In this program, the math
module is imported, which provides mathematical functions that can be used in the program.
The sqrt
function is used to calculate the square root of a number. The square root of a number is a value that, when multiplied by itself, gives the original number.
The sqrt
function takes a single argument, which is the number for which you want to calculate the square root. The function returns a floating point value representing the square root of the number.
The print
function is used to print the output of the sqrt
function to the console.
The output of the program will be:
1 2 3 4 5 | 4.0 4.041451884327381 12.0 |
Program 56.py: 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)) |
In this program, the math
module is imported, which provides mathematical functions that can be used in the program.
The print
function is used to print the math
module to the console. This will output the module object itself, which is not very useful.
The dir
function is used to get a list of all the names defined in the math
module. This list includes functions, variables, and other objects defined in the module. The dir
function takes a single argument, which is the object for which you want to get the list of names.
The print
function is then used to print the output of the dir
function to the console.
The output of the program will be:
1 2 3 4 | <module 'math' (built-in)> ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] |
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 57.py: 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") |
This output is produced by the print statements in each of the functions you defined. The greeting()
function prints “Hello” to the console each time it is called. The many_greetings(4)
function prints “Hello Again!” four times to the console. The many_greetings_with_name(x, " Mary")
function prints “Hello Again Mary!” to the console the number of times specified by the value of x
.
Here is the output that you would see if you ran the code you provided:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Hello Hello Hello Hello Hello Hello Again! Hello Again! Hello Again! Hello Again! How many greetings do you want?: 4 Hello Again Mary! Hello Again Mary! Hello Again Mary! Hello Again Mary! |
Program 58.py: 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) |
This code defines a function called cube
that takes a single argument y
and returns the cube of y
.
Then it prints the cube of numbers 1 to 5 by calling the cube
function in a loop that iterates over the range 1, 2, 3, 4, 5
.
Finally, it prints the value of x
after the loop has completed, which is 5
. The output of the code will be:
1 2 3 4 5 6 7 8 | 1 8 27 64 125 last value of x is: 5 |
Program 59.py: 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),) |
This code defines two functions: cube
and doubleIt
. The cube
function takes a single argument y
and returns the cube of y
. The doubleIt
function takes a single argument z
and returns twice the value of z
.
Then it prints the cube of numbers 1 to 5 by calling the cube
function in a loop that iterates over the range 1, 2, 3, 4, 5
. It prints a blank line after the loop.
Then it prints the double of numbers 1 to 5 by calling the doubleIt
function in a loop that iterates over the range 1, 2, 3, 4, 5
.
The output of the code will be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 1 to 5 cubed 1 8 27 64 125 1 to 5 doubled 2 4 6 8 10 |
Program 60.py: 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),) |
This is a program that defines two functions, cube
and doubleIt
, and then imports them into the main program. The cube
function takes in a number y
and returns the cube of y
, while the doubleIt
function takes in a number z
and returns 2 * z
.
After the functions are imported, the program prints the cubes of the numbers 1 to 5 and the double of the numbers 1 to 5. The for
loop iterates through the numbers 1 to 5, and for each number, the function cube
or doubleIt
is called with that number as the argument. The result of the function is then printed to the screen.
For example, when x
is 3, myFun.cube(x)
is called and returns 27
. Similarly, when x
is 4, myFun.doubleIt(x)
is called and returns 8
.
Program 61.py: Function with no return statement
1 2 3 4 5 6 7 8 9 10 11 12 13 | # 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)  |
This is a program that defines a function called times
that takes in a number x
and prints the x
times tables from 1 to 10. The function has no return statement, so it returns None
.
The function is called twice, with 1
and 2
as the arguments. When the function is called with 1
as the argument, it prints the 1 times table, and when it is called with 2
as the argument, it prints the 2 times table.
For example, when x
is 1, the function prints:
1 2 3 4 5 6 7 8 9 10 11 12 | 1 x 1 = 1 2 x 1 = 2 3 x 1 = 3 4 x 1 = 4 5 x 1 = 5 6 x 1 = 6 7 x 1 = 7 8 x 1 = 8 9 x 1 = 9 10 x 1 = 10 |
Program 62.py: Function with two return statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # 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)  |
This is a program that defines a function called division
that takes in two numbers, x
and y
, and returns the result of x / y
. The function has two return statements.
The first return statement is executed if y
is equal to 0
. In this case, the function prints a message indicating that division by zero is not allowed, and then returns None
.
The second return statement is executed if y
is not equal to 0
. In this case, the function prints a message indicating that it is returning the result of x / y
, and then returns the result of the division.
The function is called twice, with 5.0
and 2
as the first set of arguments, and with 5.0
and 0
as the second set of arguments. When the function is called with 5.0
and 2
as the arguments, it returns 2.5
, and when it is called with 5.0
and 0
as the arguments, it returns None
.
Program 63.py: Function with no arguments
1 2 3 4 5 6 7 8 | # Function with no arguments def greeting(): print("Hello there!") greeting() greeting() |
This is a program that defines a function called greeting
that takes in no arguments and prints the message “Hello there!”. The function has no return statement, so it returns None
.
The function is called twice, with no arguments. Each time it is called, it prints the message “Hello there!”.
The output of the program will be:
1 2 3 4 | Hello there! Hello there! |
Program 64.py: 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)) |
This is a program that defines a function called isPositive
that takes in a number x
and returns a Boolean value indicating whether x
is positive or negative.
The function first checks if x
is greater than or equal to 0. If it is, the function returns True
, and if it is not, the function returns False
.
The function is called once, with the user-entered value of x
as the argument. The result of the function is stored in the variable result
and is then printed to the screen. The function is also called a second time and the result is printed to the screen again.
For example, if the user enters -5.0
, the function will return False
, and the output of the program will be:
1 2 3 4 | False False |
If the user enters 5.0
, the function will return True
, and the output of the program will be:
1 2 3 4 | True True |
Program 65.py: 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)) |
This is a program that defines a function called doubleIt
that takes in a single argument x
and returns 2 * x
. The function is said to be polymorphic because the meaning of the operation 2 * x
depends on the type of the object being passed as the argument x
.
The program first calls the function with an integer value y
as the argument, and then calls the function with a string value z
as the argument.
When the function is called with the integer value 3
as the argument, the operation 2 * 3
is performed, and the function returns 6
. When the function is called with the string value "Hello "
as the argument, the operation 2 * "Hello "
is performed, and the function returns "Hello Hello "
.
The output of the program will be:
1 2 3 4 | 6 Hello Hello |
Program 66.py: 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. |
This is a program that defines a function called my_function
that takes in a single argument num
and has a local variable num
and a global variable number
. The function prints the value of both num
and number
.
The program first defines the global variable number
and assigns it the value 10
. It then prints the value of number
.
Next, the program calls the function my_function
with the value of number
as the argument. Inside the function, num
is a local variable with the value of the argument passed to the function, which is 10
. The function also has access to the global variable number
, which has the value 10
. The function prints the values of both num
and number
.
Finally, the program tries to print the value of the local variable num
defined inside the function. However, this variable is not available outside of the function, so an error will be raised stating that num
is not defined.
The output of the program will be:
1 2 3 4 5 | number in main program: 10 n in function: 10 number in function: 10 |
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 67.py: 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]) |
This is a program that creates a Python list called result
with 8 elements, all initialized to 0
, and then modifies some of the elements in the list.
The program first creates the list result
and prints it. The list result
has 8 elements, all initialized to 0
.
Next, the program modifies some of the elements in the list. The element at index 0
is set to 75
, the element at index 1
is set to 90
, and the element at index 4
is set to 72
.
Finally, the program prints the value of each element in the list using the list indexing notation result[i]
, where i
is the index of the element.
The output of the program will be:
1 2 3 4 5 6 7 8 9 10 11 12 | [0, 0, 0, 0, 0, 0, 0, 0] [75, 90, 0, 0, 72, 0, 0, 0] 75 90 0 0 72 0 0 0 |
Program 68.py: 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]) |
This is a program that creates an empty list called list1
and then prints it. An empty list is a list with no elements, so it has a length of 0
.
The program creates an empty list using the syntax list1 = []
. It then prints the list using the print()
function.
The program also includes a commented-out line that would generate an error if it were executed. This line tries to access the element at index 0
in the list list1
, but since the list is empty, it does not have any elements, and trying to access an element at an invalid index will raise an error.
The output of the program will be:
1 2 3 | [] |
Program 69.py: 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]) |
This is a program that creates an empty list called list1
, and then adds two elements to the list using the append()
method.
The program first creates an empty list using the syntax list1 = []
and then prints the list. The list is initially empty, so it has a length of 0
.
Next, the program adds an element to the list using the append()
method. The element is the integer 67
. The append()
method adds the element to the end of the list, so the list now has a length of 1
and the element at index 0
is 67
.
The program then adds another element to the list using the append()
method. This element is the string "hello"
. The append()
method again adds the element to the end of the list, so the list now has a length of 2
and the element at index 1
is "hello"
.
Finally, the program tries to access the element at index 2
in the list. However, the list only has 2 elements, so trying to access an element at index 2
will raise an out-of-range error.
The output of the program will be:
1 2 3 4 5 6 7 | [] 67 [67, 'hello'] 67 hello |
Program 70.py: 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]) |
This is a program that creates two lists, list1
and list2
, and then creates a third list called list3
that contains list1
and list2
as its elements.
The program first creates the list list1
and prints it. list1
has 3 elements: 1
, 2
, and 3
.
Next, the program creates the list list2
and prints it. list2
has 3 elements: 4
, 5
, and 6
.
The program then creates the list list3
and assigns it the value [list1, list2]
. This creates a list with list1
and list2
as its elements. list3
has a length of 2
and its elements are list1
and list2
.
Finally, the program prints the elements of list3
using the list indexing notation list3[i]
, where i
is the index of the element.
The output of the program will be:
1 2 3 4 5 6 7 | [1, 2, 3] [4, 5, 6] [[1, 2, 3], [4, 5, 6]] [1, 2, 3] [4, 5, 6] |
Program 71.py: 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]) |
This is a program that creates a list called list1
with 8 elements and then prints the first, second, last, and second-to-last elements of the list.
The program creates the list list1
and assigns it the value [1,2,3,6,7,8,9,10]
. It then prints the list.
Next, the program uses the list indexing notation list1[i]
to access and print the first, second, last, and second-to-last elements of the list. The indexing notation list1[i]
returns the element at the i
-th position in the list, where the first element has an index of 0
and the last element has an index of len(list1) - 1
.
To access the last element of the list, the program uses the index -1
, which refers to the last element of the list. To access the second-to-last element of the list, the program uses the index -2
, which refers to the element at the position len(list1) - 2
.
The output of the program will be:
1 2 3 4 5 6 7 | [1, 2, 3, 6, 7, 8, 9, 10] 1 2 10 9 |
Program 72.py: 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) |
1 2 3 4 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 3, 4, 5, 6, 7, 8, 9] |
Program 73.py: 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) |
This is a program that creates a list called list1
with 3 elements and then creates new lists by repeating list1
using the *
operator.
The program first creates the list list1
and assigns it the value [1,2,3]
. It then prints the list.
Next, the program creates a new list by repeating list1
3 times using the *
operator. This creates a new list with the elements of list1
repeated 3 times. The original list list1
is not modified. The program then prints the new list.
The program then prints the original list list1
again to show that it has not been modified.
Finally, the program assigns the value list1 * 2
to list1
. This creates a new list with the elements of list1
repeated 2 times and assigns the new list to list1
. The original list is replaced with the new list. The program then prints the new list.
The output of the program will be:
1 2 3 4 5 6 | [1, 2, 3] [1, 2, 3, 1, 2, 3, 1, 2, 3] [1, 2, 3] [1, 2, 3, 1, 2, 3] |
Program 74.py: 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]) |
This is a program that creates a list called list1
with 11 elements and then extracts a sublist from list1
using list indexing.
The program first creates the list list1
and assigns it the value [10,9,8,7,6,5,4,3,2,1,0]
. It then uses the list indexing notation list1[start:end]
to extract a sublist from list1
.
The indexing notation list1[start:end]
returns a sublist of list1
starting at the index start
and ending at the index end - 1
. If the start
index is not specified, it defaults to 0
, and if the end
index is not specified, it defaults to the length of the list.
In this program, the first sublist is extracted from the list using the indexing notation list1[0:1]
. This returns a sublist with a single element, the element at index 0
.
The second sublist is extracted from the list using the indexing notation list1[5:7]
. This returns a sublist with 2 elements, the elements at indices 5
and 6
.
The program then prints the two sublists.
The output of the program will be:
1 2 3 | [10] [5, 6] |
Program 75.py: 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)) |
This is a program that creates three lists and then prints the lengths of the lists using the len()
function.
The program first creates the list list1
and assigns it the value ["Tomy","May",'Lindia','Barbrossa',1,2,3]
. It then creates the list list2
and assigns it the value [1,2,3,4]
. Finally, it creates an empty list called list3
.
The program then prints the lengths of the three lists using the len()
function. The len()
function returns the number of elements in a list.
The output of the program will be:
1 2 3 | 7 4 0 |
Program 76.py: 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) |
This is a program that creates two lists, list1
and list2
, and then concatenates them using the +
operator.
The program first creates the list list1
and assigns it the value [1,2,3]
. It then prints the list.
Next, the program creates the list list2
and assigns it the value [4,5,6]
. It then prints the list.
The program then concatenates list1
and list2
using the +
operator and assigns the result to list1
. This creates a new list that contains the elements of list1
followed by the elements of list2
. The original list list1
is replaced with the new list. The program then prints the new list.
Finally, the program concatenates list1
with itself using the +
operator and assigns the result to list1
. This creates a new list that contains the elements of list1
repeated twice. The original list list1
is replaced with the new list. The program then prints the new list.
The output of the program will be:
1 2 3 4 5 6 | [1, 2, 3] [4, 5, 6] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] |
Program 77.py: 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=" ") |
This is a program that creates a list called list2
with 6 elements and then iterates over the elements of the list using a for
loop.
The program first creates the list list2
and assigns it the value [1,2,3,"Hello",4,5]
.
Next, the program uses a for
loop to iterate over the elements of the list. The loop variable i
takes on the value of each element of the list in turn, and the statements inside the loop are executed for each element.
The program prints the value of each element using the print()
function. The end
parameter of the print()
function is set to " "
, which means that the elements are printed on the same line separated by a space.
The output of the program will be:
1 2 3 | 1 2 3 Hello 4 5 |
Program 78.py: List membership
1 2 3 4 5 6 | # List membership list2 = [1,2,3,"Hello",4,5] print("Hello" in list2) |
This is a program that creates a list called list2
with 6 elements and then checks if an element is a member of the list using the in
operator.
The program first creates the list list2
and assigns it the value [1,2,3,"Hello",4,5]
.
Next, the program uses the in
operator to check if the element "Hello"
is a member of the list list2
. The in
operator returns True
if the element is a member of the list, and False
if it is not.
The program prints the result of the membership check using the print()
function.
The output of the program will be:
1 2 3 | True |
Program 79.py: 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) |
This is a program that creates a list called list2
with 3 elements and then demonstrates several methods of the list
class.
The program first creates the list list2
and assigns it the value ["B","C","A"]
. It then prints the list.
Next, the program uses the extend()
method to add two elements, "X"
and "Y"
, to the end of the list. The extend()
method adds the elements of the specified list to the end of the original list. The program then prints the modified list.
The program then uses the pop()
method to remove the last element of the list. The pop()
method removes the specified element from the list and returns the value of the removed element. If no element is specified, the pop()
method removes the last element of the list. The program then prints the modified list.
The program then uses the pop()
method again to remove the last element of the list. The program then prints the modified list.
The program then uses the reverse()
method to reverse the order of the elements in the list. The reverse()
method modifies the list in place, reversing the order of the elements. The program then prints the modified list.
The program then uses the append()
method to add an element, "S"
, to the end of the list. The append()
method adds the specified element to the end of the list. The program then prints the modified list.
The program then uses the sort()
method to sort the elements of the list into ascending order. The sort()
method modifies the list in place, sorting the elements into ascending order. The program then prints the modified list.
Finally, the program uses the reverse()
method again to reverse the order of the elements in the list. The program then prints the modified list.
The output of the program will be:
1 2 3 4 5 6 7 | ['B', 'C', 'A'] ['B', 'C', 'A', 'X', 'Y'] ['B', 'C', 'A', 'X'] ['B', 'C', 'A'] [' |
Program 80.py: 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") |
This is a program that creates a list called list1
with 9 elements and then performs a sequential search of the list to find a specified number.
The program first creates the list list1
and assigns it the value [21,25,24,22,65,1,44,51,78]
. It then prompts the user to enter a number to find using the input()
function.
Next, the program defines a variable found
and assigns it the value 0
. This variable will be used to keep track of whether the number was found in the list.
The program then uses a for
loop to iterate over the elements of the list. The loop variable i
takes on the value of each element of the list in turn.
Inside the loop, the program uses an if
statement to check if the number to find is equal to the current element of the list. If the number is found, the program prints the number and its index in the list using the index()
method and sets the value of found
to 1
.
After the loop, the program checks the value of found
. If found
is 0
, it means that the number was not found in the list, and the program prints a message indicating that the number was not found. If found
is 1
, it means that the number was found in the list, and the message is not printed.
If the user enters a number that is not in the list, the output of the program will be:
1 2 3 | Number not found |
If the user enters a number that is in the list, the output of the program will be:
1 2 3 | 25 |
Program 81.py: 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") |
This is a program that creates a list called mylist
with 9 elements and then performs a sequential search of the list to find a specified number.
The program first creates the list mylist
and assigns it the value [21,25,24,22,65,1,44,51,78]
. It then determines the length of the list using the len()
function and assigns it to the variable n
.
Next, the program uses a for
loop to iterate over the elements of the list. The loop variable i
takes on the values 0
, 1
, 2
, …, n-1
, and the statements inside the loop are executed for each value. The program prints the elements of the list separated by a space.
The program then prompts the user to enter a number to search for using the input()
function and assigns the entered value to the variable search
.
The program then defines a variable found
and assigns it the value False
. This variable will be used to keep track of whether the number was found in the list.
The program then uses another for
loop to iterate over the elements of the list. The loop variable i
takes on the values 0
, 1
, 2
, …, n-1
, and the statements inside the loop are executed for each value.
Inside the loop, the program uses an if
statement to check if the element at index i
is equal to the number to search for. If the element is equal to the number, the program sets the value of found
to True
and assigns the value of i
to the variable index
.
After the loop, the program checks the value of found
. If found
is True
, it means that the number was found in the list, and the program prints a message indicating the index at which the number was found. If found
is False
, it means that the number was not found in the list, and the program prints a message indicating that the number was not found.
If the user enters a number that is not in the list, the output of the program will be:
1 2 3 4 5 6 7 | 9 21 25 24 22 65 1 44 51 78 Please enter a number to search for: 20 20 20 not found |
If the user enters a number that is in the list, the output of the program will be:
1 2 3 4 5 6 7 | 9 21 25 24 22 65 1 44 51 78 Please enter a number to search for: 44 44 44 found at index 6 |
Program 82.py: 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") |
This is a program that creates a list called mylist
with 9 elements and then performs a binary search of the list to find a specified number.
The program first defines a function binarysearch()
that takes two arguments: mylist
and target
. The function uses a while
loop to perform the binary search.
The while
loop has a condition that states that the loop should continue as long as left
is less than right-1
. left
and right
are variables that are initialized to 0
and len(mylist)
, respectively, at the beginning of the function.
Inside the loop, the program computes the midpoint of the list using the int()
function to round down and assigns it to the variable mid
. It then retrieves the element at the midpoint and assigns it to the variable number_at_mid
.
The program then checks if target
is equal to number_at_mid
. If it is, the function returns True
. If target
is less than number_at_mid
, the program sets right
to mid
. If target
is greater than number_at_mid
, the program sets left
to mid
.
If left
becomes greater than or equal to right
, the function returns False
. If left
becomes equal to right-1
and the element at index left
is equal to target
, the function returns True
. Otherwise, the function returns False
.
The program then creates the list mylist
and assigns it the value [11,27,36,44,51,22,65,1,78]
. It then sorts the list using the sort()
method.
The program then enters a while
loop that continues as long as repeat
is "y"
or "Y"
. Inside the loop, the program prompts the user to enter a number to search for using the input()
function and assigns the entered value to the variable mytarget
.
The program then calls the binarysearch()
function with mylist
and mytarget
as arguments and assigns the returned value to a variable. If the returned value is True
, the program prints a message indicating that the number was found. If the returned value is False
, the program prints a message indicating that the number was not found.
Program 78.py: 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 |