I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)
Related
On line 7 and 14 I cant figure out how to divide the variable.
import keyboard
import random
def main(Number, Start):
Number = random.randrange(1,100)
Start = False
QA = input('Press "K" key to begin')
if keyboard.is_pressed('K'):
Start = True
input('I"m thinking of a random number and I want that number divisible by two')
print(Number)
input('Please divide this by two. *IF IT IS NOT POSSIBLE RESTART GAME*\n')
if QA == int(Number) / 2:
print('.')
else:
print('.')
main(Number=' ' ,Start=' ')
What you probably want:
Pick a random number
Make user divide this number by two (?)
Do something based on whether the guess is correct
What is wrong with your code:
You are not picking a number divisible by two. The easiest way to ensure that your number is, indeed, divisible by two, is by picking a random number and then multiplying it by two: my_number = 2 * random.randrange(1, 50). Note the change in the range. Also note that the upper limit is not inclusive, which may be not what your meant here. A typical check for divisibility by N is using a modulo operator: my_number % N == 0. If you want users to actually handle odd numbers differently, you would need to write a separate branch for that.
input returns a string. In your case, QA = input('Press "K" key to begin') returns "K" IF user has actually done that or random gibberish otherwise. Then you are checking a completely unrelated state by calling keyboard.is_pressed: what you are meant to do here is to check whether the user has entered K (if QA == "K") or, if you just want to continue as soon as K is pressed, use keyboard.wait('k'). I would recommend sticking to input for now though. Note that lowercase/uppercase letters are not interchangeable in all cases and you probably do not want users to be forced into pressing Shift+k (as far as I can tell, not the case with the keyboard package).
input('I"m thinking of does not return anything. You probably want print there, possibly with f-strings to print that prompt along with your random number.
input('Please divide this by two. does not return anything, either. And you definitely want to store that somewhere or at least immediately evaluate against your expected result.
There is no logic to handle the results any differently.
Your function does not really need any arguments as it is written. Start is not doing anything, either.
Variable naming goes against most of the conventions I've seen. It is not a big problem now, but it will become one should you need help with longer and more complex code.
Amended version:
import random
import keyboard
def my_guessing_game():
my_number = random.randrange(1, 50) * 2
# game_started = False
print('Press "K" to begin')
keyboard.wait('k')
# game_started = True
print(f"I'm thinking of a number and I want you to divide that number by two. My number is {my_number}")
user_guess = input('Please divide it by two: ')
if int(user_guess) == my_number / 2:
# handle a correct guess here
print('Correct!')
pass
else:
# handle an incorrect guess here
pass
Alternatively, you can use the modulo operator % to test whether Number is divisible by 2:
if Number % 2 == 0:
print('.')
else:
print('.')
This will check whether the remainder of Number divided by 2 is equal to 0, which indicates that Number is divisible by 2.
I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function
I'm trying to make a pokémon text based journey in python.
I listed the starter pokémon in a tuple to call the number that the user typed in the input to then store the chosen starter pokémon.
It all works but when the user would type a different integer then availabe in the tuple, for example: writing 5 while there are only 3 indexs in the tuple. The program just stops when this happens.
Is there a way for me to just tell the program to not go into debugging mode when this happens; and recalling the "ChoseStarter" function instead?
Here is the code:
if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3):
ChosenPokInt = int(ChosenPok)
StarterPok = Starter[ChosenPokInt-1] #Here is the problem
Sure = f"You chose {StarterPok} are you sure? (y/n)"
YORN = input(Sure)
if(YORN == "Y" or YORN == "y"):
Congrats = f"Congratulations!! You just got a {StarterPok}!!"
WriteFast(Congrats)
print(Starter[ChosenPokInt-1])
else:
WriteFast(ERROR)
ChoseStarter()
No idea what the question is about or what logic you want to implement. See if the below code helps though. Seems like the "if condition" is buggy in your case. The following code repeatedly asks for the correct input using a while loop. Replace the while loop with an if statement if you don't want that.
starter = ["x", "y", "z"]
chosen_pok = int(input("Select a pok: "))
while not (1 < chosen_pok < 4):
print("Invalid pok. try again...")
chosen_pok = int(input("Select a pok: "))
starter_pok = starter[chosen_pok - 1]
yorn = input(f"You chose {starter_pok} are you sure? (y/n)")
if (yorn in ["Y", "y"]):
print(starter[chosen_pok - 1])
else:
print("Error")
You should just check for the len and if ChosenPokInt is in it's boundaries:
pokemon_index = ChosenPokInt - 1
if 0 <= pokemon_index < len(Starter)-1:
# everything is fine
else:
# handle the problem case
Besides that I advice you to look into pep8 :). You can find an awesome guide here: https://pep8.org
You can add a while loop before the condition that checks first if the input is in the correct range:
ChosenPok = ChoseStarter()
pokRange = [1, 2, 3]
while not (ChosenPok in pokRange):
print("Wrong input, try again")
ChosenPok = ChoseStarter()
Hello I have a problem in my code. I want to check valu of ran_dice in method main but I dont know how I can do. For example I wrote ran_dice(2) it return 2 random integers and I want to check these two integers equals or not. Can I do in main method ? How ?
Printing ran_dice(2) should do the trick.
Edit according to the comment:
a,b=ran_dice(2)
if a==b:
# code to stop
As another comment mentioned, however, the ran_dice(s) function is a little dangerous as the amount of things it returns varies. It's good practice to have a program return a consistent amount of things. You could return the values in a list, and the size of the list could vary, but at least you're always returning one list.
Here is an example, you could return the dice values in a list. So you can adjust the returned number of dice as you like, and compare the result.
import random
def ran_dice(s):
if s==1:
a=random.randint(1,6)
return [a]
elif s==2:
a=random.randint(1,6)
b=random.randint(1,6)
return [a,b]
def main():
credit=100
print('Welcome user, you have ', credit,'credits.')
number=int(input('How much do you want to gamble?: '))
while number <0 or number>100:
print('You need to give a positive integer no more than your credit.')
number=int(input('How much do you want to gamble?: '))
result = ran_dice(2)
print ("dice=", result)
firstdice = 0
for dice in result:
if firstdice == 0:
firstdice = dice
elif dice == firstdice:
print("equal")
else:
print("different")
if result[0] == result[1]:
print("equal")
main()
If the given number is less than the 2, it asks to reenter the number by using recursion.
I've first given 2 and then after recursion, I gave 3, but the output is still 2.
How to output 3?
def inexpno():
exp = int(input("Enter the Experiment n.o : ")) # Takes a exp number
if exp<=2: # Enter your completed experiment here
print("It is completed Correction for both Record and Observation\n\n")
print("Do you want to select another experiment")
we = input("")
if we == "yes" or we == "YES":
inexpno() # TO CHANGE
else:
exit()
return exp
print(inexpno())
Currently you don't save the return value from inexpno() in the recursive call on line 8. You simply need to save it as exp:
exp = inexpno()
Just change your recursive line to
return inexpno()