while True: try: except ValueError: - while-loop

I want to make a function like this:
while True:
try:
x = int(input("Please enter a number 1 - 5: "))
print (x)
except ValueError:
print "Oops! That was not a valid number. Try again..."
but how can I make sure that ‘x’ only will be printed if x is between 0 – 6.

If you want to keep the exception flow, you can raise an exception when the user inputs an invalid value.
while True:
try:
x = int(input("Please enter a number 1 - 5: "))
if x < 1 or x > 5:
raise ValueError('Input not valid') # go to except block
print (x)
except ValueError:
print ("Oops! That was not a valid number. Try again...")
You can also write a loop without raising an exception:
while True:
x = int(input("Please enter a number 1 - 5: "))
if x < 1 or x > 5:
print ("Oops! That was not a valid number. Try again...")
continue # skip print
print (x)

Related

How can I use the while loop to create an endless loop of user input-->tells me if int is odd or even?

number = ''
number = int(input("Please input a number and I will tell you if it is odd or even.\n"))
while True:
if (number % 2) != 0:
print("This is an odd number.")
else:
print("This is an even number.")
#I tried this loop below
user_input = ""
while user_input != "exit":
user_input = int(input("Please input another number and I will tell you if it is odd or even.\n"))
number = user_input
This is only telling me if the first number is odd or even but not the following numbers

Simple Beginner Loop Wont Close

Practicing some stuff and I've been way beyond this simple of a concept but this loop won't close and I can't understand why.
ans = "Y"
while ans == "Y" or "y":
num = int(input("What's your number? "))
if num % 2 == 0:
print("That number is even!\n")
else:
print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))
So I declare the variable first so I can enter the loop then ask for it again on the tail side to close it out...but no matter what I enter it continues.
I'm sure it's simple like I said i'm way past this kind of thing but it won't close and I'm not sure what the issue is?
The problem lies in the 'or "y"':
You should check if ans is Y or y which is correctly expressed as 'ans == "Y" or ans == "y"'
You as well needs to specify a starting condition for ans.
ans = "y"
while ans == "Y" or ans == "y":
num = int(input("What's your number? "))
if num % 2 == 0:
print("That number is even!\n")
else:
print("That number is odd!\n")
ans = str(input("Do you have another number, Y/y or N/n? "))

nameError: name 'pivots' is not defined

Could you help me to solve the following problem,please ?
I did write a module in python . For the next module I need the following variables or values:
lastprice and lastpivotprice
What definition or script change is necessary, that this 2 variables are global variables)?
Actually if i try to call lastpivotprice outside the module i get the following error message:
nameError: name 'pivots' is not defined
Module Code: checkpivots.py
try:
df['High'].plot(label='high')
pivots =[]
dates = []
counter = 0
lastPivot = 0
Range = [0,0,0,0,0,0,0,0,0,0]
daterange = [0,0,0,0,0,0,0,0,0,0]
for i in df.index:
currentMax = max(Range , default=0)
value=round(df["High"][i],2)
Range=Range[1:9]
Range.append(value)
daterange=daterange[1:9]
daterange.append(i)
if currentMax == max(Range , default=0):
counter+=1
else:
counter = 0
if counter == 5:
lastPivot=currentMax
dateloc =Range.index(lastPivot)
lastDate = daterange[dateloc]
pivots.append(lastPivot)
dates.append(lastDate)
except Exception:
print("-")
lastpivotprice = pivots[-1]
lastprice=df.iloc[-1]['Close'] #read value in the last row in col 'close'
lastprice2 = df['Close'].values[-2] #read value in the last row minus2 in col 'close'
#print (lastprice)
# print (lastpivotprice)
# print (lastprice2)
If you want to take your variables in every module as globals, you have to set them as global variables. For example see this code below:
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print("Inside add():", c)
add()
print("In main:", c)
If you delete global from c, the c remains 0 in MAIN.

My program in Julia sees syntax error where there is none

I have a problem with this bit of code. Every time I try to run it it says that I have "Unexpected" end. For me everything is on point and I cant figure it out can someone help me find solution? Full error code and program code below.
Program:
function mbisekcji(f, a::Float64, b::Float64, delta::Float64, epsilon::Float64)
e = b-a
u = f(a)
v = f(b)
err = 0
iterator = 0
if sign(u) == sign(v)
err = 1
return err
end
while true
e = e/2
c = a+e
w = f(c)
if (norm(e) < delta) || (norm(w) < epsilon)
return w, f(w), iterator, err
end
if sign(w) == sign(u)
b = c
v = w
else
a = c
u = w
end
iterator++
end
end
Error:
LoadError: [91msyntax: unexpected "end"[39m
while loading C:\Users\username\Desktop\Study\zad1.jl, in expression starting on line 60
include_string(::String, ::String) at loading.jl:522
include_string(::Module, ::String, ::String) at Compat.jl:84
(::Atom.##112#116{String,String})() at eval.jl:109
withpath(::Atom.##112#116{String,String}, ::String) at utils.jl:30
withpath(::Function, ::String) at eval.jl:38
hideprompt(::Atom.##111#115{String,String}) at repl.jl:67
macro expansion at eval.jl:106 [inlined]
(::Atom.##110#114{Dict{String,Any}})() at task.jl:80
Also, just to make thing easier, line 60 is second end from the back. The one closing while loop.
In order to increment a variable by 1 in Julia you have to write
iterator += 1
Julia does not support ++ to increment a variable.
But, for example, you could define a macro to do almost what you want:
julia> macro ++(x)
esc(:($x += 1))
end
#++ (macro with 1 method)
julia> x = 1
1
julia> #++x
2
julia> x
2

Code or Logic to find number of char appearances in a string composed of consecutive numbers

I am struggling with this exercise where I have to find a number (y) so that when counting the times (nr) the value "1" appears in a string (x) composed of all the consecutive numbers starting from 1 to y, the following conditions are met: nr=y and nr is divisible by 10.
example:
x (string with consecutive from 1 to 12)= 123456789101112
y (the number) = 12
nr (times of "1" appearances) = 5
so i need to find the situation where nr=y and y mod 10 = 0
I've tried creating a vba sub to do this, but it takes forever and cannot seem to find a suitable result:
Sub abc2()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim i As Double
Dim y As Double
Dim nr As Double
Dim x As String
x = 1
y = 1
For i = 1 To 500001
x = x & (y + 1)
y = y + 1
nr = Len(x) - Len(Replace(x, "1", ""))
If nr = y And nr Mod 10 = 0 Then
Range("E1") = y
GoTo out
End If
Next i
out:
Range("A1") = x
Range("B1") = y
Range("C1") = nr
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
I'd really appreciate some suggestions. Maybe it can be solved in some other ingenious way.
Thank you!
Python:
x = ''
y = 0
####################################
# BRUTE FORCE, FINDS ANSWER 199990 #
####################################
#for iteration in range(100000):
# for index in range(10):
# y+=1
# x+=str(y)
# if (y == x.count('1')):
# print 'Found: ' + str(y) + ': ' + x
####################################
# More elegantly and efficiently, just track how many '1's we've added in each step
ones = 0
for iteration in range(100000):
x = ''
for index in range(10):
y += 1
x += str(y)
ones += x.count('1')
if (y == ones):
print 'Found: ' + str(y)
The commented-out solution takes about 2 minutes to execute. The second solution finishes in .46 seconds.