Wednesday, February 28, 2024

If Statements

 

If Statements

These statements are a bit like asking a question. You are telling the computer: if something is true, then do this specific block of code. Double equals (==) is asking the computer to compare if these two things are exactly the same.

In the code below, I am asking if the variable myName is the same as the string Dravid

myName = input("What's your name?: ")
if myName == "Dravid":   

But that doesn't print anything?

To create a print statement related to the input from the if statement, you must go to the next line and indent once.

An Example as a code  :- 

myName = input("What's your name?: ")
if myName == "Dravid":
  print("Welcome Dude!")   

What is else?

If the condition is not met with the if statement, then we want the computer to do the else part instead. Likewise, if the condition is met in the if statement, then the else bit is ignored by the computer. The else statement must be the first thing unindented after the if statement and in line with it.

myName = input("What's your name?: ")
if myName == "Dravid":
 print("Welcome Dude!")
 print("You're just the baldest dude I've ever seen")
else:
 print("Who on earth are you?!")  

What the elif is this?

The elif command (which stands for 'elseif') allows you to ask 2, 3, 4 or 142 questions using the same input! This command must be in a certain place. You can have as many elif statements as you want, but they must go in between if and else and have the same indentation. The print statements in your elif command need to line up with the indent of the other print statements.

An Example as a code  :- 
print("Secure login into Rude Rows")
userName = input("Tell me your Username:")
password =  input("Put your password here:")
if userName == "Ruderows" and password== "abcd" :
   print("Hey there",userName)
elif userName == "suman"  and password== "efgh":
  print("Hey there",userName)
elif userName == "biman" and password== "ijkl":
  print("Hey there",userName)
else :
  print("Go away")

No comments:

Post a Comment

  2D Dictionaries Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it...