Giving users a certain amount of tries until program exits - arrays

I'm creating a method where the user puts in a "PIN" number to access different methods.. Yes it's an ATM..
I'm trying to figure out how to make it so that the user gets a specific amount of tries until the program exit's..
After a bunch of research I haven't very well found anything useful.. The only thing I've found is to use .to_s.split(//) in order to add the number of the try into an empty array. Which doesn't make sense to me because why would you make an integer into a string..?
So my question is, how do you make it so that users only have a certain amount of tries, 3, until they get kicked out of the program?
Main source:
#!/usr/bin/env ruby
################
#ATM Rewrite
#
#Creator Lost Bam Not completed yet.
#
#11/19/15
##################
require_relative 'checking.rb'
require_relative 'savings.rb'
require_relative 'exit.rb'
require_relative 'loan.rb'
require_relative 'transfer.rb'
require_relative 'redirect.rb'
class ATM
attr_accessor :name, :checking_account, :savings_account, :pin_number, :transfer, :loan
def initialize( name, checking_account, savings_account )
#name = name
#checking_account = checking_account
#savings_account = savings_account
#pin_number = pin_number
end
end
##############
def pin
x = []
puts "Enter PIN Number:"
input = gets.chomp.to_i
if input == 1234
menu
else
x += 1.to_s.split(//) #<= This is what I found to convert integer to Array
puts "Invalid PIN, try again:"
input = gets.chomp
if x == 3
bad_pin
end
end
end
############
def menu #add #{name} on line 41
puts <<-END.gsub(/^\s*>/, ' ')
>
>Welcome thank you for choosing Bank of Bam.
>You may choose from the list below of what you would like to do
>For checking inquiries press '1'
>For savings account information press '2'
>To transfer funds press '3'
>To either apply for a loan, or get information on a loan press '4'
>To exit the system press '5'
>
END
input = gets.chomp
case input.to_i
when 1
checking_information
when 2
savings_information
when 3
transfer_funds
when 4
loan_info
when 5
exit_screen
else
puts "Invalid option please try again"
menu
end
end
def bad_pin
abort('Invalid PIN exiting sytem..')
exit
end
pin
Tried something new:
def pin
x = 3
puts "Enter PIN(#{x} attempts left):"
pin_num = gets.chomp
case pin_num.to_i
when 1234
menu
else
puts "Invalid PIN"
x -=1
return pin
if x == 0
bad_pin
end
end
end
It doesn't increment the number down it just keeps saying 3 tries left:
Enter PIN(3 attempts left):
4567
Invalid PIN
Enter PIN(3 attempts left):
45345
Invalid PIN
Enter PIN(3 attempts left):
6456
Invalid PIN
Enter PIN(3 attempts left):
4564
Invalid PIN

Your problem is that every time you recall the method the value of x resets again. You need to have a loop inside the pin method that'll keep track of attempts.
def pin
x = 3
while (x > 0) do
puts "Enter PIN(#{x} attempts left):"
pin_num = gets.chomp
case pin_num.to_i
when 1234
menu
else
puts "Invalid PIN"
x -=1
puts "no tries left" if x == 0
break if x == 0
end
end
end
Stay in the method. Recalling the method starts you back at three attempts.

Related

Skip one iteration and adding conditions Python (Basic Question)

I have been reading a text file a object and create a list with the contents.
textfile:
Activity Time Location
Football 8-9 Pitch
Basketball 9-10 Gym
Lunch 11-12 Home
Read 13-14 Library
Swim 14-15 Pool
openTime = 6
closeTime = 15
come = int(input('When do you want to come?'))
leave = int(input('When do you want to leave?'))
# endtime_of_activity and startTimeofactivity is equal to the startingtime
# of each activity and the end time of each activity in the textfile
# (taken from a list that I have been splitting).
for i in range(len(my_list)):
item = my_list[i]
if (i == 1):
continue
if closeTime <= come <= endtime_of_activity and startTimeofactivity < leave <= closeTime:
print(item.activities)
My question: As you can read in the textfile there are some activities appering on different times. For example football between 8 and 9. With the code I want to be able to skip the second element (basketball) as the code is doing, however, I want the if statement under "continue" to work. If i type that im coming 8 and leaving at 12 I want all the activities (excluding the second one) to show. This works for me when I'm doing a regular for-loop without skiping the second activity, like when im just writing: for i in my_list, then adding on the condition, but when Im doing the code above it shows me all the activites (except basketball) independeltly of when I chose to come and leave. What have I missed? How could I write the code better?
If you want to skip a certain activity, simply test if the activitiy to be printed is the same and skip it if it is:
with open("f.txt","w") as f:
f.write(("Activity Time Location\nFootball 8-9 "
"Pitch\nBasketball 9-10 Gym\nLunch 11-12"
" Home\nRead 13-14 Library\nSwim 14-15"))
data = []
with open("f.txt") as f:
for line in f:
act, time, what = (line.strip().split(" ") + ["","",""])[:3]
if data:
try:
time=list(map(int, time.split("-")))
except ValueError:
continue # invalid time: skip row
data.append([act,time,what])
header,*data = data
openTime = 6
closeTime = 15
come = 9
leave = 12
skip=set(["Basketball"])
fmt = "{:<15}"*len(header)
print(fmt.format(*header))
for act,(start,stop),what in data:
if act in skip:
continue
if start >= come and stop <= leave and openTime <= come and closeTime >= leave:
print(fmt.format(act, f"{start}-{stop}", what))
Output:
Activity Time Location
Football 8-9 Pitch
Lunch 11-12 Home

how can i format the while loop syntax?

I'm a beginner python learner and I wrote the following code asking a user to enter an account pin:
while True:
print ('Please enter your pin.')
pin = input()
if pin =='2356':
print('Access granted')
break
Now... if I only want to allow the user to enter an incorrect pin 5 times before 'freezing their account', how might I do that? Am I even using the right type of loop?
Thanks!
Yes you are almost there. You can count how many times the user has input an incorrect pin by incrementing a value like the following
incorrect_tries = 0
while incorrect_tries <= 5:
print ('Please enter your pin.')
pin = input()
if pin =='2356':
print('Access granted')
break
else
incorrect_tries +=1

Python looping with try and except

I am trying to write a program that reads numbers input by the user until the user types done. If the user types a non-number other than "done," I want to return an error message like "please enter a number number. When the user types "done", I want to calculate the total of the numbers, the number count and the average. I have tried to create a while loop with try and except to catch the non-numeric error other than done. That is part of the trick, a string entry is an error unless the string is "done." Here is the beginning of my code without any attempt to create a file that can be totaled, counted and maxed.
bank = 0
number = 0
while True:
try:
number = int(raw_input("Enter an integer ( such as 49 or 3 or 16) \n"))
bank = bank + number
print 'You entered--- ', number, 'Your running total is ', bank
except:
if number == 'done':
print 'Done'
else:
if number == 'done':
print 'Done'
else:
print 'Your entry was non-numberic. Please enter a number.'
bank = number + bank
When I run this and enter "done" I get the "else:" response and a new input line. I do not get the "Done" print from if number == "done"
Answer written in python 3
The exception used is ValueError because the compiler catches this error as a result of the conversion done in line 7 so i just added the continue in line 19 to make it skip the error and go back to the start.
bank = 0
count = 0
while True:
try:
number = input('enter an integer:\n')
if number != 'done':
bank += int(number)
print('you entered -- ', number, 'your total is ', bank)
count += 1
elif number == 'done':
print('Done')
print('you entered %d numbers' % count)
print('Your total is %s' % bank)
average = bank/count
print('Your average is %.02f' % average)
break
except ValueError:
print('oops!! that was not an integer')
continue

Displaying full array in Liberty BASIC

Going through a tutorial but I cannot figure out how to do this. It wants me to have the program display all 10 names previously entered after the quit sub. I've experimented with some stuff but cannot figure out how to do this.
'ARRAYS.BAS
'List handling with arrays
dim names$(10) 'set up our array to contain 10 items
[askForName] 'ask for a name
input "Please give me your name ?"; yourName$
if yourName$ = "" then print "No name entered." : goto [quit]
index = 0
[insertLoop]
'check to see if index points to an unused item in the array
if names$(index) = "" then names$(index) = yourName$ : goto [nameAdded]
index = index + 1 'add 1 to index
if index < 10 then [insertLoop] 'loop back until we have counted to 10
'There weren't any available slots, inform user
print "All ten name slots already used!"
goto [quit]
[nameAdded] 'Notify the name add was successful
print yourName$; " has been added to the list."
goto [askForName]
[quit]
end
Insert this code between [quit] and end:
for I = 0 TO 10
print names$(I)
next I
That'll work ;)

Create Loop So Whole Task Repeats

import sgenrand
# program greeting
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
#print("Enter coins that add up to 81 cents, one per line.")
total = 0
#prompt the user to start entering coin values that add up to 81
while True:
final_coin= sgenrand.randint(1,99)
print ("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
total = total + user_input
while total != final_coin:
user_input = int(input("Enter next coin:"))
total = total + user_input
if user_input == input(" "):
break
if total > final_coin:
print("Sorry - total amount exceeds", (final_coin))
if total < final_coin:
print("Sorry - you only entered",(total))
if total== final_coin:
print("correct")
goagain= input("Try again (y/n)?:")
if goagain == "y":
if goagain == "n":
print("Thanks for playing ... goodbye!" )
I've been trying to create this loop, so it can repeat the whole program at the end when the user accepts/ if he accepts to do it again at the end.
I know you have to have a while statement around your whole program, but with my while true statement at the top, it only repeats the first part of my program and not the whole thing.
Well one thing you should be careful of is that you do not set the
total = 0
at the start of each loop. So when the user plays the game again. He will continue using his previous total. You should move total = 0 to the start of the loop
while True:
total = 0
Additionally, you need to deindent you first
while True
statement as it does not align properly with the rest of your code.
Finally, you need to allow the user to exit the while loop after he selects No for trying again.
if goagain == "n":
print("Thanks for playing ... goodbye!" )
break
This can be done by applying a break statement.

Resources