Prompting the user for an int, not a string, until they do even if it's a negative number - python-3.6

I'm writing a program and it asks the user to input a number, I need to make sure that that number is and actual number not a string. That number can be positive or negative. I've tried using .isnumerical() and .isdigit() but they won't except negative numbers.
lowest_num = input("What would you like the lowest possible number to be?")
while lowest_num.isdigit() is not True:
lowest_num = (input("Please only enter a number : ")).lower()
Thanks for the help in advance

lowest_num = int(input("What would you like the lowest possible number to be?")) should do it
Alright, try this:
number_not_entered = True
num = 0
while number_not_entered:
try:
num = int(input("enter num"))
number_not_entered = False
except ValueError:
print("please try again")
Note that catching all exceptions is generally a bad practice.

Use isnan() function from numpy library. First import numpy and then use numpy.isnan(a number)

Related

How to re-prompt user input after incorrect type of data is given and also re prompt user input if they want to?

The program is about finding factors and if the user enters a special character or an alphabet it will show an error and I wanted to ask the user to try again "Invalid input please try again" after the error shows and also after the program shows the factors I wanted the user to have the chance to find another factor again "Try again? Yes/No"
I've tried the
while True:
if input("Try Again? (Yes/No)").strip().upper() == 'No':
break
but i don't know how to make it work.
Any other solutions will do
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
try:
num = int(input("Enter a number: "))
print_factors(num)
except ValueError:
print("Sorry, I didn't understand that.");
The program works and I just wanted to put some add ons
while True:
try:
num = int(input("Enter an integer (0 to exit): "))
if num == 0:
break
print(num)
except ValueError:
print("Sorry, you must enter an integer")

Inconsistent Output in Google Colab

I have the following basic code in Google Colab:
from random import *
number = randint(1, 100)
guess = int(input("Enter a guess: "))
while guess != number:
if guess > number:
print("Enter a smaller value")
else:
print("Enter a greater value")
guess = int(input("Enter a guess: "))
print("You guessed the number")
This loop continues until we guess the number correctly. And after each guess, program directs us for the next guess (like enter smaller/greater number).
Sometimes, I get some inconsistency in the outputs. After I enter a wrong number as input, it should direct me with an output.
After I enter 40 as input, it does not show me the output as shown above. But after I enter the next input (42), it fixes the output screen and shows the missing output as below.
What might be the problem? It is happening all the time.
Looks like Jupyter issue https://github.com/jupyter/notebook/issues/3159
My recommendation is to combine the prompt with the input request, e.g.,
from random import *
number = randint(1,100)
guess = int(input('Enter a guess: '))
while guess != number:
if guess > number:
prompt = 'Enter a smaller value\n'
else:
prompt = 'Enter a larger value\n'
guess = int(input(prompt + 'Enter a guess: '))
print ('You guessed the number')
Here's a full example:
https://colab.research.google.com/drive/1pCEn11NOCSbCGn91LIxY-Z5nCdVtc_sf

add keys together in a dictionary

Hei guys! I need help in a python program. I wanna make a method which returns the sum of the keys as a dictionary. But I get a error "object is not iterable".
def totaltAntallSalg (dic) :
s = sum (dic.keys)
return s
call_function = totaltAntallSalg({"Ahmed":2,"Nada":1, "hala":3 })
How can I solve this problem?
thanks in advance
How can you add strings ? It might be values that you want to add.
To add values you may use following code:-
def totaltAntallSalg(dic):
D={}
D['sum']=sum(dic.values())
return D

Format zero currency value with {0:C} in VB.Net

I am trying to format a zero currency value as an empty string, so that when the currency value is 0.00 then an empty string gets displayed rather than $0.00.
This code is part of an ASP.Net app that will display currency value to end user.
I have used following code to achieve this goal.
Question : Is it possible to achieve this by just using {0:C} format string or another version of this format string instead of using if then else coding for this? If I use ###,###,###.## as the data format string then an empty string shows for zero currency value and also I get rid of the if then else coding but for non-zero values no currency symbol shows.
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
charValue = Nothing
Else
charValue = String.Format("{0:C}", CDec(currencyValue))
End If
UPDATE
I ended up using the following code, which is working fine. If is better than IIf because it does short-circuiting, which means that IIf will evaluate all expressions whether the condition is true or false but If will evaluate the first expression only if condition is true and evaluate the second expression only if condition is false.
Dim d As Decimal
Decimal.TryParse(currencyValue, d)
charValue = If(d = 0D, Nothing, String.Format("{0:C}", d))
I don't think there is a way using formatting to display an empty string.
But you can write it like:
charValue = If( currencyValue = 0D, "", currencyValue.ToString("C") )
using the If Operator (Visual Basic).
Also this is something I would not do:
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
If currencyValue is Decimal:
If (currencyValue = 0D) Then
If currencyValue is Double:
If (currencyValue = 0R) Then
Also, if you are using a database and this is a Sql Server mind SQL Server Data Type Mappings
I don't think you can when using C or the other similar standard formats, since they are already defining a culture-specific format that will include a format for zero.
But if you specify your own custom format, you can specify three different formats separated by ;s, one each for positive numbers, negative numbers, and zero, respectively.
For example (giving an empty string for the zero format, resulting in blank zeroes):
charValue = String.Format("{0:#,##0.00;-#,##0.00;""""}", CDec(currencyValue))
And from what I can see, omitting the format for negative gives a default that matches the positive, whereas omitting the format for zero gives blank, which is what you're looking for, so this should be sufficient as well:
charValue = String.Format("{0:#,##0.00;;}", CDec(currencyValue))
(Using whichever custom format you wish.)
UPDATE: You can get the current currency symbol and manually put it into your custom format. IE:
Dim symbol = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol
charValue = String.Format("{0}{1:#,##0.00;;}", symbol, CDec(currencyValue))
From the sound of it, though, I think I would actually recommend doing basically what you started with, maybe with an extension method.
<Extension>
Public Function ToCurrencyString(pValue As Decimal) As String
Return IIf(pValue = 0, "", pValue.ToString("C"))
End Function
Dim someValue As Decimal = 1.23
Console.WriteLine(someValue.ToCurrencyString())
This gives you exactly what you're looking for. The exact same format as C gives, but with blank zeroes.

how to increase the limit for max.print in R

I am using the Graph package in R for maxclique analysis of 5461 items.
The final output item which I get is very long, so I am getting the following warning:
reached getOption("max.print") -- omitted 475569 rows
Can somebody please provide me the pointers with how to increase the limit
for max.print.
Use the options command, e.g. options(max.print=1000000).
See ?options:
‘max.print’: integer, defaulting to ‘99999’. ‘print’ or ‘show’
methods can make use of this option, to limit the amount of
information that is printed, to something in the order of
(and typically slightly less than) ‘max.print’ _entries_.
See ?options:
options(max.print=999999)
You can use the options command to change the max.print value for the value limit you want to reach. For example:
options(max.print = 1000000)
There you can change the value of the max.print in R.
set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.
I fixed it just now. But it looks busty. Anyone make it simple please?
def list_by_tag_post(request):
# get POST
all_tag = request.POST.getlist('tag_list')
arr_query = list(all_tag)
for index in range(len(all_tag)):
tag_result = Tag.objects.get(id=all_tag[index])
all_english_text = tag_result.notes.all().values('english_text', 'id')
arr_query[index] = all_english_text
for index in range(len(arr_query)):
all_english_text = all_english_text | arr_query[index]
# Remove replicated items
all_english_text = all_english_text.order_by('id').distinct()
# render
context = {'all_english_text': all_english_text, 'all_tag': all_tag}
return render(request, 'list_by_tag.html', context)

Resources