how to use a conditional statement to stop a code with several inputs? - if-statement

I wrote a code and want to end it after the first input is equal to "done".
If I write the condition after all of the inputs, the user should answer all the useless questions.
On the other hand, I don't want to write the condition in the middle of the inputs as you see in the following part.
I would appreciate it if anyone could help me with this.
Here is the code:
while True:
ind1=input('please enter your personal number:')
if ind1=='done':
break
ind2=input('please enter your name:')
ind3=input('please enter your family name:')
ind4=int(input('please enter your working hours:'))
ind5=int(input('please enter your payment:'))

Instead of using multiple variables, use an array.
pseudo code:
inputs = []
count = 0
while true:
if inputs[count] == 'done': break
inputs[count] = input('...')
count++

Related

How to fix a loop with boolean variable

I'm doing a project for a class, and I opted to make a text based game in python. I'm trying to set it up so that the question will loop until the player confirms their choice, and I'm having problems with the while loop in this section.
def pc_cls_sc(x):
# code does some stuff
print "You are sure about" + str(x)
exVar = raw_input("Right?")
if exVar == "y":
print "Alright!"
conf_Class = True
else:
print "Ok then."
conf_Class = False
while conf_Class is False:
pc_Class = raw_input(#asks some question)
pc_cls_sc(pc_Class)
The rest of this code functions properly, but the loop continues after the conf_Class variable is supposed to be set to true. I have a similar loop earlier in my code, which works just fine. I've tried moving the variable reassignment outside of the pc_cls_sc function, but all it did was cause double output. Can anyone tell me how to fix this?
You can use break to exit the loop. The code below will keep asking a user for input until they say 'y'.
while True:
x=input("Right? " )
if (x=='y'):
break

Returning to the beginning of a piece of code when if statement condition is not met

I am totally new to programming and I have been trying to get a simple piece of code working. However I keep getting multiple different errors so I assume I am doing something very wrong somewhere along the line... Here is my code at the moment:
userName = input('Please enter your name: ')
age = input('Please enter your age: ')
if int(age) <= 5:
print(userName, 'you are too young to play') break
else:
print (userName, 'Your old enough')
factor = 2
finalAge = int(age) + int(factor)
multAge = int(age) * int(factor)
divAge = float(age) / int(factor)
print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge)
print('Your age divided by', factor, 'is', divAge)
What I want to do is, if the user's age is not higher than 5, then they get the message that they are too young to play and it returns to the start of the piece of code - asking for the name again.
Does anyone have any advice on how to do this?
You'll need to use a loop. Syntax depends on language, which you haven't specified. As pseudo-code, you could do
loop indefinitely
prompt for name and age
if age is less than 5
print error
otherwise
print that age is ok
break loop
Take a look at while loops. For this you'd be able to set some kind of condition (such as an "old_enough" variable and when that becomes true, the loop stops running.
You would set this value inside the if statement. By default it should be whatever will make the loop run
There's loads of tutorials online for this, but here's an example in python (your code sample looks like Python3):
old_enough = False
while not old_enough:
# do something
if age > 5:
print("You're old enough")
old_enough = True
else:
print("you're not old enough")
That should make sense. if not, please do look up documentation. It'll be better for you in the long term

How to create multiple loops in python

I'm trying to create a basic maths program which will randomly generate a numerical question and then allows 3 attempts to complete it before it moves onto the next question however cant figure out how to make it do both together.
My code currently looks like this
print "What is your name?"
score = 0
Attempt = 0
loop = True
Name = raw_input()
import random
for i in range (1,6):
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
print "What is", question_1_part_1, "+", question_1_part_2, "?"
while Attempt <3: # inputing this while loop here means it will retry the same question.
Guess = raw_input()
Guess = int(Guess)
answer = question_1_part_1 + question_1_part_2
if Guess == answer:
print "Well done"
score = score + 1
else: print "try again"
Attempt = Attempt + 1
if Attempt == 3: print "You failed"
print Name, "your score is", score
A simple break statement will take you out of the loop when the answer is correct.
if Guess == answer:
print "Well done"
score += 1
break
else: print "try again"
Note the change to your assignment; this is considered a cleaner increment.
To answer your comment ... you don't use this when the person gets the question wrong. Your program logic freezes out the user after three wrong guesses total, on all questions. If you want them to have up to three guesses on every problem, then you have to reset the Attempt counter for every question. Pull that line into the outer loop:
for i in range (1,6):
Attempt = 0
loop = True
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
In the future, I strongly recommend that you program incrementally: get a few lines working before you add more. Insert tracing print statements to check that the values and program flow are correct. Don't remove them until that part of the code is solid -- and even then only comment them out until the entire program is working. Some of your problems stem from trying to write more than you can comfortably hold in your mind at once -- which is common at most levels of programming. :-)
Add another argument to your while loop.
while Attempt <3 and Guess != ... :
rest of loop code
Then you are exiting your loop when they get the correct answer. Or you could break from the statement when they get the answer right.

Python input, ifstatement, return

I have to create a function that takes an input, and returns a corresponding Grade.
So for example if the user inputs A+ output is 90%
or
if the input is A output is 80%
or
if the input is B output is 70%
I have some sort of Idea on how to do this... but I am having trouble on wrapping my head around on how I can return the statement??
def percent (percentage):
if ( percentage )== A+
return ("90%")
elif (percentage)== A
return ("80%")
Is this the correct way of going about it?
OK, so first, welcome to Python. Second, this is Pythonic way of doing this - define a dict:
grades = {'A+': "90%", 'A': "80%", ...}
then
return grades[precentage]
will do the job.
You need to protect against the case where the grade is not in the dict, for example, if the user entered some mistake, like G. There are a few ways to go about that:
A simple if:
if precentage in grades:
return grades[precentage]
else:
return "bad precentage"
After you get used to Python you will be more aesthetic about your code and will want to do better than state twice bote grades and precentage, so you can do simply:
return grades.get(precentage, "bad precentage")
Or using a special dict with default values:
import collections
grades = collections.defaultdict(lambda: "bad precentage", [("A+", "90%"), ("A", "80%")])
then
grades[precentage]
will automatically return "bad precentage" upon bad input.
#user2829744 You don't want to have to repeatedly call if statements based on what the percentage is, that would make the code unnecessarily long.
Instead, you want to have a list or tuple (a variable which stores multiple elements) that the program can compare the user's inputted value to, and then calculate the percentage mark.
Take this for example:
def percentage(per):
grades=["A+","A","B","C","D","E","F"]
percentage=("90%","80%","70%","60%","50%","40%","30%")
for i in range(7):
if per.upper()==grades[i]:
return percentage[i]
d="a"
print(percentage(d))
What happens is that i counts up to the number seven, and if the value of i in grades (let's say i is 5, then that would be grades[5] which would be an "E") then the function returns the value of i in the percentage tuple. In my case, the interpreter outputs 80%
Logically, your way of going about it (by actually dealing with every grade possible in separate if statements) would work too, however like I said your code would be longer and chances are you'd make a few typos along the way that you'd have to edit. Of course, my code has a few problems too, like what if the user enters a grade which I don't have in the tuple. This is easily fixable though as you would just need to tell the interpreter what to do if that happens.
A bit brief I know, but I hope this helps
You could do something like this
user_input = int(input("percentage: ")
if user_input < 0 and user_input > 10:
print('F")
And then you can just duplicate the code and change the numbers and the return grade
Hope it helps :)

Is there a way to go back and edit the information the user entered?

I have a simple code written in Python 2.7 that will ask users for certain information, and it exports the information to a .csv file. Once the user inputs the data, is there a way for them to go back and edit what they entered after pressing enter? Here is what i have so far:
def writer():
import csv
with open('Work_Order_Log.csv', 'a') as f:
w=csv. writer(f, quoting=csv.QUOTE_ALL)
while (1):
Correct=True
Employee=True
WorkOrder=True
Item=True
Qty=True
Process=True
Date=True
Time=True
while Correct:
Correct=False
Employee=False
WorkOrder=False
Item=False
Qty=False
Process=False
Date=False
Time=False
Employee=raw_input("1. Enter Your Name:")
WorkOrder=raw_input("2. Enter The Work Order Number:")
PartNumber=raw_input("3. Enter The Item Number:")
Qty=raw_input("4. Enter Quantity:")
Process=raw_input("5. Enter Process:")
Date=raw_input("6. Enter Date(mm/dd):")
Time=raw_input("7. Total Time(hh:mm):")
needToCorrect=raw_input("Is the last Entry Correct? (If so, type 'y') If not enter the Number of the Field that is incorrect:")
if needToCorrect=="1":
Employee=True
elif needToCorrect=="2":
WorkOrder=True
elif needToCorrect=="3":
Item=True
elif needToCorrect=="4":
Qty=True
elif needToCorrect=="5":
Process=True
elif needToCorrect=="6":
Date=True
elif needToCorrect=="7":
Time=True
w.writerow([Employee,WorkOrder,Item,Process,Qty,Date,Time,Correct])
writer()
After testing the code, I have found that when I enter the number of the incorrect field for correction, it shows in the .csv file that it was incorrect, but still makes me go through the entire loop to fix the errors. Why is this?
You can put all of your input into a while block:
while (1):
Correct = True
while Correct:
Correct = False
Employee=raw_input("Enter Your Name:")
...
needToCorrect=raw_input("Is the last Entry Correct?(y/n):")
if needToCorrect == "n":
Correct = True
w.writerow([Employee,WorkOrder,PartNumber,Process,Qty,Date,Time,Correct])
Then if a user notices something is incorrect, an "n" will prompt the user to return and retype the fields. If you want only to correct certain fields, a similar, more complicated, method would work fine.