Best way to redisplay login prompt - python-3.x

I am writing a simple Python (shell) program that asks for input. What I am looking for is a certain length (len) of a string. If the string is NOT that minimum, I want to throw an exception and take the user back to the input prompt to try again (for only a given amount of tries, say 3).
my code is basically so far
x=input("some input prompt: ")
if len(x) < 5:
print("error message")
count=count+1 #increase counter
etc...
-- This is where I am stuck, I want the error to be thrown and then go back to my input... kind of new to Python, so help is greatly appreciated. This is going to be part of a script on a Linux box.

Loops work well for this.
You also probably want to use raw_input instead of input. The input function parses and runs the input as python. I'm guessing you are asking users for a password of sorts and not a python command to run.
Also in python there is no i++, use i += 1 for example.
With a while loop:
count = 0
while count < number_of_tries:
x=raw_input("some input prompt: ") # note raw_input
if len(x) < 5:
print("error message")
count += 1 #increase counter ### Note the different incrementor
elif len(x) >= 5:
break
if count >= number_of_tries:
# improper login
else:
# proper login
or with a for loop:
for count in range(number_of_tries):
x=raw_input("some input prompt: ") # note raw_input
if len(x) < 5:
print("error message") # Notice the for loop will
elif len(x) >= 5: # increment your count variable *for* you ;)
break
if count >= number_of_tries-1: # Note the -1, for loops create
# improper login # a number range out of range(n)from 0,n-1
else:
# proper login

You want a while loop instead of your if, so you can keep asking for another input as many times as is appropriate:
x = input("some input prompt: ")
count = 1
while len(x) < 5 and count < 3:
print("error message")
x = input("prompt again: ")
count += 1 # increase counter
# check if we have an invalid value even after asking repeatedly
if len(x) < 5:
print("Final error message")
raise RunTimeError() # or raise ValueError(), or return a sentinel value
# do other stuff with x

Related

Creating a continues loop with try | Python3

I'm trying to receive user input that has to be between 2 and 10 and then return a message if the input is in fact between 2 and 10.
What I'm struggling with:
if the user inputs something other than a number, I get a ValueError
How I'm trying to resolve it:
I use the try except finally method.
Issue I'm unable to resolve:
When the user inputs a letter, the first time around, it will bring up the try: but if the user then inputs a letter a second time, it will give an error once again.
How can I make this loop so the user can give as many wrong answers as he wants and get it to it's final destination once he inputs a value between 2 and 10?
My code so far
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
except ValueError:
print(f"That wasn\'t a number! Try again.")
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
finally:
print("Good, welcome to the dark side.")
Would appreciate the help!
Thanks.
This example works, while making minimal changes to your code:
while True:
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
break
except ValueError:
print(f"That wasn\'t a number! Try again.")
print("Good, welcome to the dark side.")
The main differences are removing the while loop from within the except and the finally portion, and using a while True loop to continue asking the question until the conditions are met that lead to the break (i.e. user enters a value between 2 and 10, inclusive). My test of this code works.

Geometric mean-algorithm without package

I have a task to write a program which for a sequence number as a result give a geometric mean. I have to write this program without any package.
The introduction of the program end, when users give a 0.
The program should report an error if the first number is 0 and if the user gives a negative number.
def sequence():
prod=1
i=-1
x=1
n = int(input("Give a number: "))
while True:
if n == 0:
break
elif i==0:
print("Error")
else:
prod=prod*n
i=i+1
result=prod**(1/i)
print(" Średnia wartośc ciągu ", result)
return i, suma
sequence()
My program doesn't return anything.
I don't want to post the solution, I'd rather point out several problems with the code. Figuring them out on your own will make you a better coder. There are several problems with your algorithm:
You'd better start with i=0
elif i==0: won't work as you expect it has to be an if i==0: under if n==0:, so that you exit the loop when you get 0 from the user and you print Error when it is the first iteration.
n = int(input("Give a number: ")) has to be within the loop, so that it gets assigned on every iteration of your algorithm.
return i, suma should be outside the while loop.

Python Collatz Infinite Loop

Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue

Option to save output printed on screen as a text file (Python)

Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break

Count iterations in a loop

New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.
import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the while loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).
Here's an example:
counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
The value printed will be the number of times the while loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.
You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:
print('The while loop ran {} times'.format(counter))
Calling the format function on a string allows you replace each instance of {} within the string with an argument.
Edit: Changed to reassignment operator

Resources