How to create multiple loops in python - python-2.7

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.

Related

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

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++

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

Using for loop within if statements in Python

I am really having a hard time with loop statements for python, please see below:
I want it to check the users age, so if they are over 18, it will say "old enough, if they are over 16, it will say "almost there" and if they are younger than this, it will say "sorry you're too young"
I got the following code below:
age = int(raw_input("Enter your age:"))
if age >= 18:
print "You are old enough!"
elif age >= 16:
print "Almost there"
else:
print "You're just too young"
my problem is, how do I write code the includes an if statement and a for loop that will print out all the numbers from 0 that are less than the user's inputted age?
do I say:
for age in range (0,num)
if num <= age
print ....
else:
print...
Please kindly help. I'm new at this and still learning :(
So you could construct a variable that contains a list of numbers that is smaller than the user's age. You can construct this using python's range function; something like range(age) would do this nicely.
Then you need to use a for loop to loop through all these numbers and print them to the command line. Something like for x in range(age) would be a good place to start.
Then, in the loop, you'd just need to turn x from an integer into a string using the str() function, and print it to the command line.
So as pseudo-code:
if the age is greater than 18:
print that they're old enough
else if the age is greater than 16:
print that they're nearly old enough
otherwise:
print that they're not old enough.
for each number between 0 and age:
print the number
Come back when you have some code and we can help you with any trouble you have.

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

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 :)