Python Basic if statements - python

Hi Guys for the below code i want to execute only if the first condition satisfy so please help me
print('welcome')
username = input()
if(username == "kevin"):
print("Welcome"+username)
else:
print("bye")
password = input()
if(password == "asdfg"):
print("Acess Granted")
else:
print("You Are not Kevin")

If I got this right, you want to exit/terminate the script at the "else" block of the 1st if statement.
There are two approaches - 1st is that you use sys.exit():
import sys
#if statement here
...
else:
print("bye")
sys.exit()
2nd is that you put your 2nd if under the 1st if's else block:
...
else:
password = input()
if password=="abcdef":
#do something here
else:
print("you're not Kevin")
Also, I see that you're using brackets after the if statements (if (condition):). That is not necessary for Python 3.x as far as I'm concerned.
See: https://repl.it/CEl7/0

Related

Is that a way to break a while loop in the if loop, like I want if the certain variable is true, than the while loop ends

What i want is if you choose a specific things to do by typing 1 or 2,but it will always
run the 'gen' option(number 1) even if you type 2.
while True:
a=int(input("pls choose what do you want to do.\n1=generates password \n2=acess saved passwords \n3=save passwords\nenter here:"))
if a == 1:
gen=True
break
if a==2:
see=True
break
if a==3:
save=True
break
else:
print('pls enter a valid respond\n----------------------------------------')
continue
if gen: #*<--it will always run this*
break
break
if see:
f = open("data.txt", "a")#*this did not run if typed '2'*
content=f.read()
f.close()
print(content)
Remove the break from if statement
while True:
a=int(input("pls choose what do you want to do.\n1=generates password \n2=acess saved passwords \n3=save passwords\nenter here:"))
if a == 1:
gen=True
break---> Your code break when you type 1
if a==2:
see=True
break ---> Your code break when you type 2
if a==3:
save=True
break
else:
print('pls enter a valid respond\n----------------------------------------')
continue
if gen: #*<--it will always run this*
break
break
if see:
f = open("data.txt", "a")#*this did not run if typed '2'*
content=f.read()
f.close()
print(content)`enter code here`
It's not entirely clear what you're asking, but there are at least two things you should change to accomplish what I imagine it is you're trying to do. First, you should use elif for the conditions a == 2 and a == 3:
if a == 1:
gen = True
break
elif a == 2:
see = True
break
elif a == 3:
save = True
else:
print(...)
continue
...
Right now, it appears that you will ask for a valid response whenever the input is not 3 (including when it is 1 or 2), but I imagine you only wish to print this statement when the inputs is not 1, 2, or 3.
Second, the reason f = open("data.txt"...) did not run is that this code block is inside the while loop. Whenever part of the code causes the program to exit the while loop (such as a break statement), nothing in the rest of the loop will be executed, including the if see: block.

How do you stop a loop when a condition is met?

I'm a complete newbie to the coding trying my hands on python. While coding a simple program to calculate the age I ran into an error I cannot seem to fix no matter how hard I try. The code is pasted below. The program runs as far as I enter an year in the future, however when an year which has passed is used, the code loops again asking if the year is correct. Any help is appreciated.
from datetime import date
current_year = (date.today().year)
print('What is your age?')
myAge = input()
print('future_year?')
your_age_in_a_future_year= input()
future_age= int(myAge)+ (int(your_age_in_a_future_year)) - int(current_year)
def process ():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = input()
if answer =='yes':
print (future_age)
if answer == 'no':
print ('cya')
while answer != 'yes' or 'no':
print ('enter correct response')
process ()
process()
In this case, your function just needs to contain a while loop with an appropriate condition, and then there is no need to break out from it, or do a recursive call or anything.
def process():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')
try
...
if future_age > 0:
print(future_age)
return
else:
print('do you really want to go back in time?, enter "yes" or "no"')
...

break out of two loops without disturbing the if statements after it in python

I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')

Code end up in an endless loop. Can't see why

I am working on a simple function to let the user select the language.
But for some reason, I can't see my mistake and the while loop never breaks.
def chooseLanguage():
"""Simple function to let the user choose what language he wants to play in"""
if game["language"] == "en_EN":
import res.languages.en_EN as lang
elif game["language"] == "de_DE":
import res.languages.de_DE as lang
else:
while game["language"] is None:
print ("Hello and welcome! Please select a language.")
print ("1. German / Deutsch")
print ("2. English")
langC = input ("Your choice: ")
if inputValidator(1, langC) == 1:
game["language"] = "de_DE"
break
elif inputValidator(1, langC) == 2:
game["language"] = "en_EN"
break
if game["language"] is None:
chooseLanguage()
else:
pass
Evidently the infinite loop was caused by inputValidator returning a value that was neither equal to 1 or 2. Thus the exit conditions of the loop were never met. And so it continues.

errors with Elif expected indented block

I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.
when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.
elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.
def print_menu(self,car):
print ("1.Search by platenumber")
print ("2.Search by price ")
print ("3.Delete 3")
print ("4.Exit 4")
loop=True
while loop:
print_menu()
ans==input("Please choose from the list")
if ans==1:
print("These are the cars within this platenumber")
return platenumber_
while ans:
if ans==2:
elif ans==2:
print("These are the prices of the cars")
return price_
elif ans==3:
print("Delete the cars ")
return delete_
elif ans==4:
return Exit_
loop=False
else:
raw_input("please choose a correct option")
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.
loop=True
while loop:
print_menu()
ans = int(input("Please choose from the list"))
if ans==1:
print("These are the cars within this platenumber")
# return some valid information about plate numbers
elif ans==2:
print("These are the prices of the cars")
# return some valid information about pricing
elif ans==3:
print("Delete the cars ")
# Perform car deletion action and return
elif ans==4:
# I am assuming this is the exit option? in which case
# return without doing anything
else:
# In this case they have not chosen a valid option. Send
# A message to the user, and do nothing. The while loop will run again.
print("please choose a correct option")
Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.

Categories

Resources