Asking for user input in print function - Python 2.7 - python

Sorry if this seems like a bit of a dumb question but I’m a bit confused about a Python 2 exercise I am trying to complete.
The exercise asks to write a code that will find the factorial of a number.
I have written a function that does this but I am confused about the pre set print function that has asks for user input as I’ve only seen this done as a separate thing. Could anyone help me figure out how to make this work please as the exercise asks for the print function to not be deleted.
Thank you in advance!
def FirstFactorial(num):
# code goes here
fact = 1
while num > 0:
fact *= num
num -= 1
return fact
x = raw_input("enter a number: ")
result = FirstFactorial(x)
# keep this function call here
print FirstFactorial(raw_input())

You have to print result not print FirstFactorial(raw_input())
The way it is set up now the program will work for the first input, but it will never print it out so you never see result.
Then it will look for a second input from your second call to raw_input(), but the user will not be notified that the program wants a second input. The second output of FirstFactorial() will be correctly printed.

Related

How to make a Dungeons and Dragons-esque skill check in Python?

I am trying to make a small text-based adventure game in Python IDLE, but I am running into some issues with having the game give a different response if the player rolls above or below the DC of a DND style preception check. I am very new to this so it's probably an easy fix. Here's the code.
I have no idea how to input the code into the question correctly so here is a picture.
BTW I did import random at the beginning of the code its just too far back to include in the screencap.
Your problem is you are not specifying what numbers the random module to choose from, in the line if random.randint > 10:. To fix this, put the numbers you want it to choose between. For example, if you want it to choose a random number between 1 and 20, your line would become if random.randint(1,20) > 10:.
You will also want to do this for the other line, which reads if random.randint < 10:.
welcome to SO,
Please read the minimal reproducible example guide posted in the comments by D.L. First thing I would do is to post the actual code, because if the link expires, then others viewing this post with a similar issue cannot figure out what was the given example, and how it was solved.
With logistics out of the way, to fix the error you are specifically receiving is to put what is rolled in a variable.
Here are a few things I would change to make your code clear
# Some string that receives yes or no
room_2_input = ("...")
# if condition is yes
if room_2_input == 'yes':
# Put it in a variable
roll = random.randint(1,20)
# You do not have to format a string this way, but I think it makes it easier
print('You rolled {}'.format(roll)
# Put this condition within the first if, because you don't
# need to execute it if they do not choose to roll
# Neither of your original condition has inclusivity, so if 10 is rolled,
# your program will do nothing, because neither condition would be met
if roll >= 10:
'''do stuff'''
# I would only include elif < 10 if you are specifically looking for > 2
# outcomes, but your outcome appears to be binary, either above or below 10
else:
'''do stuff'''
The reason you would not do a random.randint(1,20) > 10: check in your second if statement is because you would be executing a different roll than your first one.

Can't call a subroutine when within a subroutine, if and for loop. Have I done something wrong here?

So here's my code.
def bubblesort(list):
global step
global oldlist
print("""
ORIGINAL LIST""")
print(list)
for i in range(len(list)):
for j in range(len(list)-1):
if float(list[j])>float(list[j+1]):
list[j], list[j+1] = list[j+1], list[j]
if oldlist==list:
**end(list)**
else:
oldlist=list
step=step+1
print("""
STEP""",step)
print(list)
end(list)
def end(list):
global step
step=step+1
print("""
STEP""",step)
print(list)
step=0
oldlist=[]
list=[]
number=int(input("How many numbers do you want to input to sort? : "))
for i in range(1,number+1):
value=float(input("INPUT NUMBER : "))
list.append(value)
bubblesort(list)
The issue is the bit of code which I have is "end(list)" bare in mind I've included the ** to make it easier to see on here it's not actually in the code. It simply won't call the subroutine when I ask it to. I know it definitely runs through the if since if i put a "print" or "break" in they both work it just won't jump to a sub-routine. Furthermore, the time I call that subroutine later on in the code works and does go to the subroutine. So i'm a bit lost as to what I've done wrong here. Any help? Would be much appreciated :)
There are quite a few things wrong with your code, and your question. Let's go through them:
First of all, the formatting was not great (I've suggested an edit). This might not sound like a big deal ("Hey, as long as it works...") but it's actually crucial: I work with python every day, and I had trouble understanding your code
You're talking about subroutines. In python, we usually refer to those as functions, or methods.
You're using globals variables all over the place. This might work in little toy examples like this one, but it will fall apart VERY fast
As David Buck said, list is one of the basic data structures: 1 in an instance of int and [1,2,3] is an instance of list). It's a really bad idea to override it.
I'm not sure what you're trying to do with the end() function. It seems do very little, and what it does is not related to its name...
You create an oldlist list but never really do anything with it. What is it supposed to to ?
With that in mind, here is my proposition:
def main():
# I like to put the main code in a "main" function, so that it can be at the top
# of the file. We'll call main() from the bottom of the file
# Make our program pretty, with a little branding
print("===== Number Sorter 9000 =====")
# 'numbers' is not the name of anything yet, so we can use it safely
numbers = []
# This will loop forever, unless we tell it to stop. It allows us to skip the
# part where you ask the user for a number of values: Simply enter the values
# one by one, and press enter once last time when done.
while True:
value = input(f"Number {len(numbers)+1} (leave empty to continue): ")
# Decide what to do with the value we received. If it's a number,
# add it to our list, if it's empty, stop collecting numbers
if value:
# Make sure the value is a number ()
value = float(value)
# Add the number to the list
numbers.append(value)
else:
# This will get us out of the number-asking loop
break
print("Number Sorter 9000 will now sort your numbers")
sorted_numbers = bubblesort(numbers)
print("Number Sorter 9000 has sorted your numbers:")
print(sorted_numbers)
def bubblesort(numbers):
# Here I've removed things that were not doing much.
# There are some ways to improve the algorithm itself, but I'll let you do that
for i in range(len(numbers)):
for j in range(0, len(numbers)-i-1):
if numbers[j] > numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
# We 'return' the result from the function, so that code that calls the
# bubblesort() function can use the result
return numbers
# Lastly, we call the "main" function to get everything started. Without this
# line, nothing happens: We've just explained to the computer how to do some
# stuff, but we haven't asked it to *DO* anything
main()
Well, I hope this was not too much information. I've tried to keep things simple, but feel free to ask if something is not clear

Python does't run some lines of code as it should

can someone help me with this code? It's use is to make timed input for 2 seconds and it needs to print the last line even if the user did or didn't type something in the console (for that time). When I don't type in anything, after printing "Too Slow" it asks me for the same input, so I added IF, but it doesn't really notice it. I hope that someone can help me. Thanks!
import time
from threading import Thread
i = 0
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow") #prints this if nothing is typed in (for 2 seconds)
if i == 0:
i = 1
Thread(target = check).start()
answer = input("Input something: ") #program doesn't even notice IF and asks me the second time for input
print("This should be printed instantly after printing Too Slow (when user doesn't input anything)")
The return in the check function only causes the thread to be completed, but the call to input is independent of that thread and thus not interrupted when the check function completes. See this answer for an alternative solution using the signal module.

Is there a way I can redirect a line of code to another in Python?

I know that the question is quite ambiguous, so I'll expand on my problem. I have written a short thingy over here as practice since I just started learning python and am sort of a newbie.
In my code, I ask the user how many apples they have and if they would like to eat it. If they keep saying "Y" until the amount of apples is 0 (#mention 1 in the screenshot), I want my code to redirect to the #redirect 1 part, instead of writing the entire code from #redirect 1 again. I know that I could just rewrite it, however, I can't for the next part. If there are no apples, I ask the user if they want to buy them and the amount.
Then I would like to redirect the code back to #redirect 2 so that the code plays out again. I have read previous questions and understand that a 'goto' doesn't exist as it is unstructured, however, I have no idea how else I would write my code. Sorry for the dumb question, but as I said I am new to this.
Sounds like you need function definition. Something like.
def dostuff():
print "doing stuff"
num = 0
num = 0
while true:
num =+ 1
if num == 5:
dostuff()
else:
pass
This should print doing stuff once every 5 loops

Error in looping so that a quiz's math query repeats itself

I have a piece of coding that is most basically a quiz. I had error handling so that if someone pressed a letter or anything other than a number, it would carry on with the quiz instead of letting the person attempt another question. (For example, if question 5 was 2+3 and they entered t, then it would carry on and not give them a different question for question 5).
I tried to update the coding, so it would loop:
def random_question():#defines function to get random question
count = 0#equates count to 0
for number in range (0,10):#makes the code generate the question 10 times
try:#the code makes it so the computer tries one thing and is the beggining
questionList = [random_sum,random_subtraction,random_times]#puts functions in a list to be called on
randomQuestion = random.choice(questionList)#calls on the list to generate the random questions
randomQuestion()#calls on variable
except ValueError:#if there is a value error or a type error it will notice it and try to stop it
print ("Please enter a number")#prints out the statement if there is a type error or a value error
else:
break
random_question()#calls on the function random_question
However, it comes up with a syntax error, and highlights the 'except' part next to the ValueError.
Any help as to why this is would be much appreciated.
Your except statement should have the same indention as your try statement. In your sample code it is indented an extra tab which would cause that error.
Python takes indention seriously and it is often the culprit. I'm unclear if your def line is a place holder or if this code is part of it, but if this code is part of the function definition you have other indention issues to worry about.
I'd suggest going through it carefully and making sure everything is lined up properly. The basic rule of thumb is, if something is part of something else, it is indented under it.
def something():
step 1
step 2
if (condition):
the true thing
else:
the false thing
while (something):
repeat something
this is not part of the function anymore

Categories

Resources