UserNumber = 0
UserNumber = int(raw_input("Enter a 3 digit number: "))
if UserNumber >= 100 and UserNumber <= 999:
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was", UserNumber, "."
How can I make the program only run when a 3 digit number is entered (i.e a number > 99 and number < 1000? I know it has to be some sort of while loop but I don't know how to implement it.
You could use regex to check if the number is 3 digits and just ask the user again if it is not matching the regex
import re
UserNumber = int(raw_input("Enter a 3 digit number: "))
while not(re.search("^\d{3}$", str(UserNumber))):
UserNumber = int(raw_input("that was not a 3 digit number, Enter a 3 digit number: "))
if UserNumber >= 100 and UserNumber <= 999:
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was", UserNumber, "."
The input is a string, therefore, you can len(input) before the cast to an integer.
The check that every character is a digit can be done with and input.isdigit.
UserNumber = 0
input = raw_input("Enter a 3 digit number: ")
if len(input) == 3 and input.isdigit():
UserNumber = int(input)
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was", UserNumber, "."
But think, 007 is also a valid 3 digit number. So if you want that it is bigger than 99, you need that check too.
To your "update", that you want a "fail-save" such that somebody is forced to do a 3 digits input:
UserNumber = 0
input = ""
while not (len(input) == 3 and input.isdigit()):
input = raw_input("Enter a 3 digit number: ")
UserNumber = int(input)
print "My name is: xxxxx xxxxx"
print "My UBIT name is: xxxxxxx"
print "The number you entered was %03d." % UserNumber
As long as somebody does not input 3 digits, the question for that input will appear.
Related
So I have an assignment:
Your friend wants to try to make a word ladder! This is a list of words where each word has a one-letter difference from the word before it. Here’s an example:
cat
cot
cog
log
Write a program to help your friend.
It should do the following:
Ask your friend for an initial word
Repeatedly ask them for an index and a letter
You should replace the letter at the index they provided with the letter they enter You should then print the new word
Stop asking for input when the user enters -1 for the index
Here’s what should be happening behind the scenes:
You should have a function, get_index, that repeatedly asks the user for an index until they enter a valid integer that is within the acceptable range of indices for the initial string.
(If they enter a number out of range, you should reply invalid index.)
You should have another function, get_letter, that repeatedly asks the user for a letter until they enter exactly one lowercase letter. (If they enter more than one character, you should reply Must be exactly one character!. If they enter a capital letter, you should reply Character must be a lowercase letter!.)
You should store a list version of the current word in a variable. This is what you should update each time the user swaps out a new letter.
Each time you have to print the current word, print the string version of the list you are keeping in your variable.
I have tried rewriting, researching, and even debug mode.
def get_index():
while True:
index_in = int(input("Enter a number between 0 and " + str(len(string) - 1) + ": "))
if index_in > len(string) or index_in < -1:
print "Invalid Index"
elif index_in == -1:
return False
else:
get_letter(index_in)
def get_letter(index):
global string
char_list = list(string)
while True:
letter = input("Enter a letter: ")
if letter.isupper():
print "Character must be lower case!"
else:
char_list[index] = letter
string = ('').join(char_list)
break
print string
string = input("Enter a word: ")
get_index()
An example of the program should look like this:
Enter a word: cat
Enter an index (-1 to quit): 1
Enter a letter: o
cot
Enter an index (-1 to quit): 2
Enter a letter: g
cog
Enter an index (-1 to quit): 5
Invalid index
Enter an index (-1 to quit): -3
Invalid index
Enter an index (-1 to quit): 0
Enter a letter: L
Character must be a lowercase letter!
Enter a letter: l
log
Enter an index (-1 to quit): -1
Your code looks perfect!
Just need some changes according to (python 3)
def get_index():
while True:
index_in = int(input("Enter a number between 0 and " + str(len(string) - 1) + " (-1 to quit): "))
if index_in > len(string) -1 or index_in < -1:
print("Invalid Index")
elif index_in == -1:
return False
else:
get_letter(index_in)
def get_letter(index):
global string
char_list = list(string)
while True:
letter = input("Enter a letter: ")
if letter.isupper():
print("Character must be lower case!")
else:
char_list[index] = letter
string = ('').join(char_list)
break
print(string)
return
string = input("Enter a word: ")
get_index()
You should use print(msg) instead of print msg in python 3
You missed one condition, consider this scenario,
Run the program
Enter a word: c
Enter a number between 0 and 0 (-1 to quit): 1
Error
there was a wrong in get_index() check on line:
if index_in > len(string) or index_in < -1:
it should be :
if index_in > len(string) -1 or index_in < -1:
============================================================ *
UPDATE
updating the annwer according to discussion in comments:
def get_index(string):
try:
while True:
index_in = int(input("Enter a number between 0 and " + str(len(string) - 1) + " (-1 to quit): "))
if index_in > len(string) -1 or index_in < -1:
print("Invalid Index")
elif index_in == -1:
return False
else:
get_letter(index_in, string)
except ValueError:
print("Please Enter a number!")
get_index(string)
def get_letter(index, string):
char_list = list(string)
while True:
letter = input("Enter a letter: ")
if letter.isupper():
print("Character must be lower case!")
else:
char_list[index] = letter
string = ('').join(char_list)
break
print(string)
return
if __name__ == "__main__":
string = input("Enter a word: ")
get_index(string)
CHANGES are:
You must avoid global variables.
Instead, pass particular variable to functions as argumens.
Notice, how string was used in first answer and how it was used in the updated answer.
Use try-catch blocks to catch unexpected behavior
import random
guesses = 0
ons = 0
ins = 0
while True: **#while loop which I want to restart if any of the user inputs are longer than 1 digit**
number = random.sample(range(0,9),4) #random 4 digit number
Creates random unique number
print(number)
number1 = raw_input("Please enter your first digit or exit")
if len(str(number1)) != 1:
print("number is not 4 digits")
break
True
If the length of the user input is not 1 then it can't be 4 digits so at this point I want it to restart the loop after printing that up.
elif number1 == "exit":
print(number)
False
exit()
number2 = raw_input("Please enter your second digit")
if len(str(number2)) != 1:
print("number is not 4 digits")
break
True
number3 = raw_input("Please enter your third digit")
if len(str(number3)) != 1:
print("number is not 4 digits")
break
True
If the length of the user input is not 1 then it cant be 4 digits so at this point I want it to restart the loop after printing that up.
number4 = raw_input("Please enter your fourth digit")
if len(str(number4)) != 1:
print("number is not 4 digits")
break
True
If I understood correctly, you want to use a continue instead of break.
Break takes you out of the loop.
Continue does not break the loop, it takes the control to next iteration.
A quick search for python shows this: break and continue in loops
I want to make a program where fraction values can be operated mathematically.
I've made a code but it show me an error.
TypeError: both arguments should be Rational instances.
print "We'll ask you for two fraction values."
print "After taking values from you, we'll use python built in operaters to make it happen."
from fractions import *
value_1_one = raw_input("Please enter 1st value : ")
value_1_two = raw_input("Please enter 1st two value : ")
value_2_one = raw_input("Please enter 2nd one value.")
value_2_two = raw_input("Please enter 2nd two value.")
vaule_1 = Fraction(value_1_one, value_1_two)
value_2 = Fraction(value_2_one, value_2_two)
print "We have %i and %i as values." % (value_one, value_two)
print "What kind of operation you would like to make."
print "Like Add, Sub, Multi, Devide"
op_kind = raw_input(">>>")
if "Add" in op_kind:
print (value_1 + value_2)
elif "Sub" in op_kind:
print (value_1 - value_2)
elif "Multi" in op_kind:
print (value_1 * value_2)
elif "Devide" in op_kind:
print (value_1 / value_2)
else:
print "Ask Mr. Ramanuj for further details."
I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")
I have to write a program in python that prompts for a phone number of 10 digits and two dashes,with dashes after the area code and next three numbers.Also to diplay if the phone number is valid format or not
I've got a short program here which does what you need.
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
x = validNumber(phone_number)
print x
def validNumber(phone_number):
for j,k in enumerate(phone_number):
if j in [3,7]:
if k != '-':
phone_number=input('Please enter a valid phone number: ')
return phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number
It will continually ask the user to put in the write one, until he does.