Text menu doesn't print properly [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The Problem has been solved. However, my account is new, so it won't let me answer the question. It seems that changing the instances of input() with raw_input() makes it work. I honestly have no clue why, but it may have something to do with the differences between 2 and 3.
I'm supposed to make a program that can calculate area and circumference. That part hasn't been so difficult.
However, the menu isn't working. The first part of the menu works just fine, but after you make a selection, it doesn't print what it's supposed to.
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if ans == "1":
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == "2":
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == "0":
print("Thanks for hanging out with me!")
quit()

After indenting properly, change if ans == "1" to str(ans) == "1" or ans == 1 and it should be fine.
This should work:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if str(ans) == "1":
diameter = input("Enter the diameter: ")
print diameter
if float(diameter) > 0.0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
....
PS: As mentionned in the comments, it works, but it is disgusting. We should only use ans == 1 or modify input to input_raw if you use python < python 3

Your code's indentation shows the span of control of each 'if', 'for', or 'while'.
You need to further indent the instructions under each major 'if' statement so that
they only get executed when that 'if' statement is selected. Otherwise, everything
that is at the leftmost indentation gets executed every time through the loop. For example, you should have something like:
if answer == '1':
....<statements that execute under condition 1>
elif answer == '2':
....<statements that execute under condition 2>
where I have emphasized the indentation with '....'.

The second if statement is not within the brackets of the first. this is true for both 1 and 2.
if ans == "1";
diameter = float(input("enter the diameter: "))
if diameter ....

for me treating ans as integer worked. What I mean by treating ans as integer is instead of writing ans=="1" ,I wrote ans==1.it print corret cvalue. Check this code:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
print ans
if ans ==1:
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == 2:
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == 0:
print("Thanks for hanging out with me!")
quit()

Related

Three Problems that I can not resolve in python [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 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value

if-else statement not running elif- or else- clauses [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
I am using Python in an attempt to create an Area Calculator (similar to the one from Code Academy). Only my else statement seems to be running:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer == "Circle" or "C" or "c" or "circle":
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer == "Triangle" or "T" or "t" or "triangle":
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
I edit texts using PyCharm and no syntax errors or errors of any other kind return. Regardless of what I respond into the answer input (whether they are integers or syntax) the code always displays line 8 [radius = float(input("Input Radius: "))]
I am sorry if this turns out to be an easy fix. I am just getting started with Python and have tried a variety of indentation and syntactical variations to no avail.
Use:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer.lower() in {"circle","c"}:
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer.lower() in {"triangle","t"}:
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
The changes are the lines with or, use in instead so checks by the set
That's what's different.
Note use lower for simplifying the length
Note use set for speed, (it's faster)
You are using the == operator incorrectly. You have to use it this way:
if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":
An easier way to do this will be to using check whether your string matches any of the items in a tuple or list. So your code will need to be modified like this:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer in ("Circle", "C", "c", "circle"):
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer in ("Triangle", "T", "t", "triangle"):
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":

My code skips the IF block and goes to ELSE

Just started python a few hours ago and stumbles across a problem.
The blow snippet shows that initially I store a userInput as 1 or 2 then execute a if block. Issue is that the code jumps straight to else (even if i type 1 in the console window).
I know Im making a simple mistake but any help will be appreciated.
using Python 3.5 === running in Visual Studio 2015 === specifically cPython
userInput = float(input("Choose 1 (calculator) or 2 (area check)\n"))
if(userInput =='1') :
shape = input("Please enter name of shape you would like to calculate the area for\n")
if(shape == 'triangle') :
base = int(input("Please enter length of BASE\n"))
height = int(input("Please enter HEIGHT\n"))
print("The area of the triangle is %f" % ((base * height)*0.5))
elif (shape == 'circle') :
radius = int(input("Please enter RADIUS\n"))
print("The Area of the circle is %f" % ((radius**2)*22/7))
elif (shape == 'square') :
length = int(input("Please Enter LENGTH\n"))
print("The area of the square is %f" % ((length**2)*4))
else :
initial1 = float(input("Please enter a number\n"))
sign1 = input("please enter either +,-,*,/ \nwhen you wish to exit please type exit\n")
initial2 = float(input("Please enter number 2\n"))
if(sign1 == '+') :
answer = float(initial1) + float(initial2)
print(answer)
elif(sign1 == '*') :
answer = float(initial1) * float(initial2)
print(answer)
elif(sign1 == '-') :
answer = float(initial1) - float(initial2)
print(answer)
elif(sign1 == '/') :
answer = float(initial1) / float(initial2)
print(answer)
PS. if [possible] could you keep the help as basic as possible as I wanna make sure i understand the basics perfectly.
Thanks for all the help!! :D
You are converting your input to float but checking for the string of the number. Change it to:
If userInput == 1.0:
Or better yet, keep it the way it is and just don't convert your user input to float in the first place. It is only necessary to convert the input to float or int if you want to do math on it. In your case you are just using it as an option, so you can keep it as a string:
userInput = input("Choose 1 (calculator) or 2 (area check)\n")
P.S. make sure to be very careful with indentation in Python. I assume your indentation is correct in your code editor, but also take care when pasting into this site. You have everything on the same level here, but some of your if blocks will need to be indented further in order for your program to work properly.

How do i have my python program restart to a certain line?

print ("Enter the object you are tyring to find.")
print ("1 = Radius")
print ("2 = Arch Length")
print ("3 = Degree")
print ("4 = Area")
x = int(input("(1,2,3,4):"))
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
if x == 2:
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
I am making a basic math program but i want it to repeat infinitely. This is not the complete code but i want to do the same thing for the rest of the "if" statements. i want it to end after each function is completed and repeat back to the first line. thanks!
Put a
while True:
at the spot you want to restart from; indent all following lines four spaces each.
At every point in which you want to restart from just after the while, add the statement:
continue
properly indented also, of course.
If you also want to offer the user a chance to end the program cleanly (e.g with yet another choice besides the 4 you're now offering), then at that spot have a conditional statement (again properly indented):
if whateverexitcondition:
break
You will need to add a way to let the user quit and break the loop but a while True will loop as long as you want.
while True:
# let user decide if they want to continue or quit
x = input("Pick a number from (1,2,3,4) or enter 'q' to quit:")
if x == "q":
print("Goodbye")
break
x = int(x)
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
elif x == 2: # use elif, x cannot be 1 and 2
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
elif x == 3:
.....
elif x == 4:
.....
If you are going to use a loop you can also verify that the user inputs only valid input using a try/except:
while True:
try:
x = int(input("(1,2,3,4):"))
except ValueError:
print("not a number")
continue

any suggestions on shortening this python code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have created a program which rolls a dice according to the amount of sides that the user enters. Here is my code:
def var():
import random
dicesides = int(input("Please enter the amount of sides you want the dice that is being thrown to have. The dice sides available are: 4, 6 and 12: "))
script(dicesides, random)
def script(dicesides, random):
if dicesides == 4:
dice4 = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice4)
elif dicesides == 6:
dice6 = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice6)
elif dicesides == 12:
dice12 = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice12)
elif dicesides != 4 or dicesides != 6 or dicesides != 12:
print("That number is invalid. Please try again.")
var()
repeat = str(input("Repeat? Simply put yes or no : "))
if repeat == "yes":
var()
else:
quit()
var()
is there a way for this to be shortened?
Thanks
You can simplify all three of those cases into one block because they all have the exact same action.
def script(dicesides, random):
if dicesides in [4,6,12]:
dice = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice)
else:
print("That number is invalid. Please try again.")
var()
Whenever you see repeated patterns in your source code, you can usually extract them into a single block.
The whole program (especially without the recursion loop between var and script and the implied bombardment of the callstack. Although your calls are in tail position, this makes no difference in python):
from random import randint
while True:
sides = int(input('Please enter the amount of sides you want the dice that is being thrown to have. The dice sides available are: 4, 6 and 12:'))
if sides in (4, 6, 12):
print('{}-sided die, score {}'.format(sides, randint(1, sides)))
else:
print('That number is invalid.')
if input('Repeat? ') != 'yes':
break
Or the code-golf version of the whole program:
(lambda f,r:f(f, r))((lambda f,r:f(f,r)if((lambda r,i:
print('{}-sided die, score {}'.format(i,r.randint(1,i)
)if i in(4, 6,12)else'That number is invalid.')) (r, (
lambda:int(input('Please enter the amount of sides yo'
'u want the dice that is being thrown to have. The di'
'ce sides available are: 4, 6 and 12: ')))()),input(''
'Repeat? '))[1]=='yes'else None),__import__('random'))

Categories

Resources