fromrandomimportrandintx=randint(1,3)y=randint(1,3)print("X is: ",x)print("Y is: ",y)if(x==y):print("X is equal to Y")elif(x>y):print("X is greater")elif(x<y):print("Y is greater")else:print("Error: Please Try Again")
This generates a random number between 1 and 3 and assigns it to the variable x and y. Then it checks if they are greater, less than, or equal to each other.
If you run it a few times you get different outputs.
Here is a flow algorithm representing IF and ELSE
With all of this in mind we can start to create our program.
That works, we also wanted to implement a 3 try system right? We can acomplish this with a loop.
The while loop is like a repeating IF statment. Its name is what it does.
While x == true then iterate Something until x == false
So we can implement this into our code like this:
password="Password123"attempt=0while(attempt<3):print("Please Login:")x=input("Password: ")if(x==password):print("Password Correct")elif(x!=password):attempt=attempt+1print("Password Incorrect")print("Attempt Number "+str(attempt))
Now the program just ends even if we get the password right. We can fix this by adding some booleans that tell the program if the password is true or false
password="Password123"attempt=0while(attempt<3):print("Please Login:")x=input("Password: ")if(x==password):passwordCorrect="true"print("Password Correct")attempt=3elif(x!=password):passwordCorrect="false"attempt=attempt+1print("Password Incorrect")print("Attempt Number "+str(attempt)+" \n")if(passwordCorrect=="true"):print("Welcome back!")elif(passwordCorrect=="false"):print("You have been locked out for too many tries. \n Contact your administrator.")else:print("Error: Please Try Again")
This will have 2 outputs.
Password Incorrect:
Or Password Correct:
Today I showed you how to use IF and ELSE statements in python.
You also learned how to create a basic Password checker from scratch.
I hope you enjoyed this post, if you did please upvote and follow me (it helps!)