I started studying programming recently.
I bought a book and I'm still learning, but I'm having trouble with the problem that came up in the middle.
Problem Description:
If the variable is less than 10, print a message.If it's more than 10, print another message.
I think it's very simple, but I don't understand it myself, so please let me know.
Thank you for your cooperation.
Simplest Implementation
#x_str contains the user-entered string.
x_str=input("Please enter a number:")
# Convert the string to an integer and substitute x.
x = int(x_str)
# Branches with if statements, where x<10 is True when x is less than 10.Otherwise, it will be False.
if x<10:
# If True, this block is executed.
print("Less than 10")
else:
# In case of False, this block is executed.
print("10 or more")
You can use the conditional operator to write the if part in one line.
print("less than 10" if x <10 else" 10 or higher")
If the variable is limited to integers greater than or equal to 0, you can also evaluate it by creating a set with all true values.
#correct_list contains integers from 0 to 9.
correct_list=list(range(10))
# If x is included in the correct_list...
print("Less than 10" if x correct_listelse" 10 or higher")
Above, we use list as a set, but it takes O(n) time to check from the beginning of the list to determine whether it is included, so it is better to use a set that can search with constant time O(1) as shown below.The set is called hashset in other languages and unordered_set in C++.
#correct_set contains integers from 0 to 9.
correct_set=set(range(10))
# If x is included in the correct_set...
print("Less than 10" if x correct_set else" 10 or higher")
Here's the answer that comes to mind.
© 2024 OneMinuteCode. All rights reserved.