xxxxxxxxxx
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()
xxxxxxxxxx
word = input('Word: ') # This will ask you to print a word
if word == 'hello': # <- If your response is: 'hello'
print('world') # <- It will output: 'world'
elif word == 'world': # If the response is: 'world'
print("Hey, that's my line >:(") # It will print this
else:
print("Hey buster you gonna say hello or not?")
# If sombody prints ANYTHING ELSE other than 'hello' or 'world'
# It will output that print statment above!
#Hope this helped you!
xxxxxxxxxx
number = float(input("Number:"))
if number > 0:
print('Number is positive.')
print('The if statement is easy')
xxxxxxxxxx
# Prompt the user to enter a number
number = input("Enter a number: ")
# Check if the number is greater than 10
if int(number) > 10:
print("The number is greater than 10")
else:
print("The number is not greater than 10")
xxxxxxxxxx
##########
value_if_true if condition else value_if_false
x = 10
result = "x is positive" if x > 0 else "x is non-positive"
print(result)
##########
if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
###############
x = 10
if x > 0:
print("x is positive")
else:
print("x is non-positive")
##################
x = 0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
###########
xxxxxxxxxx
Yes, you can use or in place of an if-else statement in Python. Using or in this way is known as a "short-circuit evaluation" because the second condition is only evaluated if the first one is False.
Here's an example of using or in place of an if-else statement:
Copy code
x = 5
y = 10
result = x < 7 or y > 12
print(result) #True
This is equivalent to:
Copy code
if x < 7:
result = True
else:
result = y > 12
It's important to keep in mind that short-circuit evaluation can sometimes have unintended side effects. For example, if the variable on the left side of an or statement has a side effect (e.g., it modifies a global variable), that side effect will occur even if the variable on the right side of the or statement would have evaluated to True.
Also it's important to note that this idiom only works with boolean operations, you can't use "or" as a replacement of if-elif-else chain.
xxxxxxxxxx
if expression:
statement(s)
elif expression:
statement(s)
else:
statement(s)
xxxxxxxxxx
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")