Python l
![](https://assets.isu.pub/document-structure/230206125403-a3e7dcc570886d68ba9b21d0a2b44b07/v1/766da3d28d6e18c81b83eac0293163d7.jpeg)
The for versus while Loop
Nested Loop
The break and continue Statements
A computer is an electronic device which does not understand human languages. We need a language to instruct computers to carry out a task, just as we use English to communicate with one another.
Since computers are machines, they can only understand machine language. As machines are electrically powered devices, they listen to two signals: on and off, which are represented by 0s and 1s, respectively.
The language that is formed with 0s and 1s is called binary language, as it builds up on two digits. Binary Language is also called Machine Language.
It is difficult for us to remember each and every binary code for every single instruction. So we need a language which we can understand and use to instruct a computer.
A programming language is a language which has its own vocabulary and syntax just like we have in English, Hindi and other languages.
Programming is the process of writing a set of instructions that tells a computer how to perform a task.
Programming Languages are classified into two categories:
● Low-Level Languages
● High-Level Languages
Low-Level Language
Machine-friendly language is called Low-Level Language (LLL). Low-level languages include Machine and Assembly Languages. They communicate with the computer directly. As a result, no language translation is required.
High-Level Language
A language that is easily understandable by humans but not machines is known as HighLevel Language (HLL). However, they can be converted into machine language.
High-Level languages, like Python, C++, and Java, are simple to learn and enable programmers to create programs with easily comprehensible human syntax.
For programmers, this makes instructing computers easier. For a computer to perform a task, high-level programs must first be translated into a low-level language.
The high level language we are going to learn now is Python.
Python is a high-level, interpreted, interactive, object-oriented programming language. It is the easiest of the existing programming languages and super reliable.
Python is not named after a real Python, but rather after Guido’s favourite comedy show, Monty Python’s Flying Circus.
1. Easy to Read: Python code is easy to read, just like English.
2. Quick to Learn: Python has few keywords, a simple structure, and a clearly defined syntax. This makes learning Python easy and quick.
3. Easy to Maintain: Python’s source code is fairly easy to maintain.
4. Interactive Execution Mode: Python offers script and interactive modes for running programs. The code can be interactively tested and debugged in the interactive mode.
A three-step loop process defines how Python runs in the interactive window:
● The Python interpreter first reads the code entered at the prompt.
● Then it evaluates the code.
● Finally, it prints the outcome and awaits new input. The acronym REPL stands for read-evaluate-print loop.
5. Dynamic Typing: Python defines data type dynamically for the objects according to the value assigned. Also, it supports dynamic data type checking.
6. Portable: Python is a portable language because it can be used on a variety of hardware platforms.
7. Rich Standard Library: Python has a rich, portable and cross-platform standard library.
8. Large Database Support: Python provides interfaces to all major commercial databases.
9. GUI Application Creation: Python also supports the creation of GUI applications.
10. Scalable: Python provides better structure and support for larger programs than shell scripting. This makes it scalable.
The Python interpreter runs the code line by line and displays the results until an error occurs. It changes the HLL-written source code into bytecode, an intermediate language, which is then converted back into machine language and executed.
Every language has its own set of rules for writing. All programming languages also have rules for writing programs in them. These rules are called syntaxes.
Python also has some rules that we need to follow while writing a program.
One of Python’s rules is that it is a case-sensitive language, which means that name, Name, and nAme all refer to different things.
Syntax errors are mistakes in following the rules to write the code, such as wrong function name, missing quotes, brackets, etc.
Below are two examples of common syntax errors:
1. Missed double quotes
print(Hello World) SyntaxError: invalid syntax
2. Missed symbols, such as a colon, comma, or brackets
print(Hello World SyntaxError: invalid syntax
The print() statement displays a value or information in the output.
Syntax: print("value")
We can also print multiple elements in a single print statement by separating them with a comma. While printing them, in the output each element is separated by white spaces.
Syntax: print("box1","box2")
print("Hello","Kitty")
print("Welcome","to","Oak")Welcome
The sep is an optional parameter in the print function in Python.
The default separator in the print function is a white space. But with this parameter you can replace it with your choice of separator to separate words or elements passed in print function.
Syntax: print("box1", "box2", sep= "symbol")
print(1, "how", "are", "you doing", sep = "#")1#how#are#you doing
The end is also an optional parameter in the print function in Python. By default, the print function ends with a newline.
But with this parameter, we can add a symbol or value at the end of the statement.
Syntax: print("box" , end = "symbol")
print("How are you", end="?")
Solved Examples
Example 1.1
Write a program to print the following:
18/05/2020
theo@python.com
10*10*10=1000
Answer:
CODE
1. print('18', '05', '2020', sep='/')
2. print('theo','python',sep='@',end='.com')
3. print(10,10,10,sep='*',end=' = ') print(10*10*10)
How are you?
Write a program using the print command and creating entities (boxes) to print your scores in the test as given below:
English=90
Maths=98
Science=96
Computers=100
Total=384
Answer: CODE
1. print('English',90,sep="=")
2. print('Maths',98,sep="=")
3. print('Science',96,sep="=")
4. print('Computers',100,sep="=")
5. print('Total',90+98+96+100,sep="=")
A variable is a memory location on a computer which can hold any value and can also change over time as needed.
To understand it in an easy way, think of it like a box in which you can store a number and later you can replace that number with another number.
In simple words, variables are names given to the memory location where your value is stored.
The figure below illustrates three variables with their respective values. The three variables used in the figure are “name”, “winner” and “score”. The variable “name” holds the value “Bob”, the variable “winner” holds the value “True”, and the variable “score” holds the value “35”.
Therefore, whenever the variable “name” is used in the program, it refers directly to its value, “Bob”.
In Python, variable declaration and initialisation happens with a single step of assigning a value to a variable.
Syntax: variable_name = value
1. word = "hello"
2. number = 5
3. print(word,number)
We can also initialise multiple variables in one line.
Syntax: var1, var2 = value1, value2
1. word, number = "hello", 5
2. print(word,number)
5
NOTE: If we change the value of a variable and use it again, the old value is replaced with the new value.
There are certain rules we need to follow while naming a variable.
Some rules are:
1. Name of a variable should be meaningful.
2. Only the underscore ( _ ) symbol can be used while naming variables.
3. A variable name must start with a letter or the underscore character.
1. greeting_message = "hello"
2. _number_ = 5
3. print(greeting_message)
4. print(_number_)
1. greeting%message = "hello"
2. print(greeting%message)
SyntaxError: cannot assign to operator
4. As Python is a case-sensitive language, variable names are also case-sensitive.
Example: old, Old and OLD are three different variables.
1. old = 5
2. Old = 10
3. OLD = 15
4. print(old)
5. print(Old)
6. print(OLD)
5. A variable name can have numbers within but cannot begin with a number
1. number_1 = 100
2. _number2 = 200
3. print(number_1)
4. print(_number2)
1. 1number = 100
2. print(1number) SyntaxError: invalid syntax
As we have case styles for words in English, we have some case styles to name variables. Below are the case styles you can follow to name variables in Python:
A variable name can be written in camel case if it contains two or more distinct words. In camel case, we write the name of the variable as the first word in lowercase and all subsequent words with the first letter capitalised without a space in between.
Example: “Name of the company” can be written as “nameOfTheCompany”.
As this represents the camel’s hump we call it Camel-Case.
1. camelCaseExample = "Hello Camel"
2. print(camelCaseExample) Hello
Snake-case is the practice of writing in which each space is replaced by an underscore ( _ ) character and the first letter of each word written in lowercase.
Example: “Name of the company” in snake-case is written as “name_of_ the_company”.
1. snake_case_example = "Hello Python"
2. print(snake_case_example)
It is always a good practice to document your work. In programming, we also document our projects to keep them organised and easily understandable by other programmers.
We use comments to add documentation to a Python program. Python ignores these lines of comments in the programme during execution as they are not part of the code.
Comments help:
● structure the code and make it easier for humans to read.
● explain the thought process and intentions behind the code.
● find errors and debug the code.
● reuse the code in other applications as well.
After all, there is a popular saying, “Anyone can write code that a computer can understand. Good programmers write code that humans can understand.”
In Python, we have two types of comments:
● Single-line Comment
● Multi-line Comment
A single-line comment starts with a hash character ( # ) and is followed by related information.
A multi-line comment begins and ends with three single or double-quote characters (‘ ‘ ‘ or “ “ ‘) with related information enclosed.
1. '''
2. This is an example of
3. Multiline comments
4. '''
5. """
6. Printing hello world with sep command
7. Printing hello world with end command
8. """
9. print("hello", "world", sep = "-")
10. print("hello", "world", end = "!")
Example 2.1
The monster truck Black Thunder is participating in the final racing tournament of this year. Its current score is 729, and winning the race will double (x 2) its score. Write a program that displays the final score if Black Thunder wins. Answer:
1. score = 729
2. final_score = score * 2
3. print(final_score)
Example 2.2
Below are the Mastery Levels of Theo and his team in Python. Your task is to store their levels in different variables and display them in the same format shown below.
OUTPUT
Name Mastery Level
Theo 10
Zog 9999
Tyra 5480
Zo 5479
Answer:
1. theo = 10
2. zog = 9999
3. tyra = 5480
4. zo = 5479
5.
6. print('Name', 'Mastery Level')
7. print('Theo', theo)
8. print('Zog', zog)
9. print('Tyra', tyra)
10. print('Zo', zo)
Four streets form a rectangle. The streets are called - Jordan(10m), Newton(6m), Da Vinci(10m) and Edison(6m). A person has to walk on two of these streets and find the perimeter and area of the rectangle.
Write a program to calculate the perimeter and area of the rectangle.
Answer: CODE
1. jordan = 10
2. da_vinci = 10
3. newton = 6
4. edison = 6
5. perimeter = jordan + da_vinci + newton + edison
6. area = jordan * newton
7. print("Perimeter =", perimeter, "m")
8. print("Area =", area, "square meters")
Perimeter = 32 m
Area = 60 square meters
The ‘=’ operator is known as assignment operator, also read as ‘is set to’. It assigns the value on the right side of the “=” symbol to the variable on the left side.
There is a difference between the “=” we use in Maths and the one we use in Python. In mathematics, = means to equate the left side with the right side, it is the sign of equality.
In python, = symbol is used to set the value of the left side variable to the right side variable.
Syntax: variable = value
# the value is stored in the variable variable = variable + value
# value is added to existing variable value and stored in the variable
1. count = 5
2. count = count + 2
3. # new value of count is set to old value of count + 2
4.
5. print(count)
A line of the program that tells Python to assign a value to a variable is called an assignment statement. The variable on the left of “=” holds/stores the value on the right.
Syntax: variable_name=value
1. name="Theo"
2. roll_no=3006
3. print(name)
4. print(roll_no)
Solved Examples
Example 3.1
Theo 3006
Classify the following into either Fruit or Vegetable, and then print all the fruit variables in the first line and vegetable variables in the second line.
“Mango, Potato, Onion, Banana, Spinach, Strawberry, Capsicum”
Fruit - Mango Banana Strawberry
Vegetable - Potato Onion Spinach Capsicum
Answer:
1. fruit_1="Mango"
2. fruit_2="Banana"
3. fruit_3="Strawberry"
4. vegetable_1="Potato"
5. vegetable_2="Onion"
6. vegetable_3="Spinach"
7. vegetable_4="Capsicum"
8. print("Fruit-", fruit_1, fruit_2, fruit_3)
9. print("Vegetable-", vegetable_1, vegetable_2, vegetable_3, vegetable_4)
Example 3.2
We have a 3 digit number (573). Break the number into 3 variables: Unit Digit, Tens Digit, Hundreds Digit. Display the sum of the digits, as well as build and display the original number using these three parts.
Sum of digits = 15
Number = 573
Hint: Store each digit in a different variable and add them for sum. For finding the number- (unit*1) + (ten*10) + (hundred*100).
Answer:
1. unit = 3
2. ten = 7
3. hundred = 5
4. sum_of_digits = unit + ten + hundred
5. number = (unit*1) + (ten*10) + (hundred*100)
6. print("Sum of Digits =", sum_of_digits)
7. print("Number =", number)
We have two types of printers. Printer 1 can print at a speed of 600 pages per hour. Printer 2 can print at a speed of 400 pages per hour. If Printer 1 works for 7 hours and Printer 2 works for 10 hours, how many pages do we have at the end from each printer and both combined as well?
Printer 1 prints 4200 pages
Printer 2 prints 4000 pages
Both of them combined print 8200 pages
Answer: CODE
1. speed_1 = 600 #printing speed of 1st printer
2. speed_2 = 400 #printing speed of 2nd printer
3. hours_1 = 7 #hours 1st printer will print for
4. hours_2 = 10 #hours 2nd printer will print for
5. total_pages = (speed_1*hours_1) + (speed_2*hours_2)
6. print("Printer 1 prints", speed_1*hours_1 ,"pages")
7. print("Printer 2 prints", speed_2*hours_2 ,"pages")
8. print("Both of them combined print",total_pages,"pages")
Data types define what type of data a variable, a named memory location, can hold.
The default data types in Python are as follows: Data Type Description Example
Integer (int) Stores non-decimal numbers in a variable.
Float (float) Stores decimal point numbers in a variable.
String (str) Stores words and characters in a variable.
“Hello”, ”World”
Boolean (bool) Stores two values: True and False in a variable True and False
The type() function returns the data type of the value held by the variable.
Syntax: type(variable_name) CODE
1. integer_ = 5
2. string_ = "Hello, Welcome to Tekie"
3. print(type(integer_))
4. print(type(string_))
<class 'int'> <class 'str'>
Type casting refers to changing the data type of a variable into another.
The int() function is used to typecast the value of a variable into integer.
It converts the following data type into integer:
1. Float by removing the decimal point and everything after it.
2. String only if string represents a number.
3. Boolean by converting True to 1 and False to 0.
Syntax: int(variable_name)
1. str_to_int = int("8")
2. bool_to_int = int(True)
3. print(str_to_int, type(str_to_int))
4. print(bool_to_int, type(bool_to_int))
8 <class 'int'>
1 <class 'int'>
The float() function is used to typecast the value of a variable into float.
It converts the following data type into float:
1. Integer by adding a decimal followed by a zero.
2. String only if the string represents a float or an integer.
Syntax: float(variable_name)
1. a=float(10)
2. b=float("10.2")
3. print(a)
4. print(b)
1. c=float("Hello")
2. print(c) ValueError: could not convert string to float: 'Hello'
The str() function is used to typecast the value of a variable into string.
It converts all the data types including float, integer, boolean into a string.
Syntax: str(variable_name)
1. num_1 = str(5)
2. num_2 = str(7.2)
3. print(num_1 , type(num_1))
4. print(num_2, type(num_2))
5 <class 'str'>
7.2 <class 'str'>
The bool() function is used to typecast the value of a variable into boolean. It converts the following data type into boolean:
1. Integer and prints False if the value of the variable is 0, otherwise prints
2. String and prints False if the string is empty, otherwise prints True.
Syntax: bool(variable_name)
CODE OUTPUT
1. a=bool(0)
2. b=bool(1)
3. c=bool("")
4. d=bool("Python")
5. print(a,b,c,d)
Difference between String and Boolean
String
Strings are written by enclosing a set of characters within a pair of single or double quotes
Strings are a series of characters that form words and sentences.
Solved Examples
Example 4.1
False True False True
Boolean
A boolean variable can take only one of the two boolean values represented by the words True or False without quotes.
Booleans are either 0 or 1, they are used to categorise something in either True or False, which also implies a Yes or a No.
Make 2 variables, one to store the name and the other for the phone number. Now your teacher has asked you to submit the above details in one line in the following manner using type casting to convert the phone number into a string.
Name Phn_Number
John 65847961
Answer: CODE
1. name="John"
2. phn=65847961
3. print('Name','Phn_Number')
4. print(name , str(phn))
In a quiz competition, for each correct answer you get 2 points and for each incorrect answer 1 point is deducted. There are 12 questions in total. What are the maximum and minimum marks that you can score in the competition? Convert those marks into the string and the boolean values and print them as well.
Maximum marks= 24
Boolean value= True
Minimum marks= -12
Boolean value= True
Answer: CODE
1. no_of_questions=12
2. max_score=no_of_questions*2
3. min_score=no_of_questions*(-1)
4. print("Maximum marks=",str(max_score))
5. print("Boolean value=",bool(max_score))
6. print("Minimum marks=",str(min_score))
7. print("Boolean value=",bool(min_score))
The Python Math Library provides common maths functions that can be used for complex mathematical computations. Math library contains functions such as ceil, floor, factorial, etc.
We need to import the math library into our program before we can use the functions.
Here is how we import the library.
Syntax: import math
Here are a few useful mathematical functions used in daily computations.
The ceil comes from the word ceiling. As the name suggests ceil() function rounds UP the number to the nearest integer (i.e., the smallest integer greater than or equal to that number) and returns the value.
Syntax: ceil(value)
As the name suggests, the floor() function rounds a number DOWN to the nearest integer (i.e., the largest integer not greater than the number) and returns the value.
Syntax: floor(value)
1. import math
2. number = 1.666666666666667
3. ceil_ = math.ceil(number)
4. floor_ = math.floor(number)
5. print("Number rounded UP to ceil is:",ceil_)
6. print("Number rounded DOWN to floor is:",floor_)
Number rounded UP to ceil is: 2
Number rounded DOWN to floor is: 1
The round() function returns a float value by rounding off the number to the decimal place that we give as input. The function takes in two values the number we want to round off and the decimal places we want to round to (i.e., the number of digits after the decimal point).
The default number of decimals is 0, i.e., the function will return the nearest integer.
Syntax: round(float_value,digits_after_decimalpoint)
1. print(round(6.98867267267,2))
Python’s Random module is an in-built module of Python which is used to generate random numbers. Random module contain functions like random(), randint() etc
The random() function generates random floating numbers between 0 and 1.
Syntax: random.random()
The randint() function returns an integer number within the specified range. The specified range from which we want the integer is given as input in the function.
Syntax: random.randint(start,end)
Example 5.1
Prepare your report card:
Store your name and marks in 5 subjects in different variables, and calculate your percentage of marks.
Now, display the following data as well.
1. Percentage of marks scored in 5 subjects.
2. Round-UP the percentage using ceil function.
3. Round-Down the percentage using the floor function.
4. Round the percentage to 3 decimal places.
Name of the student: John
Percentage of the student: 79.4 %
Percentage after using ceil(): 80 %
Percentage after using floor(): 79 %
Percentage after using round(): 79.4 %
Answer:
1. import math
2. name="John" #you can write any name
3. marks1=94
4. marks2=84
5. marks3=92
6. marks4=58
7. marks5=69
8.
9. percentage=(marks1+marks2+marks3+marks4+ marks5)*100/500
10.
11. print("Name of the student:", name)
12. print("Percentage of the student:", percentage,"%")
13. print("Percentage after using ceil(): ",math. ceil(percentage),"%")
14. print("Percentage after using floor(): ",math. floor(percentage),"%")
15. print("Percentage after using round(): ",round(percentage,3),"%")
Arithmetic operators in Python are used along with the integer or float values to perform mathematical operations on them.
There are 7 arithmetic operators in Python:
BEMDAS Rule
Whenever there is a mathematical expression in Python, it solves it in the following sequence
1. Brackets (B)
2. Exponents (E)
3. Multiplication (M)
4. Division (D)
5. Addition (A)
6. Subtraction (S)
Python solves the mathematical expression in the order above from left to right of their occurrence.
But, whenever multiple exponent operators are used in an expression, python solves the exponent part from right to left
Example:
9 + 7 * (8 - 4) / 2 - 3**2
= 9 + 7 * 4 / 2 - 3**2
= 9 + 7 * 4 / 2 - 9
= 9 + 28 / 2 - 9
= 9 + 14 - 9
= 23 - 9
= 14
(First, the brackets are solved.)
(Then, Exponent is solved.)
(Then, multiplication is solved.)
(Then, division is solved.)
(Then, addition is solved.)
(Finally, subtraction is solved.)
Example 6.1
As a programmer, write a program to help Dave with the right answers to the questions given below using operators in Python.
a = 23 b = 13
a) Addition of a and b.
b) Multiplication of a and b.
c) Division of a and b.
d) Base a to the power b.
e) Modulus of a/b
Addition of a and b is: 36
Multiplication of a and b is: 299
a divided by b is: 1.7692307692307692
Base a to the power b is: 504036361936467383
Remainder, when a is divided by b, is: 10
Answer:
1. a,b=23,13
2. print("Addition of a and b is:",a+b)
3. print("Multiplication of a and b is:",a*b)
4. print("a divided by b is:",a/b)
5. print("Base a to the power b is:",a**b)
6. print("Remainder, when a is divided by b, is:",a%b)
Practice Question:
1. Create a program that uses ceil function to round up the percentage of a student.
2. Create a program to calculate basic mathematical operations (addition, subtraction, division and multiplication) on any two numbers.
3. Create a program to generate and display random numbers between 1-6.
4. Create a program that displays the difference between floor and round functions.
A string is a data type that represents a sequence of characters. In Python, strings are put inside double quotes (“ ”) or single quotes (‘ ’). These values can be words, symbols, characters, numbers, or a combination of all these. A string can be categorised into two as follows:
● A single-line string
● A multi-line string
A single-line string can be enclosed in either single quotes or double quotes. CODE
1. name_1="Theo"
2. name_2='Theo'
3. print(name_1)
4. print(name_2)
A multi-line string can be enclosed in either three single quotes (‘) or three double-quotes (“).
CODE OUTPUT
1. proverb_1= '''A journey of thousand
2. miles begins with a
3. single step. '''
4.
5. proverb_2= """
A journey of thousand miles begins with a single step.
6. Actions speak
7. louder
8. than words.
9. """
10. print(proverb_1)
11. print(proverb_2)
Actions speak louder than words.
When we have multiple apostrophes in a sentence, python throws an error as it is illegal.
We can avoid this with the help of an escape character. An escape character is a backslash ( \ ) followed by the character that is to be inserted.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes: CODE OUTPUT
print("Best programming language is "Python".")
SyntaxError: invalid syntax
Thus if there are multiple apostrophes and we want them to be part of the same string we use backslashes before them so that the character is included in the string. CODE OUTPUT
print("Best programming language is \"Python\".")
Best programming language is "Python".
In some cases we might need to break the string into multiple lines.
In order to add a new line, we put \n before the character where we want the string to break, the characters after the \n are printed on the next line onwards.
print("Hello\nWorld")
Example 1.1
Theo went to Uncle Sam’s Pizzeria. He ordered a medium Pizza, a large Fries, and a Vanilla milkshake. The price of the Pizza was Rs. 300, the price of the Fries was Rs. 140 and the price of the Milkshake was Rs. 180. Your task is to print the bill for Theo.
1. Print the name of the restaurant - Uncle Sam’s Pizzeria (Use escape character)
2. Print the name of each dish Theo ordered on a new line. (Use multiline string)
3. Print the total amount of the bill as below.
Uncle Sam's Pizza
Ordered Items:
Medium Pizza
Large fries
Vanilla milkshake
Total Bill: 620
Answer: CODE
price_1 = 300
price_2 = 140
price_3 = 180
print("Uncle Sam\'s Pizza\n")
print("Ordered Items:")
print("""Medium Pizza
Large fries
Vanilla milkshake """)
print("Total Bill:")
print(price_1+price_2+price_3)
Concatenation is the technique of combining two or more strings together. There are different ways to concatenate strings.
The addition operator (+) has a different meaning in the case of strings. The + operator is used to join two or more strings into one single string.
a= "Hello"
b = "World"
c = a + b print(c)
HelloWorld
The join() string function returns a string by joining all the elements of a string.
Syntax: str.join([var1, var2]) CODE
var1 = "Hello"
var2 = "World" print("".join([var1, var2]))
HelloWorld
The (*) operator duplicates the string and combines them.
If * is used with an integer, it performs multiplication, but if it is used with strings, it performs repetition.
Syntax: repeated_string = string1*no_of_times
Multiplying a string with an integer, repeats the string that many times.
str = "Python" print(str*3)
PythonPythonPython
Multiplying a string with a float gives an error. We can only repeat strings with integers.
str = "Python" print(str*3.5)
Example 2.1
TypeError: can't multiply sequence by non-int of type 'float'
You’re a programmer working for Copland’s Corporate Company. At this company, each employee’s username is generated by joining the first name and the last name. You have the first_name = “John” and the last_name = “Simons” of the employee. Now do the following tasks.
1. Create the username by concatenating the first_name and last_name.
2. Create a temporary password by repeating the username twice.
3. Print a welcome message “Hello, JohnSimons” using the join() function.
Username is: JohnSimons
Temporary password is: JohnSimonsJohnSimons
Hello JohnSimons
Answer: CODE
first_name = "John"
last_name = "Simons"
username = first_name+last_name
print("Username is:",username)
temp_password = username*2
print("Temporary password is:",temp_password)
welcome_message = "".join(["Hello",username])
print(welcome_message)
The input() function in Python is used to take and store input from the user.
We can take any kind of information from the users as input. Whatever is entered as input, the input() function converts it to a string.
Syntax: input("message to be shown in input prompt")
x = input("Enter your name:") print("Hello, " + x) Enter your name:Zog Hello, Zog
The islower() function returns True if all the characters in a string are in lower case, otherwise it returns False.
Syntax: string.islower()
greetings_1 = "welcome to oak"
check_1 = greetings_1.islower()
print(check_1)
greetings_2 = "WELCOME to oak"
check_2 = greetings_2.islower()
print(check_2)
True False
If a string contains symbols and numbers only the function returns False. If symbols and numbers are present along with lower case characters it returns True.
(i.e., Symbols and numbers are ignored by the function)
sentence_1 = "#%@&^"
check_1 = sentence_1.islower()
print(check_1)
sentence_2 = "hello@uolo.in"
check_2 = sentence_2.islower()
print(check_2)
The isupper() function returns True if all the characters are in upper case, otherwise it returns False.
Symbols and numbers are ignored by this function as well.
Syntax: string.isupper()
proverb_1 = "PRACTICE MAKES PERFECT"
check_1 = proverb_1.isupper()
print(check_1)
proverb_2 = "PRACTICE makes perfect"
check_2 = proverb_2.isupper() print(check_2)
The lower() function is used to convert all the characters of a string to lowercase.
Syntax: string.lower() CODE
statement = "Python Is Easy" x = statement.lower()
print(x)
python is easy
The upper() function is used to convert all the characters of a string to uppercase.
sentence = "Practice is the key" x = sentence.upper()
print(x)
Example 3.1
Jeniffer wants to make a virtual marks card that takes input of name , school , standard , section , total score. Then display the name , school , grade (display standard with section), total score.
The name has to be in small letters, school and section in capital letter despite the case in which the user provides the input. Help her to create the virtual marks card using Python.
Enter your name: John
Enter school name: Oak's School
Enter the grade you're studying: 7
Enter your section: B
Enter total score: 320
Name: john
School: OAK'S SCHOOL
Grade: 7 B
Total Score: 320
Answer:
name = input("Enter your name: ")
school = input("Enter school name: ")
std = int(input("Enter the grade you're studying: "))
sec= input("Enter your section: ")
score = int(input("Enter total score: "))
print("Name: " ,name.lower())
print("School: ",school.upper())
print("Grade: ", std, sec.upper())
print("Total Score: " , score)
Create a program that takes input of the game’s name. Display a boolean value to see whether the entered name is lowercase or not. Also, it would look messy to store the game names if everyone used a different case so, convert the input to uppercase.
Enter a game you like to play: Football
Entered Game name is: FOOTBALL
The input is in lowercase: False
Answer:
game = input("Enter game you like to play: ")
upper_case = game.upper()
print("Entered Game name is: ",upper_case)
print("The input is in lowercase: ",game.islower())
%s reserves a place for the variables that hold the value to be inserted in the string.
Syntax: print("String %s " %variable_name)
fruit = "apples"
print("Get me %s." %fruit)
Get me apples.
Multiple strings can also be embedded within a single string using multiple %s operators. If there are multiple %s , the strings are replaced based on their order in the brackets.
num = 5
fruit = 'apples'
print('I ate %s %s.' %(num,fruit))
I ate 5 apples.
f-strings are another way to use and embed variables and expressions inside a string.
We start a string with the letter f followed by quotes, and the variables or expressions we want to embed within the quotes are enclosed within curly brackets {}.
Syntax: print(f"string {variable_name}.") CODE
name = "Zog"
age = 40
print(f"Hello, {name}. You are {age}.")
Hello, Zog. You are 40.
To embed values using the format() function, we use curly brackets in the string where we want to replace values stored in variables. Then the variables are specified in the .format() function in the sequence we want them to be inserted in the string.
Syntax: "{} {}".format(value1, value2...) CODE
var1 = "Hello"
var2 = "World"
print("{} {}".format(var1, var2))
Solved Examples
Example 4.1
You are assigned a task to make a program to spread some joy amongst people who use your program.
Write a program to do the following:
(a) Get the name as input from the person and store it in a variable name.
(b) Using the %s and f-string embedding, produce the following output
Enter your name: Zo Hi Zo. You look wonderful today. Have a nice day, Zo!
Answer: CODE
name=input("Enter your name: ") print("Hi %s. You look wonderful today." %name) print(f"Have a nice day {name}!")
Example 4.2
Your school results are out. Take 5 subject marks as input (scored out of 50), and display the total percentage scored in the following manner. Use format() function to display the results.
Enter marks for subject 1 out of 50: 34
Enter marks for subject 2 out of 50: 36
Enter marks for subject 3 out of 50: 43
Enter marks for subject 4 out of 50: 45
Enter marks for subject 5 out of 50: 37
You scored 195 out of 250 in the exams.
Congratulations, you scored 78.0% in your exams.
Answer: CODE
sub1=int(input("Enter marks for subject 1 out of 50: "))
sub2=int(input("Enter marks for subject 2 out of 50: "))
sub3=int(input("Enter marks for subject 3 out of 50: "))
sub4=int(input("Enter marks for subject 4 out of 50: "))
sub5=int(input("Enter marks for subject 5 out of 50: "))
total_marks=sub1+sub2+sub3+sub4+sub5 percentage=(total_marks/250)*100
print("You scored {} out of {} in the exams.".format(total_ marks,250))
print("Congratulations you score {}% in your exams.".format(percentage))
Every character in a string is given a number that is called an index. We can access each character of a string with help of these indices. The first character has index 0, the second character has index 1, and so on.
Syntax: string_name[index number]
greeting = "Bonjour"
# B=0, o=1, n=2, j=3, o=4, u=5, r=6
print(greeting[6])
The index() function is used to get the index number of a particular character in a string.
If the character occurs more than once in the string, the index of the first occurrence of that character is returned.
Syntax: string.index(value, start, end)
#value - The character to search for #start (Optional): Index number to start the search from. Default is 0.
#end (Optional): Index number to end the search at. Default is to the end of the string.
prince_name = "Prince Poppy" print(prince_name.index('i')) print(prince_name.index('p'))
Python numbers the characters of a string in two ways, forward and backward. While numbering backward, Python gives the characters a negative index starting from -1 for the last character in the string.
funny_prince = 'Prince Poppy' print(funny_prince[-1]) print(funny_prince[-4])
Python does not allow you to change any character in a string with help index. So we cannot change the value or a character within a string unless we reassign the entire string to the variable again. CODE
greeting = "Hey, man!" greeting[0] = "C" print(greeting)
TypeError: 'str' object does not support item assignment
In addition to indexing the strings, Python allows us to extract a part of a string. This extraction of strings is known as slicing and the extracted part of the string is known as a substring.
We slice a string by providing the starting index and 1 more than the ending index in square brackets [] after the variable.
Syntax: string_name[starting index:ending index] CODE
s = "ABCDEFGHI" print(s[2:7]) CDEFG
Python can also skip letters in between while slicing. We use two colons for that.
Syntax: String_name[start:end:step]
#If step is 3, python will print every third character
word = "ABCDEFGHI"
print(word[2:7:2])
#python prints every second character
By not specifying the ending index, Python automatically takes the last letter of the string as the endpoint.
Syntax: string_name[starting index:]
word = 'helipad'
print(word[2:]) lipad
By not specifying a starting index, Python takes the start index of the first letter in the string.
Syntax: string_name[:ending index]
Strings
word = 'helipad'
print(word[:6]) helipa
Python counts and returns the number of characters in a string using len() function.
Syntax: len(string_variable)
Example 5.1
Store your first name as a string in the variable my_first_name and your last name as a string in the variable my_last_name.
1. Print the length of the string.
2. Select the first letter of the variables my_first_name and my_last_name and store them in variables first_initial and last_initial respectively.
3. Now, print your name and your first and last initials on 2 separate lines.
Entered name is: Theo
Length of the name string is: 4
The first initial is: T
The last initial is: o
Answer:
my_name="Theo"
print("Entered name is: ",my_name)
print("Length of the name string is: ",len(my_name))
first_initial=my_name[0]
print("The first initial is: ",first_initial)
last_initial=my_name[-1]
print("The last initial is: ",last_initial)
The reversal of strings means the output shown would be a string from last to first. For example, take a string “Andy” and the reversal of it would be “ydnA”.
1. Reverse the following string: ”Hello world”
2. Now using string slicing, reverse each word separately and join them back together.
(i.e., Change ”Hello world” to “olleH dlrow”)
Hello world
Reverse of the entire string is: dlrow olleH
Word 1: Hello
Word 2: world
Reverse of both words individually: olleH dlrow
Answer: CODE
string_1="Hello world"
print(string_1)
string_1_rev = string_1[::-1]
print("Reverse of the entire string is:",string_1_rev)
word_1 = string_1[:5]
print("Word 1:",word_1)
word_2 = string_1[6:]
print("Word 2:",word_2)
string_2_rev = word_1[::-1]+" "+word_2[::-1]
print("Reverse of both words individually:",string_2_rev)
The find() function returns the index of the first occurrence of the searched character or substring in a string.
The find() function returns -1 if the searched character or substring is not found within the string.
Syntax: string.find(<letter / substring to be searched>)
line = 'Kate on her skateboard!' print(line.find('Kate'))
line = 'Kate on her skateboard!' print(line.find('Katie'))
#As 'Katie' is not present in the string, the output will be -1
line = 'Kate on her skateboard!' print(line.find('ate'))
#there are 2 ""ate"" substrings in the variable line, #but python shows the starting index of the first occurrence.
The replace() function replaces a specified character or substring with another in a string. The part of the string you wish to replace and the new string to replace it with are specified inside the replace() function along with the number of times you want to replace.
Syntax
string.replace('oldWord','newWord',count)
oldWord: word you want to replace
newWord: is word you want to replace with count: is the number of times you want to replace oldWord with newWord
line = "O'really? bababa!"
print(line.replace('ba', 'ha', 2))
O'really? Hahaba!
If a count is not specified python replaces all the occurrences. CODE
line = "O'really? bababa!"
print(line.replace('ba', 'ha'))
Example 6.1
O'really? hahaha!
You have been given a text str1= “Hello , Good Morning!”.
Take your name as an input and insert it between the string (using replace function) as shown below.
Hint: Replace the first space (“ “) with your name and spaces before it
Enter your name: Theo Hello Theo, Good Morning!
Answer: CODE
str1= "Hello , Good Morning!"
name = input("Enter your name: ")
str2 = str1.replace(' '," "+name,1) print(str2)
Example 6.2
We have a string str1=”Hello World”. You have to perform the following tasks in the specified sequence:
1. Replace all occurrences of the letter “l” with the letter “x”.
2. Find and print the index of the first and the last occurrence of the letter “x”.
3. Find and print the number of letters between the first and the last “x”.
The string after replacing l with x is: Hexxo Worxd
Index of first x is : 2
Index of last x is: 9
Number of letters in between the first and the last x is: 6
Answer: CODE
str1="Hello World" str1=str1.replace("l","x")
print('The string after replacing l with x is:',str1) firstx=str1.find("x")
str1_reverse=str1[::-1]
xtemp=str1_reverse.find("x")
lastx=len(str1_reverse)-1-xtemp print('Index of first x is :',firstx) print('Index of last x is:',lastx)
no_of_letters=lastx-firstx-1 print('Number of letters in between the first and the last x is:',no_ of_letters)
Example 6.3
Take input of a sequence of your favourite food items in a single string.
For example food_items = “Apple Coke Pizza Burger”
You have to display this in a vertical manner using the replace function and the newline character.
The list with each item on new line is as follows: Apple Coke Pizza Burger
Answer:
food="Apple Coke Pizza Burger" food=food.replace(" ","\n")
print("The list with each item on new line is as follows:") print(food)
Practice Problem:
1. Write a program to display all words with even length in a given string.
2. Write a program to replace all the ‘n’ with letter ‘m’ in “NATHENATICAL”.
3. Write a python program to split and join the string using “ -” . (I love python → I-love-python)
4. Write a python program to accept a string and replace all the spaces with “#” symbol.
Decision-making, as the name suggests, is making decisions based on certain conditions. To write these conditions we need to use comparison and logical operators.
Comparison operators compare the value on the left-hand side with the value on the right-hand side and returns either True or False as a result of the comparison.
These operators are also known as relational operators. Below are the six comparison operators in Python.
== Equal to Returns True if both operands are equal x==y
!= Not Equal to Returns True if operands are not equal x!=y
> Greater than Returns True if left operand is greater than the right x>y
< Less than Returns True if left operand is less than the right x<y
>= Greater than or equal to Returns True if left operand is greater than or equal to the right x>=y
<= Less than or equal to Returns True if left operand is less than or equal to the right x<=y
# Using the equality operator print(2==2.0)
print(3==5)
# Using the inequality operator print(3!=5)
print(2!=2)
# Using the greater than operator print(1>3)
print(10>8)
# Using the less than operator print(10<12)
print(10<9)
# Using the greater than or equal to operator print(16>=16)
print(14>=15)
# Using the less than or equal to operator print(16<=18)
print(15<=10)
Example 1.1
Johnny has to check whether the number of balls in box A is equal to, less than or greater than the number of balls in box B. Box A contains 453 balls and box B contains 454 balls respectively. Using conditional statements print whether the situations are True or False.
OUTPUT
Are balls in box A equal to box B?- False
Are balls in box A less than box B?- True
Are balls in box A greater than box B?- False
Answer: CODE
box_A=453
box_B=454
cond1=box_A==box_B
print("Are balls in box A equal to box B?-", cond1)
cond2=box_A<box_B
print("Are balls in box A less than box B?-", cond2)
cond3=box_A>box_B
print("Are balls in box A greater than box B?-", cond3)
Joe’s mother gives him Rs. 350 and asks him to get some groceries from a nearby shop. He plans to buy tomatoes for Rs. 50, onions for Rs. 60, and a jar of Peanut Butter for Rs. 100.
(a) With the help of a conditional statement print True or False to help him know if the money his mother gives him will be enough to buy the planned items or not.
(b) Joe plans to buy 2 more jars of Peanut butter with the remaining money. Help him decide if he has enough money to do so.
The total money with Joe is: 350
The total bill will be: 210
Is the money adequate to buy groceries?- True
The remaining amount left with Joe is: 140
Can Joe buy 2 more jars of Peanut butter?- False
Answer:
price_tomato=50
price_onion=60
price_butter=100
total_money=350
print("The total money with Joe is: ",total_money)
total_bill=price_tomato+price_onion+price_butter print("The total bill will be: ",total_bill)
cond=total_money>total_bill
print("Is the money adequate to buy groceries?-",cond)
remaining_money = total_money - total_bill
print("The remaining amount left with Joe is: ",remaining_money) cond2=remaining_money>(price_butter*2)
print("Can Joe buy 2 more jars of Peanut butter?-",cond2)
Logical operators are used to compare two or more conditions. These conditions can be formed using the comparison operators. We get a boolean value (True or False) as output after comparing these conditions.
The logical operators include “and” and “or”.
The and operator compares two conditional statements and returns True only if BOTH are true, else returns False in all other cases.
Syntax: Statement1 and Statement2
Following is the truth table for the AND operator:
Condition_1 Condition_2 Condition_1 and Condition_2
print(3<7 and 8==8) print(6>2 and 9==8)
The or operator compares two conditional statements and returns True if any one of the statements is true. It returns False if both conditional statements are false.
Syntax: Statement1 or Statement2
Condition_1 Condition_2
Condition_1 or Condition_2 TRUE TRUE TRUE TRUE FALSE
print(4+5>8 or 9!=7)
print(6>7 or 8==9.0)
We can form complex conditional statements in Python using multiple AND/ OR operators. In such cases where we have multiple AND/OR conditional statements, AND has precedence over OR. (i.e., the conditions with AND are solved first and then the conditions with OR are solved)
Syntax: Statement1 or Statement2 and Statement3
#First we solve the AND operator, and then the OR
print(2>3 or 3==3 and 1>0)
2 > 3 or 3 == 3 and 1 > 0
False or True and True
#Solve and first False or True #Solve or True
Example 2.1
David needs to select students for his upcoming project based on two criteria. The students should have 60% in their academics, and they should have a score of 7 in their analytical tests.
Now, Ray has a score of 65% in his academics and 8.5 in analytical tests. Similarly, Joe has a score of 55% in his academics and 8 in analytical tests.
So display True or False based on the condition each for Ray and Joe whether they pass David’s criteria or not.
Ray's scores:
Academics: 65%
Analytical test: 8.5
Does Ray meet David's criteria?- True
Joe's scores:
Academics: 55%
Analytical test: 8
Does Ray meet David's criteria?- False
Answer:
ray_academics=65
ray_analytical=8.5
print(f"Ray's scores:\nAcademics: {ray_academics}%\nAnalytical test: {ray_analytical}")
ray_condition = ray_academics>=60 and ray_analytical>=7
print("Does Ray meet David's criteria?-",ray_condition)
joe_academics=55
joe_analytical=8
print(f"Joe's scores:\nAcademics: {joe_academics}%\nAnalytical test: {joe_analytical}")
joe_condition = joe_academics>=60 and joe_analytical>=7
print("Does Ray meet David's criteria?-",joe_condition)
Example 2.2
Ben is the captain of the school’s football team. He needs defensive players who are tall and strong and offensive wingers who are short and agile.
For defense, he needs players taller than 6 feet and with a weight of more than 68 kg.
For offense, he needs players shorter than 5.5 feet and with a weight of less than 57 kg.
Take your height and weight as float inputs, and with the help of Comparison and Logical operators, print True or False for the combined condition.
Enter your height in feet: 5
Enter your weight in Kg: 55
Do you meet any of Ben's criteria for the football team?- True
height=float(input("Enter your height in feet: ")) weight=float(input("Enter your weight in Kg: "))
condition = (height>6 and weight>68) or (height<5.5 and weight<57)
print("Do you qualify any of Ben's criteria for the football team?",condition)
Indentation is a fixed amount of spaces added at the beginning of the code grouping a set of statements into a particular block of code. So Python runs a particular block of code at a time.
Below you can see how the spaces or Indentation divides the code into various blocks of code.
Flowchart is a diagram and a graphical representation of an algorithm or program.
It is a blueprint of the program and it shows steps in sequential order.
Certain shapes are used to draw flowcharts, and these shapes have the meaning as follows:
A conditional statement is a statement that tests a criterion and performs the defined action if it becomes true.
The if-else statement in Python is the most simple decision-making statement. It is used to decide if a certain condition or set of conditions is True or not.
If the condition after the “if” keyword is True, the code block after the if condition is executed, and if the condition is False, the code block after the “else” keyword is executed.
It is not necessary to have another condition.
Syntax:
if condition_1:
#Statements to execute if condition_1 becomes True
else:
#Statements to execute if condition_1 becomes False
age = 21
if age >= 18:
print("Eligible to vote.")
else:
print("Too young to vote!")
Eligible to vote.
Nesting is the process of adding an if-else statement within another if-else. This will help us evaluate the second condition only when the first condition is True.
The first if statement is commonly called “outer if” and the block within it is called “nested / inner if”.
Syntax: if condition_1: if condition_2:
Statement_A
else:
Statement_B
else: if condition_3:
Statement_C
else:
Statement_D
age=10
height=160
if age >= 10: if height > 150:
print('You get a roller coaster!')
else:
print('You get water rides!')
You get a roller coaster!
else:
print('Sorry, no rides for you!')
In situations where we have multiple conditions to evaluate the elif statement is used. This in simple terms means “else if”. The elif statement lets you add more than one conditional statement after the if statement or between the if and else statements in the program.
In multiple elif conditions, Python checks for the next one if the previous ones are False.
Syntax:
if condition_1:
Statement_1
elif condition_2:
Statement_2
elif condition_3:
Statement_3 .. .. ..
else:
age=10
height=160
if age >= 10 and height > 150: print('You get a roller coaster!')
elif age >= 10 and height <= 150: print('You get water rides!')
else: print('Sorry, no rides for you!')
You get a roller coaster!
Example 3.1
Take a number as an input from the user and write a program to check whether the given number is a positive number or a negative number. Also, take another number as a reference in the variable ref_number and display if the input number is on the left or right-hand side of the reference number when put on the number line.
Enter a number: -5.2
The input number -5.2 is negative
Enter a reference number: -9 -5.2 is on the right-hand side of the number -9.0
Answer: CODE
num=float(input("Enter a number: ")) if num>0:
print(f"The input number {num} is positive")
else:
print(f"The input number {num} is negative")
ref_number = float(input("Enter a reference number: ")) if num>ref_number:
print(f"{num} is on the right-hand side of the number {ref_ number}")
else:
print(f"{num} is on the left-hand side of the number {ref_ number}")
Example 3.2
Write a program to get today’s day as the input and check if it is a “weekend” or a “weekday”.
If it is a day from the weekend, check if the next day is a weekend or a weekday.
Enter today's Day: Monday Monday is a weekday.
Enter today's Day: Saturday Saturday is a weekend.
Next day is Sunday, it is the weekend.
Answer:
current_day = input("Enter today's Day: ")
if current_day.lower()=="Monday" or current_day.lower()=="Tuesday" or current_day.lower()=="wednesday" or current_day.
lower()=="Thursday" or current_day.lower()=="Friday":
print(f"{current_day} is a weekday.") elif current_day.lower()=="Saturday":
print(f"{current_day} is a weekend.")
print("Next day is Sunday, it is the weekend.") elif current_day.lower() == "sunday":
print(f"{current_day} is a weekend.")
print("Next day is Monday, it is a weekday.")
Write a program to take a year as input from the user and calculate whether the year is a leap year or not.
Hint: Leap year is the year which is divisible by 4 and not by 100 or which is directly divisible by 400.
Enter a year: 2004
The year 2004 is a leap year
Enter a year: 1999
The year 1999 is not a leap year
Answer:
year=int(input("Enter a year: ")) if(year%4==0 and year%100!=0):
print(f"The year {year} is a leap year") elif(year%400==0):
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
1. Write a program to check if a student has passed the exam or not by accepting their marks as input.
2. Write a program to check if a number is greater than 100 or not.
3. Write a program to print the largest number among three inputs.
4. Write a program to input three numbers from the user and check if three numbers are unique or not.
While programming, we will often come across situations where we need to use a piece of code over and over again. However, writing the same line of code multiple times does not make sense. This is where loops come in handy. Loops help us repeat a set of instructions again and again until a particular condition remains True. As soon as the condition becomes False, the loop stops.
Python provides mainly two types of loops, the While loop and the For loop. But the steps remain loosely the same as below.
A looping process has mainly 4 steps:
1. Creating a condition variable and storing an initial value in it.
2. Providing a test condition that runs the loop (This should be carefully stated in order to run the loop for a desired number of times).
3. A set of instructions inside the loop.
4. Updating the value of the condition variable.
Syntax:
condition_variable = 0
repeat till condition is True:
condition_variable = condition_variable + 1
In some cases, the body of the loop gets executed over and over as the test condition never becomes false, and the execution never stops. Such a loop is called an Infinite loop.
The simplest looping statement is the while statement. It allows a programmer to repeat a set of instructions when the condition is evaluated as True, hence it is also known as a conditional loop.
It verifies the condition before executing the loop. The code inside the while loop is repeated as long as the given condition remains True.
A while loop can be written using:
1. The while keyword.
2. A condition which is either True or False.
3. A block of code, which is nothing but the set of instructions that is supposed to be repeated.
Syntax: while condition:
Statement 1
Statement 2 ... ...
(Incrementing the value if required)
Proper indentation needs to be provided for the block of code present inside the while loop. It is also called the body of the loop.
Here, i is the condition variable, which starts with 1, and when Python checks the condition (i < 6), it comes out to be True. So, the loop starts. In line 3, the value of i is displayed. Then in line 4, i is increased by 1 (i = i + 1 = 1 + 1 = 2). After that, Python checks the condition again. As 2 < 6 is True, the loop runs again. This continues till the value of i is less than 6. When i becomes 6, the condition becomes False, and the loop stops.
The for loop is another looping statement. It is also known as a counting loop because we can use it to count up to a number or go through a sequence of values.
We use a variable to create the for loop called the loop variable.
The two ways to create a for loop:
1. With the range() function.
2. Without using the range() function.
Using range() function, we can specify a starting number and an ending number. So, the for loop will start from the starting number and continue up to (ending number - 1), increasing the number by 1 after each loop.
Syntax:
for loop_variable in range(start, end, steps):
<statements>
#the loop runs from start to end-1
start Optional. An integer number specifying at which position to start. If the start number is not specified, Python takes 0 by default.
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying by what value to increase the value of loop variable. By default Python increases the value by 1.
Here, the starting number is 0 and the ending number is 5. So, the for loop starts counting from 0 and continues tile (ending number - 1) which is 4. And after each loop, the value of 1 increases by 1.
Without using the range function, a for loop can iterate over letters in a string, values in a list, tuple, or a dictionary as well.
Syntax: for loop_variable in string_variable: <statements>
word = 'bumfuzzle'
for letter in word: #In loop 1, letter = 'b' print(letter)
Here the loop starts with the first letter, i.e., letter = ‘b’. And in each loop, the value of the variable changes to the next letter in the string. So in the second loop, letter = ‘u’, in the third loop, letter = ‘m’, and so on. It continues up to the last letter in the string.
In for loop, we initialise, test and update the loop variable during writing a loop in one single line, whereas the while loop requires more lines.
For loop is also called a counting loop since it counts up to a number. for i in range(start, stop, increment):
//step1 //step2
In a while loop, the condition is tested first and the loop gets executed when the condition is met. In case, if we forget to update the loop variable, there are chances we may end up in an infinite loop which doesn’t happen in the case of for loop.
While loop is also called a conditional loop because it has a condition.
i=1
while(i<=10):
//step1 //step2
A nested loop is a loop inside another loop. The first loop we start off with is called the outer loop. All the loops that are written inside the outer loop are called inner loops. The outer loop can contain more than one inner loop. The inner or outer loop can be any type, such as a while loop or a for loop.
The entire “inner loop” gets executed every time the “outer loop” runs.
If the outer loop runs 5 times, and the inner loop runs 10 times. Then for the 1st iteration of the outer loop, the inner loop will run 10 times, for the 2nd iteration of the outer loop, the inner loop will run 10 times, and so on.
So in total, the inner loop will run 5 (outer loop count) * 10 (inner loop count) = 50.
rows = 6 for num in range(rows): for i in range(num):
Loops run the same set of code for a defined number of times or until the test condition becomes False, but sometimes we might wish to stop the loop even before the test condition becomes False or skip an iteration.
In those cases, we can use the break and continue statements.
The break keyword is used to break out / get out of the loop and execute the next statement.
Syntax:
while expression: if condition: break #breaks out of the loop
#executes statement outside the loop
word = input('Enter a word: ') for letter in word: if letter in 'aeiou': print('Vowel found!') break
Enter a word: apple Vowel found!
Here, the loop runs for all the letters in the word entered by a user. Inside the loop, Python checks the condition if the letter is a vowel or not (i.e., a, e, i, o, u). If the condition becomes True, Python runs the break statement in line 5, which forces it to stop the loop.
The continue keyword is used to skip the execution of statements ahead in the loop. Python skips the statements after the continue keyword in the current iteration/cycle of the loop and does not stop the loop.
Syntax:
while expression: Statement_1 if condition: continue
#skips next set of statements and starts with next loop
Statement_2
for num in range(1,11):
if num == 4 or num== 6 or num==8:
#When num = 5, it's False
Here, the for loop starts counting from 1. In each loop, it increases the value of num by 1, and when num is equal to 4, 6, or 8 (i.e., the condition in line 2) is True, Python runs the continue statement, which forces it to skip the lines below it. That is why the numbers 4, 6, and 8 are not displayed in the output.
Practice Question:
1. Write a program to print numbers in decreasing order from 10 using a while loop.
2. Write a program to print the first 10 even numbers in reverse orders.
3. Write a program to find the sum of digits of a number accepted from the user.
4. Write a program to display the following pattern of stars.
About this book
This coding book is supplementary to the main “Mel n Conji” content book. This book represents a 21st-century approach to learning coding concepts and developing computational thinking and problem-solving skills. To prepare students for the digital age, the curriculum is interwoven with well-thought-out concept graduation with real-life examples and practice problems.
• Illustrative approach: Concepts in coding and computer science are delivered through pictorial representations and learner-friendly approaches.
• Learning through real-life examples: Age-appropriate examples that enable learners to relate to the concept and learn about the unknown from the known.
• Extensive practice: Multiple practice scenarios to reinforce learnings.
• Coding Challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.
About Uolo Explore more
UOLO partners with K12 schools to bring technology-based learning programs. We believe pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. UOLO is trusted by over 8,000 schools with more than 3 million learners across India, South East Asia, and the Middle East.
hello@uolo.com