Python inputs
Categories:
2 minute read
The input()
pauses a program and waits for user input. When received, the input is assigned to a variable.
message = input("What you type in the prompt, will be displayed back to you: ")
print(message)
prompt = "I'd like to say hello'."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello {name.title()}!")
Modulo operator
The modulo operator, represented by the percentage symbol %
, is a mathematical operation that returns the remainder when one number is divided by another. In Python, it works as follows:
result = dividend % divisor
Here, dividend
is the number you want to divide, and divisor
is the number you want to divide by. The result is the remainder of the division.
# Example 1
result = 10 % 3
print(result)
# Output: 1
In this example, 10 is divided by 3. The quotient is 3, and the remainder is 1. Therefore, the output of result
is 1.
# Example 2
result = 15 % 7
print(result)
# Output: 1
In this example, 15 divided by 7 gives a quotient of 2 and a remainder of 1. So, the output of result
is 1.
The modulo operator can be useful in many situations, such as:
Checking if a number is even or odd: If a number
x
is even, thenx % 2
will be 0. Otherwise, it will be 1.Wrapping around a range: If you want to ensure a number stays within a specific range, you can use the modulo operator. For example, if you have an hour value that goes from 0 to 23 and you want to handle cases where it exceeds that range, you can use
hour % 24
to wrap it around.Generating repeating patterns: You can use the modulo operator to create patterns that repeat after a certain interval. For instance, if you want a sequence of numbers from 1 to 5 to repeat indefinitely, you can use
i % 5
in a loop wherei
is the loop variable.
While loops
A while loops runs “while” a certain condition is true.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1