Im trying to make a square root function in python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I know there are probably a ton of these but the ones I have looked at arent quite my question. I am trying to make a function where you It asks you "What would you like to square" and then I have raw input for them to type something in. How can I make it so I can just type in any number and it will square it for me. In these circumstances I can not use the ** thing.
My exact code. Its nothing special, very basic.
def square():
print ("What would you like to square?")
raw_input("> ")
square()

You want to first cast the value from the user input to an actual number (raw_input returns a string), and then take the square root of that:
import math
def square():
print ('What would you like to square?')
user_input = raw_input('> ')
try:
number = float(user_input)
except ValueError:
print('You did not input a number!')
else:
print(math.sqrt(number))
square()

math.sqrt is the function you are looking for.

You need to set the return value of raw_input to a variable. The variable that raw_input returns is a string. The sqrt function takes a number as an input, so you need to cast your variable to be a float.
Here's an example:
def square():
print("What would you like to square?")
x_str = raw_input("> ")
x_float = float(x_str)
sqrt_x = math.sqrt(x_float)
print(sqrt_x)
This function will prompt the user to input a number to calculate the square root of, and then print out the square root of that number.

Related

Unable to print a sentence in python 3.7 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have created a function named user_choice() using Jupyter Notebook. This function is expecting an valid integer input from the user and prints the same. If a user any input other than integer then it should display an error message like " Sorry that is not a digit!" and it will again ask the user to enter valid input.
Below is my code for the function user_choice()
def user_choice():
choice = "WRONG"
while choice.isdigit() == False:
choice = input("Enter a digit(0-10): ")
if choice.isdigit == False:
print("Sorry that is not a digit!")
return(int(choice))
On calling the above function and entering non integer value, It is not displaying the message "Sorry that is not a digit!"
Enter a digit(0-10): ten
Enter a digit(0-10):
Looks like you just forget brackets after .isdigit method in if statement.
You need to use recursive call
def user_choice(choice="WRONG"):
if choice.isdigit() == False:
choice = raw_input("Enter a digit(0-10): ") #use input for higher python version, mine is 2.7 hence used raw_input
if choice.isdigit() == False:
print("Sorry that is not a digit!")
user_choice(choice)
else:
print("Captured:"+choice)
return(int(choice))
A shorter version:
def user_choice(choice="WRONG"):
if choice.isdigit() == False:
choice = raw_input("Input must be a digit(0-10): ") #use input for higher python version, mine is 2.7 hence used raw_input
user_choice(choice)
else:
print("Captured:"+choice)
return(int(choice))

How do I make the program repeat the question if the answer is not an integer?

I'm relatively new to program and I'm creating a credit calculator program for assignment. Now, in order to validate the inputs, I was asked to include a function in the program that will only allow integers for the user to input. If the input is a letter, they should get an error, asking them to try again. Now the problem with my program is that it will move on to the next question after asking the user to try again. How can I make sure the program asks the same question again after the wrong value is entered until the user inputs the right type of input?
passCR = input("Enter your pass credits")
try:
passCR = int(passCR)
except ValueError:
print("Not an integer! Try again.")
This will help:
while True:
passCR = input("Enter your pass credits")
if passCR.isdigit():
passCR = int(passCR)
break
else:
print("Not an integer Value")

Call function at any time on input, python 3.x [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
If you made a function like this:
def show():
print(something)
How would you make it so that, on any input, if the user typed a specific thing, this would be called? I want multiple functions like this to be able to be called whenever the user wants. Would I just have to have it as an option every time I ask for an input?
EDIT: sorry, this wasn't very clear. Say I have a variable in a game, like money. When I ask for an input as the game goes along, the inputs being about unrelated things, I want the user to be able to type eg. gold and the show() function will activate. Then the input will go on as usual. Would I be able to do this without just have it as an option for each input, eg.
variable = input("type something")
if variable == "gold":
do stuff
elif variable == other things
do other things
Do you mean something like this:
def thing1(): # Random command
print('stuff')
def thing2(): # Random command
print('More stuff')
def check(command):
'''Checks if the users command is valid else it does a default command'''
if command == 'thing1':
thing1()
elif command == 'thing2':
thing2()
else:
default_thing()
while True: # Loop going on forever
userinput = input('') # Lets the user input their command
check(userinput)
you could put all your functions in a dictionary: {"<some user input>":func_to_call} and see if it matches any
something like:
def gold():
print("gold")
input_options = {"gold":gold}
variable = input("type something:")
if variable in input_options:
input_options[variable]()

Why this while loop just keeps going instead of stopping? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
When I press "y" in the first question the loop just keeps going instead of stopping.
Done = True
while Done:
quit = str(raw_input ("Do you want to quit? "))
if quit == 'y' :
Done=False;
attack = str(raw_input("Does your elf attack the dragon? "))
if attack=='y':
print ("Bad choice, you died.")
done=False;
print "Loop stopped"
I am using Python 2.7.
You may want to use a break, this is used to stop a loop:
while True:
quit = str(raw_input ("Do you want to quit? "))
if quit == 'y' :
break # Add this
...
Quoting Python docs:
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
Edit:
You could try using an infinite loop (while True) and when you want to exit it, just check for a condition and use a break statement.
Python is case-sensitive. You need to make sure Done is always capitalized or not:
>>> Done = True
>>> while Done:
quit = str(raw_input ("Do you want to quit? "))
if quit == 'y' :
Done = False
attack = str(raw_input("Does your elf attack the dragon? "))
if attack=='y':
print("Bad choice, you died.")
Done = False
print("Loop stopped")
As Makoto has pointed out, in Python 2.x, the parentheses in the print statements above are a grouping mechanism. But in Python 3.x, print constitutes a function and requires parentheses. The above code will work in both versions of Python.

Problems simulating a dice in Python

I'm new to python and I'm trying to create a simple program to allow the user to choose to use an 8, 12 or 24 sided dice and then display the result from rolling it.
This is my code but I am unsure why when I enter whether I wish to roll again it produces an error.
import random
def dice4():
min=1
max=4
print random.randint(min, max);
return;
def dice6():
min=1
max=6
print random.randint(min, max);
return;
def dice12():
min=1
max=12
print random.randint(min, max);
return;
roll = "yes"
y = 1
while roll == "yes" or roll == "y":
x = input("What dice do you want to use? 4/6/12?");
if x ==8:
dice4();
elif x==12:
dice6();
elif x==16:
dice12();
else:
print "You have not entered a valid dice number";
roll = input("Do you want to roll again? y/n");
print "Thanks for rolling!";
input("Press <Enter> to quit");
Thanks for any help, I realise it is probably a trivial error.
I am unsure why when I enter whether I wish to roll again it produces an error.
So the problem is in that part of the code. Let's look at it:
roll = input("Do you want to roll again? y/n");
You're using the input function. That will try to evaluate whatever you type as a Python expression.
So, if you type yes, it will try to find the value of yes, and raise a NameError. The same for n or no.
If you type y, the same thing should happen… except because you happen to have an extraneous variable named y lying around, it will actually find a value, 1. So, when you check that later, in while roll == "yes" or roll == "y":, obviously 1 is not equal to either of those strings, so it will just exit.
The only thing you could type that would work is "y" or "yes" (or the same with single quotes). Which obviously you don't want your users to have to type.
The solution is to use raw_input instead of input, which just gives you the input as a string, instead of trying to evaluate it.
roll = raw_input("Do you want to roll again? y/n");
This is one reason using input is usually a bad idea. Even in the earlier case, where you want an integer, the errors for typos are going to be ugly.
For an even better reason, see what happens when you type __import__('os').system('dir C:\\') (substitute ls / if you're on Unix instead of Windows), and imagine how much mischief your user could cause with other inputs.
So, I would recommend always using raw_input. If you want to convert the input to an integer, pass it to int. If you want to treat it as a literal value of any type, use ast.literal_eval. If you really want to evaluate it as arbitrary Python code, use eval (which is no safer than input, but at least it's more explicit).
Let me just add other problems with your code. You overwrite the builtins minand max in your functions and you use semicolons which are not needed. You use empty return statements.
Then you repeat too much code with dice4, dice6 and dice12. You should use one function with a parameter. Now you will be able to throw a lot of different dice.
def dice(value):
print random.randint(1, value)
dice(4)
dice(6)
dice(8)

Categories