change (lack of) user input to default string value - python

This is probably a straight forward question but I don't have the Python fundamentals down yet (running before walking)
I want user inputs for the following (coordinate) variables:
source_x = input('enter blast x: ')
source_y = input('enter blast y: ')
source_z = input('enter blast z: ')
receiver_x = input('enter receiver x: ')
receiver_y = input('enter receiver y: ')
receiver_z = input('enter receiver z: ')
When the user input is Enter for the z coordinate (or any other), the following error arises:
source_z = float(source_z)
ValueError: could not convert string to float: ''
I understand the error, the Enter input was seen as a string, but is there a quick way to identify and convert the Enter input to (e.g.) a 0?
Just in case I want to undertake bulk imports and not stop my calculations further down the code.
kind regards

The solution is to check the input value to see if it is composed of digits and then cast it to the desired type or assign a default value else:
import re
is_number = re.compile(r'^[-+]?[0-9]*\.?[0-9]+$')
src_x = input('enter blast x: ')
src_y = input('enter blast y: ')
src_z = input('enter blast z: ')
rcv_x = input('enter receiver x: ')
rcv_y = input('enter receiver y: ')
rcv_z = input('enter receiver z: ')
src_x = float(src_x) if is_number.match(src_x) else 0
src_y = float(src_y) if is_number.match(src_y) else 0
src_z = float(src_z) if is_number.match(src_z) else 0
rcv_x = float(rcv_x) if is_number.match(rcv_x) else 0
rcv_y = float(rcv_y) if is_number.match(rcv_y) else 0
rcv_z = float(rcv_z) if is_number.match(rcv_z) else 0

Input always returns a string. You could do variable = int(number inputted).
Also, just use a try/except statement and assign a default value in the except clause
>
Try:
Num1 = int(input("Enter a number"))
#mathematical function or whatever
Except Exception as e:
Num1=int(10) #or whatever default number
print(e) #for troubleshooting

Related

how to print getValidInteger? python

I'm a beginner in the Python language. I have my getValidInteger function which is:
def getValidInteger():
isValid = False
#initialize strInput
strInput = ""
while (not isValid):
#get string input from the user
strInput = input('Enter an integer: ')
isValid = IsValidInteger(strInput)
if (not isValid):
print('Invalid integer was entered: try again')
#after exiting the loop return strInput cast to an int
return int(strInput)
However, I cannot call that function in the line code below. It shows Typererror: TypeError: getValidInteger() takes 0 positional arguments but 1 was given
setSizeSmall = um.getValidInteger('Enter a small size of each subset:')
I want the output to look like :
Enter a small size of each subset:
I dont know what is your IsValidInteger() function but it doesn't seem to take arguments.
Instead, you can use the isdigit() method like this
def getValidInteger():
isValid = False
#initialize strInput
strInput = ""
while (not isValid):
#get string input from the user
strInput = input('Enter an integer: ')
isValid = strInput.isdigit()
if (not isValid):
print('Invalid integer was entered: try again')
#after exiting the loop return strInput cast to an int
return int(strInput)

Python3 mask-string

I am trying to solve an exercise in python3 and I can't get it to work.
I have this code:
def mask_string(string3):
"""Mask string"""
s = string3[-4:].rjust(len(string3), "#")
masking_string = ""
string3_length = len(s)
result = multiply_str(masking_string, string3_length) + s
return result
def multiply_str(string3, masking_string):
"""Mulitply string"""
new_multiply_str = string3 * int(masking_string)
return new_multiply_str
And I am running it like this:
elif choice == "10":
string3 = input("Enter a string that will replace all of the caracters with # exept the 4 last ones: ")
print(marvin.mask_string(string3))
masking_string = input("Enter number: ")
print(marvin.multiply_str(string3, masking_string))
And I get this error when I run it:
line 131, in multiply_str new_multiply_str = string3 * int(masking_string)
ValueError: invalid literal for int() with base 10: ''
Would really appreciate some help, and please dumb it down a lot when explaining because I am new to python and still do not understand a lot of how to do things.
line 131, in multiply_str new_multiply_str = string3 * int(masking_string)
ValueError: invalid literal for int() with base 10: ''
Therefore your masking_string was "" which is not a valid number (integer or not). You must have pressed enter without entering a number.
If you want to prevent this, wrap your input routine in a loop and only return when you have a number:
def get_int():
while True:
x = input("Number: ")
try:
return int(x)
except ValueError:
print(f"Invalid input {x}, try again...")

Caesar Cipher Code Python printing on separate lines

The code below works fine, however the message prints onto separate lines once it has been encrypted. For example if I type: abc with the shift of 1 it encrypts it but prints it back as:
b
c
d
And I don't understand why. I want it to print as:
bcd
Here is the code:
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage = chr(ShiftedMessage)
NewMessageList = list(NewMessage)
print("".join(NewMessageList))
Indentation matters and you shouldn't create new list of NewMessage everytime
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
NewMessageList = []
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage = chr(ShiftedMessage)
NewMessageList.append(NewMessage)
print("".join(NewMessageList))
you should change the following part;
print("".join(NewMessageList), end="")
What happening was is that for each charachter it was running the loop and printing the answer, now I have collected all the encrypted letter and clubbed them as one in the end and printed it.
it at first initialize an empty list with NewMessage = [] and then for every letter that we get encrypted it adds to that empty list using .append() and at end print all by ''.join(NewMessage)
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
NewMessage = []
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage.append(chr(ShiftedMessage))
print(''.join(NewMessage))

CSV error when trying to write

import csv
name = input(': ')
password = input(': ')
age = input(': ')
hello = [name, password, age]
length = len(hello[0])
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
When I run the code above on a separate python file alone it works but whenever I try to put it in my full code it doesn't work.
What I am trying to do is basically make a register that when I put input it writes to the csv file. I also added a captcha thing for verification because why not.
csv_writer.writerow([x[y] for x in hello]):
Line 33 ^
The full code v
import random
import csv
def reg2():
print('wip')
def reg1():
ok = False
while not ok:
try:
name = input('Enter your name: ')
age = int(input('Enter your age:'))
password = input('Enter your password: ')
confirm = input('Confirm Password: ')
if confirm == password:
alphabet =''.join(random.choice('0PQRSTUVefghij56789WXYZabcdABCDEFCDrstuvwEFGJ234NOKLMkHImnopqxyz') for i in range(7))
print(alphabet)
captcha = input('Enter the words shown above (Not Case Sensitive): ')
if captcha.capitalize() == alphabet.capitalize() or 'admin'.capitalize():
print('Name: ' + name)
print('Age: {}'.format(age))
print('Password: ' + password)
option = input('Enter No to register again. Enter Yes to login.')
if option.startswith('N') or option.startswith('n'):
reg1()
elif option.startswith('Y') or option.startswith('y'):
hello = [name, password, age]
length = len(hello[0])
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
else:
captcha = input('Try again: ')
if captcha == alphabet:
print('Confirmed. ')
else:
print('You have tried too many times. Please register again.')
reg1()
else:
print('Your password is incorrect. Please register again.')
except ValueError:
print('Error 666: Please register again.')
reg1()
How do I fix this?
The full traceback error is http://pastebin.com/zshHji8i
[...]
length = len(hello[0])
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
So here, "length" is the number of characters in the name variable, a few lines later, for y in range(length) you're "enumerating" the letters, say you have 6 letters you're getting 0, 1, 2, 3, 4, 5 in y. A line later [x[y] for x in hello] you're asking for the letter y for the name, password, age, that has no sense for me.
What about a simple:
name = input(': ')
password = input(': ')
age = input(': ')
hello = [name, password, age]
with open('db.csv', 'a') as testfile:
csv.writer(testfile).writerow(hello)
Oh, and "hello" is a badly chosen name (we can't deduce what it contains). Oh and "x", "y", and "length" are badly chosen too, (length of what ?). Just choose a nice name for your variables and your bug will become obvious.
Why don't you just write:
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
csv_writer.writerow(hello)
hello is already a list, there is no need for the construction you used.

Restarting my program based on user input on Python?

I'm new to programming, fyi. I want my program to restart back to the top based on what the user inputs. It will proceed if the user inputs 2 names. If they input 1 name or more than 2 names, it should restart the program but I'm not sure of how to do this.
def main():
print("Hello, please type a name.")
first_name, last_name = str(input("")).split()
while input != first_name + last_name:
print("Please enter your first name and last name.")
main()
You should use a while loop and check the length of the split before assigning:
def main():
while True:
inp = input("Please enter your first name and last name.")
spl = inp.split()
if len(spl) == 2: # if len is 2, we have two names
first_name, last_name = spl
return first_name, last_name # return or break and then do whatever with the first and last name
Use try/except
Well, your program didn't work for me to begin with, so to parse the first and last names simply, I suggest:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
Also your while loop will just, like, break your life if you run it without good 'ol ctrl+c on hand. So, I suggest:
def main():
print “type your first & last name”
try:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
if f and l:
return f + ‘ ‘+ l
except:
main()
The except: main() will re-run the program for you on error.

Categories