Programming challenge while loops and for loops - python

I have been asked to make a piece of code including a for loop and a while loop. I was asked to:
Get the user to input a number
Output the times table for that number
Starts again every time it finishes
I was able to do the for loop like so:
num= int(input ("Please enter a number."))
for x in range (1,13):
print (num,"x",x,"=",num*x)
But I cannot figure out how to make it repeat, any ideas?

Just put your code inside a while loop.
while True:
num = int(input("Please enter a number: "))
for x in range(1,13):
print("{} x {} = {}".format(num, x, num*x))

I think it would be nice for you to handle errors.
If a user decides to enter a non digit character it will throw an error.
while True:
num = input('please enter a number')
if num ==0:
break
elif not num.isdigit():
print('please enter a digit')
else:
for x in range(1, 13):
mult = int(num)
print('%d x %d = %d' %(mult, x, mult*x))

Related

Using a While loop in python when asking for something specific

Question is to
Prompt the user for a number from 1 to 100. Using a while loop, if they entered an invalid number, tell them the number entered is invalid and then prompt them again for a number from 1 to 100. If they enter a valid number - thank them for their input.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
int(input("please enter a number 1-100, inclusive: ")
else:
print("thank you for your input")
my code is incorrect. Help me fix it please?
Aren't you missing a parenthesis in the statement before else: ? Looks like it says else: is invalid due to that.
Besides the syntax error (missing ) before the line of else, your code also have logical error, you need to set the y = False when user give proper input to get out from the while loop, like :
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
value = int(input("please enter a number 1-100, inclusive: "))
if value >= 0 and value <= 100:
y = False
else:
print("thank you for your input")
Simplification and correction of your code
while True:
x = int(input("please enter a number 1-100, inclusive: "))
if 1 <= x <= 100: # range check
print("thank you for your input")
break # terminates while loop
else:
print("invalid.") # print then continue in while loop
#Krish says a really good answer about how you are missing a second bracket during the line that you prompt inside the while loop. I assume you receive a SyntaxError about it (probably listing the immediately following line--unfortunately common in software).
Solution
However, you have a much more fundamental issue with your code: you never update y so you have an infinite loop that will always think that the input is invalid.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y: # it is unnecessary to check a boolean against a condition
print("invalid.")
x = int(input("please enter a number 1-100, inclusive: ")) # missing bracket
y = x<0 or x>100 # necessary to end the loop
else:
print("thank you for your input")
Improvement
Another option is to use break to exit the loop on the spot. It can make for cleaner code with less duplication because now everything is inside the loop.
while True: # infinite loop...but not because of break
x = int(input("please enter a number 1-100, inclusive: "))
if x<0 or x>100:
print("invalid.")
else:
print("thank you for your input")
break
Advanced
For completeness I will also include a couple more advanced features. You can skip this part since you are starting out, but it may be interesting to come back to once you have become more familiar with the language.
Lambda
Helps make the code cleaner.
user_input = lambda: int(input("please enter a number 1-100, inclusive: "))
condition = lambda x: x<0 or x>100
while condition(user_input()):
print("invalid.")
else:
print("thank you for your input")
Cmd
This one is really advanced and overkill for what you are trying to accomplish. Still, it is good to know about for a later, more advanced problem that it would be appropriate for. Docs found here.
from cmd import Cmd
class ValidNumberPrompter(Cmd):
"""
This is a class for a CLI to prompt users for a valid number.
"""
prompt = "please enter a number 1-100, inclusive: "
def parseline(self, line): # normally would override precmd but this is modifying the way the line is parsed for commands later
command, args, line = super().parseline(line) # superclass behaviour
return (command, args, int(line))
def default(self, line): # don't care about commands
if line<0 or line>100:
print("invalid.")
return False
else:
print("thank you for your input")
return True
"""
Only start if module is being run at the cmdline.
If it is being imported, let the caller decide
what to do and when to run it.
"""
if __name__ = '__main__':
ValidNumberPrompter().cmdloop()

Beginner: Creating a list with divisors

I just started learning Python and am stuck with an exercise.
The program should ask the user for a number and then print out a list including all of the number's divisors.
myList = []
usernumber = int(input("Please enter a number: "))
a = int(1)
for a in range(1, usernumber):
while usernumber % a == 0:
divisor = usernumber / a
myList.append(divisor)
a += 1
print(*myList)
This seems to work for everything except 1, but I can't figure out what I have to change to make it work for an input of 1. Any ideas?
Try this:
myList = []
usernumber = int(input("Please enter a number: "))
#No need to declare a as an integer, for loop does that for you.
for a in range(1, usernumber+1):
#usernumber+1 as range() does not include upper bound.
#For each number leading up to the inputted number, if the
#remainder of division is 0, then add to myList.
if usernumber % a == 0:
myList.append(a)
print(myList)

why the if-else does not loop

I find my prog's if-else does not loop, why does this happen and how can I fix it for checking?
my prog supposed that store user's inputs which must between 10 and 100, then delete duplicated inputs.
examples: num=[11,11,22,33,44,55,66,77,88,99]
result: `[22,33,44,55,66,77,88,99]
inList=[]
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
if num >= 10 and num <= 100:
inList.append(num)
else:
num = int(input("Please enter a valid number: "))
print(inList)
I found that the if-else only did once, so when I enter invalid num for the 2nd time, the prog still brings me to the next input procedure. What happen occurs?
Please enter number 1 [10 - 100]: 1
Please enter a valid number: 1
Please enter number 2 [10 - 100]:
Additionally, may I ask how can I check the inList for duplicated num, and then remove both of the num in the list?
I'd also suggest a while loop. However the while loop should only be entered if the first prompt is erraneous:
Consider this example:
inList = []
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
while not (num >= 10 and num <= 100):
num = int(input("Please enter a valid number [10 - 100]: "))
inList.append(num)
print(inList)
However, may I suggest something else:
This code creates a list of valid inputs ["10","11"...."100"] and if the input which by default is a string is not inside that list we ask for new input. Lastly we return the int of that string. This way we make sure typing "ashashah" doesn't throw an error. Try it out:
inList = []
valid = list(map(str,range(10,101)))
for x in range(1,11):
num = input("Please enter number {} [10 - 100]: ".format(x))
while num not in valid:
num = input("Please enter a valid number [10 - 100]: ")
inList.append(int(num))
print(inList)
I'm no python expert, and I don't have an environment setup to test this, but I can see where your problem comes from.
Basically, inside your for loop you are saying
if num is valid then
add to array
else
prompt user for num
end loop
There's nothing happening with that second prompt, it's just prompt > end loop. You need to use another loop inside your for loop to get num and make sure it's valid. The following code is a stab at what should work, but as said above, not an expert and no test environment so it may have syntax errors.
for x in range(1,11):
i = int(0)
num = int(0)
while num < 10 or num > 100:
if i == 0:
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
else:
num = int(input("Please enter a valid number: "))
i += 1
inList.append(num)
print(inList)

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

How to count how many tries are used in a loop

For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value
i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.
import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$

Categories

Resources