Im a student, and just started learning python a month back, so right now, I have only learnt the basics. My teacher had given me a question like this, and the problem is, I dont know how to rerun a program, suppose, after finding the area of a particular shape, I want it to loop back to printing the first statement.
Is there any way of doing that without re-running the program using the "F5" key?
print "1. Triangle"
print "2. Circle"
print "3. Rectangle"
shape= input("Please Select the serial number =")
if shape==1:
a=input("Base =")
b=input("Height =")
area=0.5*a*b
print area
if shape==2:
a=input("Radius =")
area=3.14*a*a
print area
if shape==3:
a=input("Width")
b=input("Length")
area=a*b
print area
If you want to restart, just use a simple while loop.
while True:
# Your lovely code
Then just put some validation at the end:
again = raw_input("Play again? ")
if again.startswith('n') or again.startswith('N'):
break
else:
continue
Related
First time using Stackoverflow.
I'm a total noob with Python so I need a little help. I'm trying to make a choice based text adventure game and in the middle of it is going to be a sandwich making simulator (don't ask how my mind works) and I need a little help.
def sandwich():
print("You see bread, meat, cheese and mayo.")
while True:
try:
print(" 1. Bread \n 2. Meat \n 3. Cheese \n 4. Mayo")
print ("Select the ingredients based on number. Which would you like to grab?")
response = set(int(input("Select ingredients: ").strip))
except ValueError:
print("Please enter an integer!")
I only have four choices to keep it simple so I can build from there. Basically I want to make the program check for user integer input and depending on that input give feedback on the sandwich that's created.
for example:
if response == "1234":
print("Wow that's an amazing sandwich")
But I want the program to be able to be smart enough to do this regardless of the order that is given. So if someone puts in "4321" instead of "1234", it can give the same result. Currently I'm using set, int, and strip on line 7 (not sure if that's good or not) so that there can't be duplicates, and if spaces is added it should strip it away. It should also give an error if an integer is not entered.
I'm thinking of using for loops with in, but I have no idea where to begin or if that's even the right path.
Any points in the right direction would be appreciated!
Is better to put the list of ingredients in a dictionary, so you can easily add or substract ingredients, and you have a relation between the number and the ingredient.
Strip is a function call, so it has to be written .strip()
Is better to not add the response directly to the set of ingredients, because you should validate it first.
You need a way to stop adding ingredients. If the user does not writes an integer, you could ask if he wants to stop adding ingredients.
sandwichIngredients = {1: "Bread", 2: "Meat", 3: "Cheese", 4: "Mayo"}
def sandwich():
chosenIngredients=set()
print("You see "+ ", ".join(sandwichIngredients.values())+".")
while True:
try:
print(*[f"{number}. {ingredient}" for number, ingredient in sandwichIngredients.items()], sep="\n")
print ("Select the ingredients based on number. Which would you like to grab?")
response=int(input("Select ingredients: ").strip()) #strip is a function call, so it has to be written .strip()
if response in chosenIngredients:
print("You already have that ingredient.")
continue
elif response not in sandwichIngredients:
print("That is not an ingredient.")
continue
else:
chosenIngredients.add(response)
if len(chosenIngredients)==len(sandwichIngredients):
print("Wow that's an amazing sandwich.")
break
except ValueError:
if input("That is not a number. Do you want to finish the sandwich? (y/n)").lower()=="y":
break
print("Please enter an integer!")
#now you can print the ingredient names by using the dictionary
print("your sandwich has the following ingredients: " + ", ".join([sandwichIngredients[i] for i in chosenIngredients]))
sandwich()
Hi please i want your help I don't know how to execute this python script or run i wrote attack() but there is no result , if any one can help and thak you so much .
and please can you check if it's coorrect ( syntax ) .
def attack():
while 1:
X = list(
map(float_input,[
"WHAT IS TARGET SHIP LENGTH IN FEET?\n",
"WHAT IS TARGET SHIP BEAM IN FEET?\n",
"WHAT IS TARGET SHIP SPEED IN KNOTS?\n",
"WHAT IS RANGE TARGET TO SUB IN YARDS?\n",
"WHAT IS ASPECT ANGLE (ANGLE ON THE TARGET BOW) IN DEGREES?\n",
"HOW MANY TORPEDOS IN A SALVO?\n",
"WHAT IS THE COVERAGE FACTOR? ( TORPEDO SPREAD + TARGET SHIP LENGTH)\n",
"WHAT IS TORPEDO SPEED IN KNOTS?\n",
"WHAT IS TORPEDO MAXIMUM RANGE IN YARDS?\n",
]))
print("YOUR ANSWERS IN ORDER WERE ")
print(' '.join(vector))
if input("ARE THEY OK? YES/NO\n")=="YES":
break
else:
print('\n'*5)
SW = list(
map(yes_no_input,[
"DO YOU WANT TRACK PROBABILITIES DISPLAYED? YES/NO\n",
"DO YOU WANT TRACK ANGLE, RUN DISTANCE, RUN TIME, EFFECTIVE LENGTH, AND TL DISPLAYED? YES/NO\n",
"DO YOU WANT HITS DISPLAYED? YES/NO\n"
]))
while 1:
print("IF YOU HAVE A VULNERABILITY VECTOR I’’LL COMPUTE EXPECTED LOSSES.")
VUL = input("INPUT THE VECTOR STARTING WITH PROB OF LOSS GIVEN ONE HIT,PROB OF LOSS GIVEN TWO HITS, ...ETC. IF AVAILABLE. OTHERWISE HIT THE RETURN.\n")
try:
VUL = 0 if not VUL else (map(float, VUL.split()) if ' ' in VUL else [float(VUL)])
SW.append(bool(VUL))
break
except:
print('Please insert floats or integers in vectors')
First: Save the file with a name (let "firstpython.py") and extension should be ".py"
Second: Open the command prompt/terminal then write ,
python "firstpython.py"
If the file has no error it will run and display the desired result else, it will show the error in the file(most probably the indentation error)
OK there are 2 things that im aware of wrong in your program, one is your syntax and another is why it wont run
Disclaimer: somethings you might already know, but I'll say it just in case
THE SYNTAX ERROR:
The syntax of a function should ideally look like this
def {function name}():
code
the indent is important as it is nessesary for python to tell which code is inside the function
your program should be edited to something like:
def attack():
while 1:
X = list(
map(float_input, [
"WHAT IS TARGET SHIP LENGTH IN FEET?\n",
"WHAT IS TARGET SHIP BEAM IN FEET?\n",
"WHAT IS TARGET SHIP SPEED IN KNOTS?\n",
"WHAT IS RANGE TARGET TO SUB IN YARDS?\n",
"WHAT IS ASPECT ANGLE (ANGLE ON THE TARGET BOW) IN DEGREES?\n",
"HOW MANY TORPEDOS IN A SALVO?\n",
"WHAT IS THE COVERAGE FACTOR? ( TORPEDO SPREAD + TARGET SHIP LENGTH)\n",
"WHAT IS TORPEDO SPEED IN KNOTS?\n",
"WHAT IS TORPEDO MAXIMUM RANGE IN YARDS?\n",
]))
print("YOUR ANSWERS IN ORDER WERE ")
print(' '.join(vector))
if input("ARE THEY OK? YES/NO\n") == "YES":
break
else:
print('\n' * 5)
SW = list(
map(yes_no_input, [
"DO YOU WANT TRACK PROBABILITIES DISPLAYED? YES/NO\n",
"DO YOU WANT TRACK ANGLE, RUN DISTANCE, RUN TIME, EFFECTIVE LENGTH, AND TL DISPLAYED? YES/NO\n",
"DO YOU WANT HITS DISPLAYED? YES/NO\n"
]))
while 1:
print("IF YOU HAVE A VULNERABILITY VECTOR I’’LL COMPUTE EXPECTED LOSSES.")
VUL = input(
"INPUT THE VECTOR STARTING WITH PROB OF LOSS GIVEN ONE HIT,PROB OF LOSS GIVEN TWO HITS, ...ETC. IF AVAILABLE. OTHERWISE HIT THE RETURN.\n")
try:
VUL = 0 if not VUL else (map(float, VUL.split()) if ' ' in VUL else [float(VUL)])
SW.append(bool(VUL))
break
except:
print('Please insert floats or integers in vectors')
That solves the indentation, the next problem is why it is not running
WHY IT IS NOT RUNNING:
Possibility number 1.
in python, a function doesnt run unless called, so at the end of your code add a
attack()
at the end of your code
Possibility number 2.
if this is just a snippet of code, and you call attack() in another portion of the code, it is because you haven't made it output anything, or return anything, so it has no way of showing that it has ran, even though it did. If the target of the code is to change global variables, then before using the variables, under your function name add the global variables you want changed. If you havent declared it globally, it might not work, so out of every scope, you have to define the variable to none at the top of the code screen. If you define variables in your function, it wont exist outside of it. I reccomend reading this article: https://www.w3schools.com/python/python_scope.asp
Thank you for reading this, hope it helped you in any way!
I've started to make a cmd-based minigame, and I wanna implement a feature, where you come across choices which you have to decide that what option will you choose. My problem however is that in my code, if you type anything other than the two options listed, than the game will just 'end' there.
print('Welcome to \'The Exchange\'.')
print('This game is all about making wise decisions with your money.')
print('At the beginning, you\'ll start out with 10$, and from here,')
print('Everything is YOUR choice! Have fun!\n')
# Starter informations. #
yourMoney = 100
# First choise part of the game. #
print('You\'ve come to your first decision of the game -')
print('Do you want to make an insurance for 5 dollars, or you just wanna skip it for now?')
firstDecision = input('Type \"make\" to make one, and \"skip\" to just skip it.\n')
if(firstDecision == "make"):
print("Fine.")
elif(firstDecision == "skip"):
print("Not fine.")
else:
print("You've misspelled it, try again!")
But I want to make it that if you type anything other than the two options, then the game would simply ask the question again, and again, until you type any of the two optins, and then, it would move on. I know, that I have to use some kind of loop, or function, and I also tried these in my code, but it haven't turned out too great. I'd greatly appreciate the help.
My suggestion with minimal change in the code.
print('Welcome to \'The Exchange\'.')
print('This game is all about making wise decisions with your money.')
print('At the beginning, you\'ll start out with 10$, and from here,')
print('Everything is YOUR choice! Have fun!\n')
# Starter informations. #
yourMoney = 100
# First choise part of the game. #
print('You\'ve come to your first decision of the game -')
print('Do you want to make an insurance for 5 dollars, or you just wanna skip it for now?')
firstDecision = input('Type \"make\" to make one, and \"skip\" to just skip it.\n')
while(firstDecision != 'make' or firstDecision != 'skip'):
if(firstDecision == "make"):
print("Fine.")
### Do here all your logics and in the end add the line below
break
elif(firstDecision == "skip"):
print("Not fine.")
### Do here all your logics and in the end add the line below
break
else:
print("You've misspelled it, try again!")
firstDecision = input('Type \"make\" to make one, and \"skip\" to just skip it.\n')
Please let me know if there were problems or this is not what you wanted.
Basically I want to record high scores in my program. I'm new to coding so need a bit of help. I will create this basic program to demonstrate what I want.
import time
name = input("Please enter your name: ")
mylist=["Man utd are the best team","I am going to be a pro typer.","Coding is really fun when you can do it."]
x=random.choice (mylist)
print ("The sentence I would like you to type is: ")
print (x)
wait = input ("Please press enter to continue, The timer will start upon hitting enter!")
start = time.time()
sentence = input("Start typing: ")
end = time.time()
overall = end - start
if sentence == (x):
print ("It took you this many seconds to complete the sentence: %s" % overall)
if overall <= 9:
print ("Nice job %s" % name)
print ("You have made it to level 2!")
How would I be able to save the time it took and if someone beats the time make that the new high score?
You're looking for a way to persist data across program executions. There are many ways to do it, but the simplest is just writing to a file.
In addition, if you want to use a database, look into SQLite3 for Python.
I am having trouble with the randint usage of exercise 43 in Learn python the hard way link to exercise. Assuming I follow Zed Shaw's code perfectly in all other parts of the program, and I have from random import randint, when I run the program and type the 3 digit passcode into the keypad, it returns a "BZZZZEDDD!". Here is that section of code:
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
Lets say in the guess = raw_input("[keypad]> ") when running the program I type in "368".
Shouldn't that be within the parameters of code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) and be TRUE for if guess ==code:? Instead it runs it as if guess != code and returns a "BZZZZEDDD!"
Your guess of 368 is within the possible range for the code, but that's not what the while loop is checking. The line
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
will generate a string of three random digits. The code could be anything between 111 and 999 (except there can be no zeroes) and you have no way of knowing exactly what it is as the program currently stands. At the bottom of the lesson, under Study Drills, the author says:
Add cheat codes to the game so you can get past the more difficult
rooms. I can do this with two words on one line.
Presumably, this code is one of the rooms he's talking about. Try adding something that will give you a hint of the code.