mySpeed = input("What is your speed? ")
if mySpeed < ("50"):
print ("safe")
Why does this print if the value is above 99?
Try this:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
# same as before
Explanation: you should read a number and compare it against a number. Your code currently is reading a string and comparing it against another string, that's not going to give the results you expect.
Because you are comparing two strings, not two integers. A string is a sequence and for a sequence comparison works as follows:
The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
So if you take a number large than '99', e.g. '100' it will take the first character '1' and compare it to '5' (first character of '50'). '1' is smaller than '5' in ascii ('1'==49 and '5'==53). So this comparison will already terminate and the result will be that indeed '100' is smaller than '50'.
For the same reason '9' is not smaller than '50':
In [1]: b'9'<b'50'
Out[1]: False
You should compare integers, as follows:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
print ("safe")
"50" is a string, not a number ... try eliminating the " " ...
If mystring is a string, try a cast with the int-function - e.g. int(mystring)
mySpeed < ("50") is checking a string. You need to be working with integers:
mySpeed = input("What is your speed? ")
if mySpeed < (50):
print ("safe")
You can't evaluate a string as if it were an integer. Think of a string as the word "ten", whereas the integer is "10". You can't add the three letters t-e-n to an integer and result in a number. However, you can add "10+10", for example to result in "20". Your code should look like this:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
print ("safe")
NOTE: by using the int() function to turn users' input into an integer, you are not in fact verifying what they input. If the user inputs a string, such as "ten", your code will return an error because "ten" cannot be converted into an integer.
My answer isn't best practice, but it will "work".
Related
i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:
f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.
Using variable names that indicate their meaning might make it easier to keep it all straight:
num_count = int(input("Length of string of numbers: "))
num_list = input('Enter numbers in the string, separated by spaces: ').split()
if len(num_list) == num_count:
print(f"there are {len(set(num_list))} different numbers")
else:
print("incorrect string length")
In the above code, num_count is the count of how many (non-unique) numbers you expect them to input, and num_list is the actual list. To figure out if the list is the expected length, compare num_count to len(num_list).
Note that since all you're doing is looking for unique values, converting the strings in num_list to int is not necessary (whether or not you use a set as I've done here).
You will most likely be better off using another function that ultimately has a while loop. This will make sure that when the user is giving the input that if anything is malformed you can then parse it checking and finally making sure to prompt the user again.
For example:
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
# XXX Here call your "input-function"
get_user_input(i, l)
def get_user_input(user_len, len):
while True user_len != len:
print('Incorrect Input')
user_len = int(input("String of numbers: "))
return
This is not exactly a working example but with what you have you get the idea that you want to do a while loop until your inputs match.
d_num = []
d_num.append(input("Enter a figure to verify if is a Disarium number: "))
With the above code, an input of 135 and print(d_num), would return '135' opposed to '1, 3, 5'.
A quick-fix would be, prompt the user to include whitespace or other characters between digits and use the split command. However, that poses a problem because the output calculation is based upon the index of the digit.
For example:
input: 135
output: true, 135 == Disarium number as 1^1 + 3^2 + 5^3 = 135
Is there an easier way to convert user input, despite type, into a list?
You wanted to know a way to automatically store each digit of the user input as a list item right? Below is the easiest way I can think of:
user_input = input("Enter a figure to verify if is a Disarium number: ")
d_num = [digit for digit in user_input]
The d_num list will have each digit stored separately and then you can convert it into an integer/float and perform the calculation to identify if its a Disarium number or not.
As #Jérôme suggested in the comment, a much simpler solution would be to simply convert the user input to a list and python handles the work of adding individual characters as a list item.
d_num = [digit for digit in user_input] can be written as d_num = list(user_input)
Hope that helps
Calling list(d_num) will give you a list of the individual characters that make up the number. From there, you can just go over them, convert them to integers and raise them to the appropriate power:
if int(d_num) == sum((int(d[1])**(d[0] + 1) for d in enumerate(list(d_num)))):
print("%s is a Disarium number" % d_num)
EDIT:
As Jean-François Fabre commented, you don't actually need the list call - you could enumerate the string's characters directly:
if int(d_num) == sum((int(d[1])**(d[0] + 1) for d in enumerate(d_num))):
print("%s is a Disarium number" % d_num)
Instructions:
"Create a python program to detect if a number of 10 digits is valid. The number should have 10 digits, it can't contain the number "0" and can't contain duplicate consecutive numbers."
...I am using the append to request the 10 numbers and validating that they are different of 0, but I still dont know how to see if the numbers are consecutive.
This is what I have so far:
list=[]
for num in range (1,10): #Request 10 numbers (it can't be zero)
num=int (input("Add 10 digits:"))
list.append (num)
while num != 0:
print ("The number is valid.")
Hints:
Convert the number to a string using the str() function
Use the len() function to validate the length
Use the in-operator to see validate whether the number contains zero
Use zip(s, s[1:]) as a simple way to bring consecutive characters together
use while because for will end you loop before finished if there duplicate digit
mylist=[]
while len(mylist) < 10: #Request 10 numbers (it can't be zero)
mylistLength = str(len(mylist))
num=int(input("Add 10 digits [" + mylistLength +"]: "))
if num not in mylist:
mylist.append(num)
else:
num=int(input("Digit exist, try other: "))
if len(mylist) == 10:
print("The number is valid.")
print(mylist)
This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 8 years ago.
How would I have the user input a number and then have the computer spit their number out in reverse?
num = int(input("insert a number of your choice "))
for i in
That is all I have so far...
I am using 3.3.4
Here's an answer that spits out a number in reverse, instead of reversing a string, by repeatedly dividing it by 10 and getting the remainder each time:
num = int(input("Enter a number: "))
while num > 0:
num, remainder = divmod(num, 10)
print remainder,
Oh and I didn't read the requirements carefully either! It has to be a for loop. Tsk.
from math import ceil, log10
num = int(input("Enter a number: "))
for i in range(int(ceil(math.log10(num)))): # => how many digits in the number
num, remainder = divmod(num, 10)
print remainder,
You don't need to make it int and again make it str! Make it straight like this:
num = input("insert a number of your choice ")
print (num[::-1])
Or, try this using for loop:
>>> rev = ''
>>> for i in range(len(num), 0, -1):
... rev += num[i-1]
>>> print(int(rev))
Best way to loop over a python string backwards says the most efficient/recommended way would be:
>>> for c in reversed(num):
... print(c, end='')
Why make it a number? 'In reverse' implies a string. So don't cast it to int but use it as string instead and just loop over it backwards.
You've got here a variety of different answers, many of which look similar.
for i in str(num)[::-1]:
print i
This concise variation does a few things worth saying in english, namely:
Cast num to a string
reverse it (with [::-1], an example of slicing, a pythonic idiom that I recommend you befriend)
finally, loop over the resultant string (since strings are iterable, you can loop over them)
and print each character.
Almost all the answers use [::-1] to reverse the list -- as you read more code, you will see it more places. I recommend reading more about it on S.O. here.
I hate to do your problem for you since you didn't really try to actually solve it or say what you're specifically having a problem with, but:
num = str(input("..."))
output = [num[-i] for i in range(len(num))]
print(output)
output = input("Insert number of your choice: ")[::-1]
print("Your output!: %s" % output)
In python 3.x+ input is automatically a string, doing [::-1] reverses the order of the string
I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]