How i can do simple counter? - python

How can I make a "counter", and after this counter reaches for example 3, I had the function executed.
When I call the function "this", 3 and more times, "if this >= 3:" don't work, and I'm not understand why does this happen.
I already tried to write it, I asked more knowledgeable people, but I haven't found a solution.
Code which i write:
# question
def get_doing():
return input('What u gonna do now, ' + name + '? ')
# doings
def doings():
do = get_doing()
this = 0
if do == 'Anything':
print('Good')
else:
print('Don\'t write, pls.')
this += 1 # Here is a problem
if this >= 3:
print('If u keep it up, you\'re going to get in trouble.')
while True:
doings()

The counter needs to exist outside the function, so that its value is remembered between calls. For example,
def doings(c):
do = get_doing()
if do == "Anything":
print("Good")
else:
print("Don't write, pls.")
c += 1
if c >= 3:
print("If you keep it up, you're going to get in trouble")
return c
c = 0
while True:
c = doings(c)

Related

Mathematic questions in python

Looking on for some guidance on how to write a python code
that executes the following:
The program will ask for math problems to solve.
The program will asks for the number of problems.
And asks for how many attempts for each problem.
For example:
Enter amount of programs: 4
Enter amount of attempts: 5
what is: 4x3 =?
Your answer: 16
and so goes on to another attempt if wrong if correct moves onto another problem, just like before and exits when attempts or problems are finished.
I have this code but I want to it only do multiplication ONLY and would like to know how to integrate how to put additional code to limit how many time one can solve the question and how many questions it asks
import random
def display_separator():
print("-" * 24)
def get_user_input():
user_input = int(input("Enter your choice: "))
while user_input > 5 or user_input <= 0:
print("Invalid menu option.")
user_input = int(input("Please try again: "))
else:
return user_input
def get_user_solution(problem):
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
return result
def check_solution(user_solution, solution, count):
if user_solution == solution:
count = count + 1
print("Correct.")
return count
else:
print("Incorrect.")
return count
def menu_option(index, count):
number_one = random.randrange(1, 21)
number_two = random.randrange(1, 21)
problem = str(number_one) + " + " + str(number_two)
solution = number_one + number_two
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
def display_result(total, correct):
if total > 0:
result = correct / total
percentage = round((result * 100), 2)
if total == 0:
percentage = 0
print("You answered", total, "questions with", correct, "correct.")
print("Your score is ", percentage, "%. Thank you.", sep = "")
def main():
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
As far as making sure you're only allowing multiplication problems, the following function should work.
def valid_equation(user_input):
valid = True
for char in user_input:
if not(char.isnumeric() or char == "*"):
valid = False
return valid
Then after each user_input you can run this function and it will return True if the only things in the users string are numbers and the * sign and False otherwise. Then you just need to check the return value with a if statement that tells the user that their input is invalid if it returns False. You can add more "or" operations to the if statement if you want to allow other things. Like if you want to allow spaces (or char == " ").
As far as limiting the number of times a user can try to answer, and limiting the number of questions asked, you just need to store the values the user enters when you ask them these numbers. From there you can do nested while loops for the main game.
i = 0
user_failed = False
while ((i < number_of_questions) and (user_failed == False)):
j = 0
while ((j < number_of_attempts) and (user_correct == False)):
#Insert question asking code here
#In this case if the user is correct it would make user_correct = True.
j += 1
if j == number_of_attempts:
user_failed = True
i += 1
So in this situation, the outer while loop will iterate until all of the questions have been asked, or the user has failed the game. The inner loop will iterate until the user has used up all of their attempts for the question, or the user has passed the question. If the loop exits because the user used up all of their attempts, the for loop will trigger making the user lose and causing the outer loop to stop executing. If it does not it will add one to i, saying that another question has been asked, and continue.
These are just some ideas on how to solve the kinds of problems you're asking about. I'll leave the decision on how exactly to implement something like this into your code, or if you decide to change parts of your code to better facilitate systems like this up to you. Hope this helps and have a great one!

How to put a choice to try again to repeat the loop?

So after finishing the code, I would like to have an option where the user would like to try again by typing Y/n or N/n. How do I make it?
a=int(input('enter value of n: '))
i = 1
sum=0
while a < 1 or a > 300:
print(a, 'is not in the range 1-300')
exit()
for a in range(1,a+1):
print (a, end = ' ')
while i<=a:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print('\nsum of all multiples of 3 and 5 is:',sum)
repeat=str(input('Would you like to try again? Y/N?'))
Here's a simple way to do it (keeping your code structure) without any functions or jargon (for beginners :]):
from sys import exit # Just something to exit your code
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
exit()
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Note that you don't need the exit() when checking if n is within 1 - 300, you could also just use break.
EDIT (WITH BREAK)
Program without from sys import exit below:
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
break # This will mean that "Thank you for running me!" gets printed even if your input is wrong
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Hope this helped!

How to exit while loop

I don't understand why I cannot go out from simple loop.
Here is the code:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
elif b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
Thanks for your help.
This should solve your problem:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
if b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
the following condition
if b == '0':
a = 0
should be in the same scope as the if b: condition.
You cant break out of the loop because. actually, there is nobreak. You need to putbreak` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.
Also, you could break out assigning a = 0 instead of the break.

My while loop never reaches the conditional stament and keeps looping

The assignment was to make a guessing game where the parameter is the answer. At the end if the person gets it right, it prints a congratulatory statement and returns the number of tries it took, if they type in quit, it displays the answer and tries == -1. other than that, it keeps looping until they get the answer correct.
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1
When i run it, no matter what i put in it just keeps asking me for my guess.
Since you called your variable num so I'm guessing it's a integer, you were checking equality between an integer and a string so it's never True. Try changing the num to str(num) when comparing, so:
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1
Is the code properly indented?
The body of the function you are defining is determined by the level of indentation.
In the example you pastes, as the line right after the def has less indentation, the body of the function is 'empty'.
Indenting code is important in python
Additionally, for assigning one value to a variable you have to use a single '=', so the:
tries == -1
should be
tries = -1
if you want to assign the -1 value to that variable.

How to get python to go back to start of loop and not use random?

I'm a bit new to python and was giving myself a task, I wanted a number guessing game that gets you to guess four numbers and the program will keep telling you how many numbers you guess right till you guess the full list of numbers.
running = True
import random
def compareLists(a, b):
return list(set(a) & set(b))
def start():
rNums = random.sample(range(10), 4)
gNums = []
print("Get ready to guess 4 numbers!")
for i in range(0, 4):
x = int(input("Guess: "))
gNums.append(x)
print("You guessed: ", gNums)
comparison = len(compareLists(rNums, gNums))
while gNums and rNums:
if gNums != rNums:
print("You guessed " + str(comparison) + " numbers right, keep guessing!")
break
elif gNums == rNums:
print("What amazing luck!")
while running:
start()
The problem is that when I use a break a new list of 4 numbers is created, I want python to just go back to the start of the loop and not make a whole new list!
You want to use continue. Try it with a toy example:
i = 0;
while i < 10:
i += 1
if i % 2 == 0:
continue
print i
Output:
1
3
5
7
9
You can put the
rNums = random.sample(range(10), 4)
outside the loop and pass rNums to start. This way you will have the same four numbers in the list. Hope this helps
For the sake of minimizing the amount of loops going on in your code, I would probably first pop your random numbers in a dictionary.
Something like this (probably more efficient way of doing this...but it's the first thing that popped in my head):
from collections import Counter
d = Counter(random.sample(range(10), 4))
Start your while loop, and keep asking the user to guess. Every time they make a right guess, just perform this operation:
d.pop(correctly_guessed_num)
Once your dictionary is empty, you are done and you break the loop.
EDIT adding my quick stab at the implementation. Not fully thought through, might be some edge cases that break this...but this is the overall idea. Hope it helps.
from collections import Counter
import random
d = Counter(random.sample(range(1, 10), 4))
size = len(d) - 1
while True:
x = int(input("Guess: "))
if size == 0:
print("you guessed them all, way to go")
break
if x not in d:
print("keep going buddy")
continue
else:
d.pop(x)
size -= 1
print("A right guess")

Categories

Resources