I'm completely new to Python so all of this is a bit new for me.
I'm trying to create a script in which it by itself thinks of a number and after wards wants the user to guess a number and enter it. It seemed to work but there are wo problems here.
It understands everything however it does not understand the == part.
Because even though the both numbers are the same, it still goes on towards the else statement.
import random
while True:
Thethinker = random.randint(1,10)
Guessnumber = (input("Guess a random number "))
if Guessnumber == Thethinker:
print("Correct")
print(Thethinker)
else:
print("Not correct")
print(Thethinker)
Any help?
Assuming Python 3, input returns a string.
In Python, a string and a number can never be "equal"; you have to transform one or the other. E.g, if you use
Thethinker = str(random.randint(1,10))
then the equality-comparison with another string can succeed.
Your input returns a string instead of an integer. To get an integer do:
int(Guessnumber)
This is better than using str() because then if you ever want to change the numbers, you wouldn't be able to do that without doing the method I suggested
As far as I know, I don't do much Python
Related
can anyone help me? im pretty new to python and im trying to generate 10 files, each with increasingly harder questions. this code is for difficult 2. I dont want the answers in dif. 2 to be negative so whenever i get a second number bigger than the first i swap the two. for some reason some of them still come out with the first number bigger than the second. i added the "its less than" print statments for testing and it will detect the fact that its less than but wont do something about it.
Your issue is that you're casting your random numbers to a string before comparing their mathematical values. You need to compare them as integers then cast them to strings.
I believe this is because you are checking for comparison between 2 strings not 2 integers. This will give bad results for this type of program
num1 = str(r.choice(numbers))
num2 = str(r.choice(numbers))
Here you are storing strings and not integers.
and then below this you are checking if num1 <= num2.
Convert them to integers before comparing them and your code should work.
I'm having some issues that I really would like some help on. Right now I'm trying to get the user to input a phone that only accepts the first three things typed in as numbers. The rest can be letters that will get converted into numbers, but even if the first three things are numbers or letters it will keep repeating. The input has to be in this format (XXX-XXX-XXXX).
examples: (234-SDF-SDFL) this would pass, if (SDF-FSD-UEIE) then the program would ask again until the first three are number. Please and thank you.
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
while area.isdigit() == False :
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
Why dont you use regular expressions? (BTW: Do not use this odd naming, use pythons naming convention: snake case)
import re
phone_number=input("Number: ")
while not re.match(r'^\d{3}-[A-Z]{3}-[A-Z]{4}$', phone_number):
phone_number=input("Number: ")
I was using the if not equal to code but I needed the equal to code specifically for lengths from some previous posts I have tried this code of len(pin(4)) however this somehow still doesn't work
thank you in advance
pay =input("card or cash")
if pay ==("card"):
pin = str(input("enter your pin number"))
while True:
if len(pin)!=4:
str(input("not four digit try again"))
if len(pin(4)):
print("payment cleared")
else:
print("payment cleared")
break
There are several problems with your code, starting with the formatting. You may use essentially any form of tabbing or spacing in python, but the convention and general best practice is to use 4 spaces.
Next, the line. if pay ==("card"): is unnecessarily confusing.
if pay == "card": is much clearer and functions identically.
The first big error you make is to ask for the pin outside of the loop. Since your pin = str(input("enter your pin number")) occurs outside of your while True: loop, your program will only accept input once, then will enter an infinite loop unless the else clause of len(pin)!=4 occurs.
The line str(input("not four digit try again")) makes absolutely no sense. Here, you are accepting input in a line which you surely instead meant to use the print statement instead, and on top of that you are unneccessarily converting the value entered via input into a string. A simple print("not four digits! try again.") will suffice here.
The line if len(pin(4)): should throw an error if run, as there is no builtin called pin which you should be able to call with pin(4). The correct syntax would be if len(pin) == 4:.
I made a couple changes in the code below besides those described above to help with usability. I first convert the value of pin to integer to check if the value is a number. I assume that it is not inappropriate to represent a value which must clearly be a number as an integer in your example, but if you really want it to be a string you could use regex to check if it is a number or not with the re module. Something like if re.match('[0-9]{4}', pin): would work in this case.
pay = input("card or cash")
if pay == "card":
while True:
try:
pin = int(input("enter your pin number: "))
if len(str(pin))!=4:
print("not four digits! try again.")
else:
print("payment cleared")
break
except ValueError:
print('not a valid number! try again.')
In my code for guessing game, even when the guess is 1, it returns that the guess is too high. Cant figure it out. Thanks!
Essentially you should not be using raw_input as this will get you a string and not an integer. Try using input
Please see this question for more details: Python read input as integers
Your guessNum is string. Need to make it to int when ever you expect a user to input an integer. For example:
guessNum = int(raw_input('Enter a number between 1 and 100: '))
I am currently trying to learn Python 2.7 via Learn Python The Hard Way, but have a question about Study Drill 5 of Exercise 35.
The code I'm looking at is:
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
The study drill asks if there is a better way than checking if the number contains zero or one, and to look at how int() works for clues.
I obviously want to be able to accept any number given by the user while dismissing strings, and I understand that int() converts what was given in raw_input() into a number.
So, I tried a couple of ways of amending the if statement which threw up fatal errors when typing a string, but struggled to find anything suitable. I tried variations of the following code, and now understand why they don't work:
choice = int(raw_input("> "))
if choice > 0:
After searching SO I discovered this answer which gives two ways to solve the problem, however try...except and .isdigit() aren't something mentioned in the book at this point.
Is there any other ways to achieve taking user input, converting it to an integer if necessary, and returning an error if not that is appropriate for this stage of the book?
You can write your own is_digit function
def my_digit(input):
digits = ['0','1','2','3','4','5','6','7','8','9']
for i in list(input):
if not i in digits:
return False
return True
So, firstly read what jonrsharpe linked to in the comments and accept that try-except is the best way of doing this.
Then consider what it means to be an integer:
Everything must be a digit (no decimal point, too)
So that's what you check for. You want everything to be a digit.
Thus, for a represents_integer(string) function:
for every letter in the string:
check that it is one of "0", "1", "2", ..., "9"
if it is not, this is not a number, so return false
if we are here, everything was satisfied, so return true
Note that the check that is is one of might require another loop, although there are faster ways.
Finally, consider "", which won't work in this method (or GregS').
Since you already learned sets, you can test that every character is a digit by something like
choice = choice.strip()
for d in choice:
if d not in "0123456789":
# harass user for their idiocy
how_much = int (choice)