Day 3- Facilitation Guide
Programming Statements
Index
I. Recap
II. Programming Statements
III. User Input
IV. Comments in Program
(1.5 hrs) ILT
I. Recap
In our last session we learned:
● Variables and Constants:Variables and constants are fundamental concepts in
programming and represent different types of data storage in a program.
● Operators and its Precedence:Operators in programming are symbols or
keywords that represent specific operations or actions to be performed on data.
Each operator has a precedence level, which determines the order in which
operators are evaluated in an expression. When an expression contains multiple
operators, the operator with higher precedence is evaluated first.
In this session we are going to learn about Programming Statements,User Input and
how to use Comments in Programming.
Note: Every programming language follows certain syntax.
Syntax refers to the rules that define the structure of a language. Syntax in computer
programming means the rules that control the structure of the symbols, punctuation,
and words of a programming language.
Without syntax, the meaning or semantics of a language is nearly impossible to
understand.
For example,
A series of English words, such as —
subject a need and does sentence a verb ?
The above has little meaning without syntax.
Applying basic syntax results in the sentence —
Does a sentence need a subject and verb?
Now the above line is more understandable as we applied the sentence formation
rules of the English language.
Programming languages function on the same principles.
If the syntax of a language is not followed, the code will not be understood by a
compiler or interpreter.
II. Programming Statements
Programming statements are fundamental instructions or commands that make up the
code of a computer program. These statements tell the computer what actions to
perform and how to perform them. Statements are the building blocks of algorithms and
logic that control a program's behavior. Common types of programming statements
include:
[Link] Statements:
Assign values to variables or data structures.
Example : x = 10
[Link] Statements:
Perform calculations or evaluate expressions.
Example: result = x + y
[Link] Statement:
Used to display output to the console.
print("Hello, World!") # Display "Hello, World!"
[Link] Statement:
Accepts user input and assigns it to a variable.
name = input("Enter your name: ") # Prompt user for input
print(name)
[Link] Statements (if, elif, else):
Used to execute code based on a condition.
Syntax:
If condition:
# statement if true
else
# statement if condition is false
Control program flow based on conditions.
x=20
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
[Link] Loop:
Repeat code while a condition is true.
Syntax:
while condition:
# statements
# increment/decrement
count = 0
while count < 5:
print(count)
count += 1
[Link] Loop:
Iterates through a sequence of items.
Syntax:
for variable in sequence:
# statements
for i in range(5):
# Loop from 0 to 4
print(i)
[Link] Definition and Invocation:
Functions are reusable blocks of code.
Syntax:
def function-name(parameter 1, parameter 1, ..):
# statements
def add_numbers(a, b):
return a + b
result = add_numbers(3, 7) # Call the function
[Link] Creation and Manipulation:
Lists hold sequences of elements.
my_list = [1, 2, 3, 4, 5] # Create a list
my_list.append(6) # Add an element
[Link] Handling (try, except, finally):
Handle errors gracefully.
Syntax:
try:
# statements that can throw error
except ExceptionType as object:
# statements for handling exception
try:
result = 10 / 0 # Attempt to divide by zero
except ZeroDivisionError as e:
print("Error:", e)
[Link] and Continue Statements:
Alter the flow of loops.
for i in range(10):
if i == 5:
break # Exit the loop when i equals 5
if i == 3:
continue # Skip the rest of the loop body for i equals 3
print(i)
12. Return Statement:
Used in functions to return values.
def square(x):
return x ** 2 # Return the square of x
print(square(3))
13. Comments:
Comments provide explanations and are not executed.
# This is a single-line comment
"""
This is a
multi-line comment
"""
These are essential Python programming statements that form the foundation of Python
programming. You can use these building blocks to create more complex programs and
applications by combining and modifying them as needed.
P.N - We will learn in detail about the programming statements such as
conditional statements, loops, functions, etc in the upcoming sessions
III. User Input
In Python, you can capture user input using the input() function. The input() function
reads a line of text entered by the user from the keyboard and returns it as a string.
Here's how you can use input() to get user input:
# Get user input and store it in a variable
user_input = input("Enter something: ")
# Display the user's input
print("You entered:", user_input)
In this example:The input("Enter something: ") statement prompts the user to enter
something by displaying the text "Enter something: ".
The user enters text at the keyboard, followed by pressing the Enter key.
The input() function reads the entered text and assigns it to the user_input variable as a
string.
Finally, the program prints the user's input back to the console.
Below is the output
Note: that input() always returns a string, even if the user enters numerical values. If
you need the input as a different data type (e.g., integer or float), you should explicitly
convert it using functions like int() or float():
Another example of input() function which will accept your age and display the
age by adding 1
# Get an integer input from the user
user_age = int(input("Enter your age: "))
# Perform calculations using the integer input
next_year_age = user_age + 1
print("Next year, you'll be", next_year_age, "years old.")
Output:
In this example, int(input()) converts the user's input to an integer, allowing you to
perform arithmetic operations with it.
Remember to handle user input with care, especially if the program expects specific
input formats or needs to handle potential errors (e.g., non-integer input when expecting
an integer). You may want to include error-checking and validation to ensure the input
meets your program's requirements.
Another example of input() function which will accept two number and display
their addition, subtraction and multiplication and division
# Accept two numbers as input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform arithmetic operations
sum_result = num1 + num2
diff_result = num1 - num2
prod_result = num1 * num2
div_result = num1 / num2
# Display the results
print(f"Addition: {num1} + {num2} = {sum_result}")
print(f"Subtraction: {num1} - {num2} = {diff_result}")
print(f"Multiplication: {num1} * {num2} = {prod_result}")
print(f"Division: {num1} / {num2} = {div_result}")
In this code:
We use the input() function to accept two numbers as input from the user. We convert
the input values to floating-point numbers using float() to handle decimal input.
We perform the addition, subtraction, and multiplication operations on the input
numbers and store the results in variables.
We check if the second number is zero before performing division to avoid division by
zero errors. If the second number is zero, we display a message indicating that division
by zero is undefined.
Finally, we display the results of all four operations using formatted strings with print().
IV. Comments in Program
Comments in a program are non-executable lines of text that provide explanations,
notes, or documentation about the code. They are used to make the code more
understandable for programmers (including yourself) and anyone else who may read or
maintain the code in the future. Comments are ignored by the compiler or interpreter
and do not affect the program's functionality. In Python, comments are created using the
# symbol.
Here's how you can use comments in your Python code:
● Single-Line Comments:You can add comments on a single line by prefixing the
text with a # symbol. Everything after # on the same line is treated as a
comment.
# This is a single-line comment
result = 42 # This comment explains the purpose of the following line of code
● Multi-Line Comments (Docstrings):For longer comments or documentation
strings, Python allows multi-line strings enclosed in triple quotes (''' or """) at the
beginning of a module, class, function, or method. These are often used as
docstrings to describe the purpose and usage of the module, class, or function.
'''
This is a multi-line comment or docstring.
It can span multiple lines and is typically used for documentation.
'''
def add(x, y):
"""
This is a docstring for the add function.
It explains what the function does and describes its parameters.
Args:
x (int): The first operand.
y (int): The second operand.
Returns:
int: The sum of x and y.
"""
return x + y
Comments are an important part of code readability and maintenance. They can help
others (and your future self) understand your code's logic, purpose, and usage. Good
commenting practices make it easier to collaborate on projects and debug code when
issues arise.
Exercise ChatGPT
1. Hi can you help me with a program in Python to accept two number from the
user and calculate their square.
2. I need to create a program to check if a number is even or odd. Please help
with a program in Python to accept a number from the user and using ternary
operator check whether the number is even or odd.