print() Command
The print() function in Python is used to output data to the screen.
Syntax: print(“message to be printed”)
Example:
print("Hello world! ")
Output:
Hello world!
input() Command
The input() function in Python is used to read a line of text from keyboard.
It accepts the line as a string by default.
When you want to work with numbers entered by the user, such as integers or floats, you need
to convert the string returned by input() to the appropriate numerical type using Python's type
conversion functions. Here's how you can handle integers and floats when using input().
Example 1: age = int(input("Enter your age: "))
Example 2: age = float(input("Enter your marks: "))
Syntax:
input(‘prompt’)
or
variablename = input(‘prompt’)
Note: prompt is a message to display on the screen before accepting the input. This is optional.
Example:
name = input("Enter your name: ")
print("Hello", name)
In this example, the program will pause and display
"Enter your name:", wait for the user to type something followed by Enter, and then store the input in
the name variable. The next print() function then outputs the greeting with the entered name.
Both print() and input() are essential for basic input/output operations in Python, making them
fundamental for interactive applications.
Examples on print and input commands
Question 1: Greet the User
Program Output
name = input("What is your name? ") What is your name? Emily
print("Hello, " + name + "!") Hello, Emily!
Explanation: This program asks the user to input their name and then greets them by name. The
input() function collects user input after displaying the prompt "What is your name?". The print()
function is then used to concatenate and display the greeting message.
Question 2: Calculate Age in Future Year
Program Output
current_age = input("How old are you? ") How old are you? 12
future_age = int(current_age) + 5 In 5 years, you will be 17 years old.
print("In 5 years, you will be " + str(future_age) + " years old.")
Explanation: The program first asks for the user's current age and then calculates their age in 5 years.
The input() function retrieves the age as a string, which is converted to an integer using int(). The
future age is calculated and then converted back to a string to be printed with the message.
Question 3: Favorite Subject
Program Output
subject = input("What is your favorite school subject? ") What is your favorite school subject?
print(subject + " sounds like a lot of fun!") Math
Math sounds like a lot of fun!
Explanation: The user is asked to enter their favorite school subject, and the program responds with a
positive comment about it. The input() function captures the subject, and the print() function outputs a
custom message including the subject.
Question 4: Adding Numbers
Program Output
print("Enter two numbers and I will add them.") Enter two numbers and I will add them.
number1 = int(input("First number: ")) First number: 7
number2 = int(input("Second number: ")) Second number: 8
sum = number1 + number2 The sum of the numbers is: 15
print("The sum of the numbers is: " + str(sum))
Explanation: This program prompts the user to enter two numbers and calculates their sum. Each
number input is converted from a string to an integer. The sum is then calculated and converted back
to a string for display in the final print() statement.
Variables
Definition: A variable in Python is like a box where you can store information. It holds data
that can be used later in the program.
Naming: You can name a variable almost anything, but there are some rules:
The name must start with a letter or underscore (_).
The name cannot start with a number.
It can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
Variable names are case-sensitive (age, Age, and AGE are different variables).
Creating a Variable: You create (or declare) a variable by assigning it a value with the =
operator.
Example: age = 12 creates a variable named age and stores the number 12 in it.
Data Types
Python has several data types that define the operations that can be done on the values and the storage
method for each of them. The most common types for beginners are:
1. Integers (int): These are whole numbers without a decimal point.
Example: age = 12
2. Floating-point (float): These are numbers with a decimal point.
Example: height = 5.4
3. Strings (str): These are sequences of characters, typically used to represent words or text.
They are enclosed in quotes.
Example: name = "Emily"
4. Booleans (bool): This type only has two possible values: True and False. It is often used to
keep track of conditions that can be either true or false. Do not use quotes for True or False.
Example: is_student = True
How to Use Variables
Assignment: You can change the value of a variable by assigning a new value to it.
Example: age = 14 (now age is 14, not 12)
Operations: You can perform operations with variables. The operations available depend on
the data type.
Example with integers: new_age = age + 2 (if age is 12, then new_age will be 14)
Example with strings: full_name = first_name + " " + last_name (concatenates two
strings with a space between)
Dynamic Typing or Type Conversion
Python is dynamically typed, which means you don’t need to declare the type of a variable
when you create it. Python figures out the type based on the value you assign.
You can change the type of data a variable holds by reassigning it to a different type of data.
Example: age = "twelve" (now age is a string, not an integer)
Understanding these basic concepts will help Grade 7 students get a solid start in learning how to
program in Python, allowing them to handle data and perform various operations effectively in their
coding projects.
Handling Integer Input
To convert the input string to an integer, you can use the int() function. This is useful when you
expect the user to input whole numbers.
Example:
# Ask the user to enter an age and convert it to an integer
age = input("Enter your age: ")
age = int(age) # Convert the input string to an integer
print("You are", age, "years old.")
Note: If the user inputs something that isn't an integer (like letters or decimal numbers), Python will
raise a ValueError. It's often a good idea to handle this possibility with a try-except block to make
your program more user-friendly.
Handling Floating-Point Input
To handle numbers with decimals, use the float() function to convert the input string to a floating-
point number.
Example:
# Ask the user to enter a height and convert it to a float
height = input("Enter your height in meters: ")
height = float(height) # Convert the input string to a
float
print("Your height is", height, "meters.")
Note: Similar to int(), if the user inputs something that isn't a number, using float() will also raise a
ValueError. Handling this with a try-except block can prevent the program from crashing and
provide feedback to the user to enter a valid number.
Comments
In Python, comments are used to annotate the code, providing explanations about what the
code is doing, why certain decisions were made, or to remind yourself and inform others of
what needs to be done.
Comments are not executed as part of your program, so they don't affect how your code runs.
They're essential for maintaining code, especially in a team environment or when you return
to your code after some time.
Python supports two types of comments: single-line comments and multi-line comments.
Single-Line Comments
Single-line comments start with a hash symbol (#) and extend to the end of the physical line. A
comment may appear at the start of a line or following whitespace or code, but not within a string
literal.
Example of Single-Line Comments:
# This is a single-line comment
x = 15 # This comment follows a line of code
Multi-Line Comments
Python uses multi-line strings by triple quotes """ or ''' that can function as multi-line comments
Example of Multi-Line Strings Used as Comments:
""" This is a multi-line string used as a comment.
You can write explanations across multiple lines here. """
def my_function():
""" The purpose of this function is to demonstrate how multi-line strings can be used as
comments within functions. """
print("Hello, world!")
String Concatenation
In Python, string concatenation involves joining two or more strings into one using the + operator. To
concatenate strings with other data types (like integers or floats), you must first convert these types to
strings using the str() function to avoid type errors.
Example of String Concatenation:
name = "Alice"
age = 30
height = 5.4
description = name + " is " + str(age) + " years old and " + str(height) + " feet tall."
print(description)
Output:
Alice is 30 years old and 5.4 feet tall.
Mathematical Operators:
Mathematical operators are used to perform arithmetic operations in
Python.
Common mathematical operators include addition (+), subtraction (-),
multiplication (*), division (/), and modulus (%).
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
Operator Description Example
// Floor Division a // b
% Modulus (Remainder) a%b
** Exponentiation a ** b
Example program
result_addition = 5 + 3
print("Addition:", result_addition)
result_subtraction = 8 - 2
print("Subtraction:", result_subtraction)
result_multiplication = 4 * 6
print("Multiplication:", result_multiplication)
result_division = 10 / 2
print("Division:", result_division)
result_floor_division = 10 // 3
print("Floor Division:", result_floor_division)
result_modulus = 10 % 3
print("Modulus:", result_modulus)
result_exponentiation = 2 ** 4
print("Exponentiation:", result_exponentiation)
Output:
Addition: 8
Subtraction: 6
Multiplication: 24
Division: 5.0
Floor Division: 3
Modulus: 1
Exponentiation: 16
Relational Operators:
Relational operators are used to compare values in Python.
Common relational operators include equal to (==), not equal to (!=),
greater than (>), less than (<), greater than or equal to (>=), and less
than or equal to (<=).
They return either True or False based on the comparison result
Operator Description Example
== Equal to x == y
!= Not equal to x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Examples:
# Equal to
result = (5 == 5) # result is True
# Not equal to
result = (5 != 3) # result is True
# Greater than
result = (10 > 5) # result is True
# Less than
result = (3 < 5) # result is True
# Greater than or equal to
result = (7 >= 7) # result is True
# Less than or equal to
result = (4 <= 2) # result is False
Logical Operators
Logical operators are used to combine multiple conditions in Python.
Common logical operators include AND (and), OR (or), and NOT (not).
They return either True or False based on the logical combination of
conditions.
Operator Description Example
and Logical AND x and y
or Logical OR x or y
not Logical NOT not(x > 0)
and: Returns True if both statements are true.
or: Returns True if one of the statements is true.
not: Reverse the result, returns False if the result is true.
Conditional Statements:
Conditional statements allow you to execute different blocks of code based
on certain conditions.
The if statement is used to execute a block of code if a condition is True.
The if-else statement is used to execute one block of code if the
condition is True and another block if it's False.
The elif statement is used to check multiple conditions sequentially.
Examples on if statement
Program 1: Check if a Number is Positive
number = 5
if number > 0:
print("The number is positive.")
Explanation: This program checks if the variable number is greater than zero.
Since 5 is greater than 0, it prints "The number is positive."
Program 2: Determine if a Person is a Teenager
age = 13
if age >= 13 and age <= 19:
print("You are a teenager!")
Explanation: This program checks if the variable age falls within the range that
defines teenagers (13 to 19 years old). The if statement uses logical operators to
ensure the age is between these values. Since 13 is within this range, it prints
"You are a teenager!"
Program 3: Check for Passing Grade
grade = 75
if grade >= 70:
print("You passed the exam.")
Explanation: This program evaluates whether the grade is 70 or higher, which
is often the threshold for passing. Since the grade is 75, the program prints "You
passed the exam."
Program 4: Determine Eligibility for a Competition
age = 18 if age >= 18:
print("You are eligible to participate in the
competition.")
Explanation: This program checks if a person is 18 years old or older to
determine if they are eligible to participate in an adult competition. Since the age
is 18, it prints "You are eligible to participate in the competition."
Program 5: Verify Login Credentials
username = "admin"
password = "12345"
if username == "admin" and password ==
"12345":
print("Access granted!")
Explanation: This program checks if both the username and password match a
predefined set of credentials. Since both the username and password match
correctly, the program prints "Access granted!"
Programs on if else
Program 1: Determine if a Number is Positive or Negative
number = -3
if number > 0:
print("The number is positive.")
else:
print("The number is negative.")
Explanation: This program determines whether a number is positive or
negative. If the number is greater than zero, it prints "The number is positive."
Otherwise, it prints "The number is negative."
Program 2: Check Adult or Minor Status
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Explanation: This program checks if someone's age qualifies them as an adult
(18 or older). If not, it identifies them as a minor.
Program 3: Maximum of Two Numbers
a=5
b=8
if a > b:
print("a is greater than b.")
else:
print("b is greater than or equal
to a.")
Explanation: Here, two numbers are compared. The program prints which
number is greater. If a is not greater than b, it defaults to stating that b is
greater or equal to a.
Program 4: Pass or Fail
grade = 60
if grade >= 50:
print("Congratulations! You
passed.")
else:
print("You failed. Try harder
next time.")
Explanation: This example evaluates whether a student's grade is sufficient to
pass (assuming the passing mark is 50). It outputs a congratulatory message if
the student passes, otherwise a motivational message for failure.
Program 5: Discount Eligibility
total_purchase = 250
if total_purchase > 200:
print("You are eligible for a 10%
discount!")
else:
print("Spend more than $200 to get a
10% discount.")
Explanation: This program decides if a customer's total purchase qualifies them
for a discount. If the purchase exceeds $200, it announces eligibility for a 10%
discount. Otherwise, it advises how much more needs to be spent to receive the
discount.
Programs on elif
Program 1: Grading System
score = int(input("Enter your
score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Explanation:
This program takes a numerical score from the user and assigns a grade based
on the score. The elif is used here to differentiate between different grading
scales.
Program 2: Age Group Classifier
age = int(input("Enter your age:
"))
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 60:
print("Adult")
else:
print("Senior")
Explanation:
The program determines the age group of a person based on the age input. It
uses elif statements to cover different age ranges, ensuring that each age falls
into one specific category.
Program 3: Transportation Suggestion
distance = float(input("Enter the distance to your
destination (in km): "))
if distance < 1:
print("Walking is recommended.")
elif distance < 5:
print("Consider cycling.")
elif distance < 20:
print("It's better to take a car.")
else:
print("Use public transport or a long-distance service.")
Explanation:
This program suggests modes of transportation based on the distance to a
destination. The elif statements help provide the most practical advice for
different ranges of distances.
Program 4: Activity Recommendation Based on Weather
temperature = int(input("Enter the current temperature in
degrees Celsius: "))
if temperature > 30:
print("It's hot, consider swimming.")
elif temperature > 20:
print("Nice weather for a walk.")
elif temperature > 10:
print("Might be a bit chilly, wear a jacket.")
else:
print("Very cold, staying indoors is recommended.")
Explanation:
This program gives activity recommendations based on the temperature. It uses
elif to handle different temperature ranges, offering appropriate advice for each.
Program 5: Discount Calculator
total_purchase = float(input("Enter the total purchase
amount: "))
if total_purchase > 1000:
discount = 0.1 # 10% discount
elif total_purchase > 500:
discount = 0.05 # 5% discount
else:
discount = 0 # no discount
final_amount = total_purchase * (1 - discount)
print("After discount, your total is: “, final_amount)
Explanation:
This program calculates the final amount to be paid after applying a discount
based on the purchase amount. The elif allows for different discount rates
depending on how much is spent.
for loop
Syntax:
for i in range(start, stop,
step):
# Code block
range() generates a sequence of numbers starting from start, up to (but not
including) stop, incrementing by step (which defaults to 1 if not provided).
The loop iterates over each value generated by range(), assigning it to the
variable i, and executes the code block for each iteration.
Programs on for loop
Program 1: Sum of First N Natural Numbers
n = int(input("Enter the number of terms: "))
sum = 0
for i in range(1, n+1):
sum += i
print("The sum of the first", n, "natural numbers
is:", sum)
Explanation:
that iterates from 1 to 𝑛, adding each number to a sum variable.
This program calculates the sum of the first n natural numbers using a for loop
Program 2: Multiplication Table
number = int(input("Enter the number for the multiplication
table: "))
for i in range(1, 11): # Multiplication table
from 1 to 10
print(number, "x", i, "=", number * i)
Explanation:
The program prints the multiplication table for a given number from 1 to 10. It
uses a for loop to iterate through the multipliers.
Program 3: Counting Odd and Even Numbers
n = int(input("Enter the upper limit: "))
odd_count = 0
even_count = 0
for i in range(1, n + 1):
if i % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Number of odd numbers:",
odd_count)
print("Number of even numbers:",
even_count)
Explanation:
This program counts the number of odd and even numbers between 1 and 𝑛. It
uses a for loop to iterate through each number, checking if it is odd or even and
updating the respective counters.
Program 4: Generate a Series of Squares
n = int(input("Enter the number of terms in the square
series: "))
print("The first", n, "squares are:")
for i in range(1, n + 1):
print(i * i, end=" ")
Explanation:
This program outputs the first 𝑛 square numbers. A for loop is used to iterate
over a range of numbers from 1 to n, calculating the square of each number and
printing it.
While Loop:
The while loop in Python is used to repeatedly execute a block of code as long as
the specified condition remains true. It continues execution until the condition
becomes false.
Syntax
while condition:
# code block
Key Points:
1. Condition: The loop continues executing as long as the condition
evaluates to True.
2. Initialization: Ensure that variables used in the condition are initialized
before the loop.
3. Increment or Decrement: Inside the loop, ensure there's a mechanism
(usually an increment or decrement operation) that eventually makes the
condition false, or else it could result in an infinite loop.
4. Flow Control: You can control the flow of the loop using break,
continue,
Program 1: Guessing Game
This program lets the user guess a predefined number until they get it right.
secret_number = 7
guess = None
# Start the guessing game
while guess != secret_number:
guess = int(input("Guess the number: "))
if guess < secret_number:
print("Too low, try again!")
elif guess > secret_number:
print("Too high, try again!")
print("Congratulations! You guessed the
number.")
Explanation:
The while loop continues to run as long as the user's guess is not equal to the
secret number. Inside the loop, the program takes an input guess from the user,
checks if it is too high or too low, and provides feedback accordingly.
Program 2: Exponentiation Without Using **
This program calculates the power of a base number raised to an exponent using
multiplication in a while loop.
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1
counter = 0
while counter < exponent:
result *= base
counter += 1
print(base, “raised to the power of “, exponent , “is
“, result)
Explanation:
The while loop runs from 0 up to (but not including) the exponent. Each iteration
multiplies the current result by the base, effectively raising the base to the power
of the exponent by the end of the loop.
break Statement:
The break statement is used to terminate the loop prematurely based on a
certain condition.
When encountered inside a loop, it immediately exits the loop, regardless of
whether the loop's condition has been satisfied.
It is often used to prematurely end a loop when a specific condition is met,
avoiding unnecessary iterations.
Example:
for i in range(1, 11):
if i == 5:
break
print(i)
Output: 1, 2, 3, 4
continue Statement:
The continue statement is used to skip the rest of the code inside the loop for the
current iteration and proceed to the next iteration.
When encountered, it jumps directly to the next iteration of the loop, without
executing the remaining statements inside the loop block.
It is often used to skip certain iterations based on a specific condition, without
terminating the loop entirely.
Example:
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
Output: 1, 3, 5, 7, 9
Comparison:
break terminates the entire loop when a condition is met, whereas continue skips
the current iteration and proceeds to the next iteration.
break is used to exit the loop prematurely, while continue is used to skip specific
iterations within the loop.
In summary, nested control structures in Python provide a way to handle more
complex logic by nesting one control structure inside another. They are
commonly used in situations where decisions or loops depend on other decisions
or loops. Proper indentation is crucial for readability and correctness when using
nested control structures
break:
Terminating a loop early when a specific condition is met (e.g., finding a target
element in a list).
Ending a loop when an error condition occurs.
continue:
Skipping certain iterations based on conditions (e.g., skipping even numbers in a
loop).
Implementing conditional logic within loops to control the flow of execution.
Nested Loops
Nested loops are loops inside other loops.
They allow us to perform repetitive tasks in a structured way.
Structure of Nested Loops:
There's an outer loop and one or more inner loops.
The inner loop is fully contained within the outer loop.
Controlling Outer and Inner Loops:
The outer loop determines how many times the inner loop will run.
The inner loop performs its task each time the outer loop runs.
Multiplication Table
# Outer loop for rows
for i in range(1, 6):
# Inner loop for columns
for j in range(1, 11):
# Print the product of i and j
print(i * j, end='\t')
# Move to the next line after each row
print()
Functions
Functions are like mini-programs inside a larger program.
They help us break down tasks into smaller, manageable parts.
Defining Functions:
We use the def keyword to define (create) a function.
After def, we give the function a name followed by parentheses () and a colon :.
Calling Functions:
To use a function, we "call" it by using its name followed by parentheses ().
Example of Defining and Calling a Function:
# Defining a function
def greet():
print("Hello, world!")
# Calling the function
greet()
Output: Hello, world!
Understanding the Process:
When we define a function, we're telling Python what actions it should perform
when called.
When we call a function, Python executes the code inside the function.
No Parameters:
In this example, our function greet() doesn't require any information to do its job.
It simply prints a greeting message.
Why Use Functions?
Functions help us write cleaner, more organized code.
They make it easier to reuse code without rewriting it.
Conclusion:
Functions are like specialized tools in a toolbox. We define them to perform
specific tasks, and we can call them whenever we need to use them.
Functions with Parameters:
Functions can accept input data called parameters or arguments.
Parameters allow us to customize the behavior of a function.
Defining Functions with Parameters:
When defining a function, we can specify parameters inside the parentheses ().
These parameters act as variables within the function.
Calling Functions with Parameters:
When calling a function with parameters, we provide values or variables inside
the parentheses.
Example of Defining and Calling a Function with Parameters:
# Defining a function with parameters
def greet(name):
print("Hello,", name, "!")
# Calling the function with a parameter
greet("Alice")
Output: Hello, Alice!
Understanding Parameters:
In this example, the function greet() accepts a parameter called name.
Inside the function, name behaves like a variable that holds the value we provide
when calling the function.
Passing Multiple Parameters:
Functions can accept multiple parameters separated by commas.
Example of a Function with Multiple Parameters:
# Defining a function with multiple parameters
def add_numbers(x, y):
result = x + y
print("Sum:", result)
# Calling the function with multiple parameters
add_numbers(3, 5)
Output: Sum: 8
Default parameters are values assigned to a function's parameters, which are
used when the function is called without providing corresponding arguments for
those parameters. Here are some key points regarding default parameters in
Python:
Syntax: Default parameters are specified in the function definition by assigning
a value to the parameter name. For example:
def greet(name='Guest'):
print("Hello, {name}!")
In this example, name is a parameter with a default value of 'Guest'.
Usage: Default parameters allow functions to be called with fewer arguments
than they are defined to accept. If a value is not provided for a parameter when
calling the function, the default value will be used.
Why Use Parameters?
Parameters allow functions to be more flexible and reusable.
They enable us to perform the same task with different input values.
Conclusion:
Functions with parameters enable us to create versatile and adaptable code, as
we can customize their behavior based on the input provided.
Function Namespaces
Functions in Python have their own namespaces, which play a crucial role in
organizing and managing variables, functions, and other objects within the
function's scope. Here are some key points regarding function namespaces in
Python:
Local Scope:
Definition: Local scope refers to the namespace created within a function when
it is called. Any names (variables, parameters, or nested functions) defined
within the function are considered local to that function.
Access: Variables defined in the local scope are accessible only within the
function's block of code where they are defined. They cannot be accessed from
outside the function.
Lifetime: The lifetime of variables in the local scope begins when the function is
called and ends when the function exits. After the function exits, local variables
are destroyed, and their memory is released.
Example:
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
# print(x) # Error: NameError: name 'x' is not defined
Global Scope:
Definition: Global scope refers to the namespace that exists outside of any
function. Names defined at the top level of a Python module or script are
considered global and belong to the global namespace.
Access: Global variables can be accessed from anywhere within the module or
script, including within functions. However, accessing global variables from
within functions without proper declaration can lead to scope-related issues.
Lifetime: Global variables persist throughout the execution of the program.
They are created when the module is imported or when the script is executed,
and they exist until the program terminates.
Example:
global_var = 20 # Global variable
def my_function():
print(global_var)
my_function() # Output: 20