Error after using input() to get user age - python

I for the life of me cannot figure out what I'm doing wrong. Here's what I have so far. It's my first time trying to use PyCharm. Please help.
PyCharm. Write a program that prompts the user for their name and
age. Your program should then tell the user the year they were born
user_name = input()
user_age = input()
birth_year = (2020 - user_age)
print('Hello',user_name,'!','You were born in', birth_year)
PyCharm just keeps giving me this:
C:\Users\HELLO\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/HELLO/PycharmProjects/pythonProject/main.py

the input() function function returns string by default modify it by passing it to int() funtion as follows:
user_name = input()
user_age = int(input())
birth_year = (2020 - user_age)
print('Hello',user_name,'!','You were born in', birth_year)

Yes, you need to make the users age input as an integer. That way the program knows that you are trying to subtract a number, not a string, which would result in an error.

Related

How to link input from user to a variable with assigned value?

I am very new to Python (literally just started learning last week). My group got an assignment to code a program to compute system that calculate total price with several conditions. But we are stuck because the user input returns as string but we need it to link with the variable. And also we aren't allowed to use IF, ELSE method and everyone is new to this so we are at dead end. Please help :')
This is what we have coded in the last hour.
min_price=30
oak_type=15
pine_type=0
black=0
white=0
gold_leaf=15
print("Welcome to Mark Daniels Carpenting Service!")
import random
order_num=random.randint(1000,1999)
print("\nYour order number is", (order_num))
cust_name=input("Enter name:")
print("Type of wood available:")
print("1 oak_type \n2 pine_type")
wood_type=input("Enter choice of wood:")
And when we tried to total up the price it comes up as error because the wood_type returns as string while the other data returns as integer.
How to make input from wood_type link to oak_type or pine_type value?
wood_type=input("Enter choice of wood:")
You can use wood_type=int(input("Enter choice of wood:"))
Use integer_x = int(input("Enter... ")) for integer and float_x = float(input("Enter... ")) for float.
You can add the type of your input at the beginning of your input syntax.
So for your case, it will be :
wood_type = int(input("Enter choice of wood:"))

I dont know how to do error handling with incorrect inputs

im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)

How do i create a simple subroutine to find and print a user's inputed age?

def findAge(userAge):
userAge = int(input("Enter your age please: "))
return userAge
age = findAge()
print(age)
what am i doing wrong, I literally have no clue! Can somebody please also explain to me which variable names i can change and keep the same!
First of all you defined your function with a parameter, which you don't need. Your function is working without it. If you are coming from a C background and think of your parameter as some kind of pointer, please forget about it. You define a local variable inside of the function and initialise it with the user input.
Now you only need to take care of your indentation, see the code snippet below. The following should work on your machine as it works on my, too:
def findAge():
userAge = int(input("Enter your age please: "))
return userAge
age = findAge()
print(age)
Here are some further readings suggestions:
Python3 functions
Code Indentation (PEP 8)
Hope I could help you. Have a nice day.
Update
If you do need a parameter and you want to modify it, do something like this:
def get_older(age):
age += 1
return age
my_age = 5
my_age = get_older(my_age)
print(my_age) # 6
Another example using parameter, but slightly different:
def print_name_age(name):
age = int(input("How old are you {name}?"))
print(f"Ah, so you are {age} years old, {name}?")
print_name_age("Michael")
Note
f-Strings are only available for Python 3.6 or higher. If you are using another Python 3 version, replace the print-statement with the following:
print("Ah, so you are {} years old, {}?".format(age, name))

Displaying time in Python using "Strptime()"

I'm trying to make a basic program that shows how many days are left until your next birthday, however when I run it in terminal, it says that the input value should be returning a string not an integer? when using the input function in python, doesnt it automatically return as a string value?
import datetime
currentDate = datetime.date.today()
userinput = input("Please enter your birthday(MM.DD.YY)")
birthday = datetime.datetime.strptime(userinput, "%m/%d/%Y")
print(birthday)
Use %y (small letter) to catch two digit years
You should advice the user about the expected format - you expect "MM/DD/YY", but you tell the user to type "MM.DD.YY"
To calculate the difference use something like this (for python3, for python2 use raw_input as Jahangir mentioned):
import datetime
today = datetime.date.today()
userinput = input("Please enter your birthday(MM/DD):")
birthday = datetime.datetime.strptime(userinput, "%m/%d")
birthday = datetime.date(year=today.year, month=birthday.month, day=birthday.day)
if (birthday-today).days<0:
birthday = datetime.date(year=today.year+1, month=birthday.month, day=birthday.day)
print("%d days to your next birthday!"%(birthday-today).days)
In Python 2 use raw_input() instead.

How do I provide error checking to ensure user input only allows letters and provides a looping error message if numbers are typed?

I am trying to provide a looping error message to the user for the customerName input so that the user receives an error message if they type anything other than letters aA - zZ,(I don't want to allow the user to input numbers specifically). I would like it to operate similar to the one I used for the customerAge input( which i provided as an example). but I cant seem to figure out the correct code to accomplish this. can anyone provide some insight?
customerName = input('Enter your name: ')
customerAge = int(input('Enter your age: '))
while customerAge <= 15 or customerAge >= 106:
print('Invalid entry')
customerAge = int(input('Enter your age: '))
after reviewing all the answers I received (thanks goes out to all of you for the help). I coded it like this and it appears to be operating correctly.
customer_name = input('Please enter your name: ')
while not customer_name.isalpha():
print('invalid Entry')
customer_name = input('Please enter your name: ')
Let's start with what your program needs to do:
Loop until the input is valid
That will be it for all kinds of validation that are in the form of:
1) User inserts something
2) Something is wrong
3) Program informs user and asks for input again
So, in python:
valid = False
while not valid:
valid = True
customer_name = input('Enter your name: ')
customer_age = int(input('Enter your age: '))
if customer_age <= 15 or customer_age >= 106:
print 'Enter a valid age'
valid = False
if not customer_name.isalpha():
print 'Enter a valid name'
valid = False
What we did here:
1) Set valid to True, so the happy case will let us out of the loop
2) Obtain both values
3) If any of them is invalid, set valid to False and inform the situation
You can even use 2 loops to validate separately.
A note on the isalpha() method: You can find the documentation here and some good info about it in this question
Also, as a bottom line advice: never use camel case in python variables.
That notation is reserved for Class names. For variables, use lower case and _
Regex should do what you want
import re
while 1:
name = raw_input("Enter your name: ")
if re.search(r'(?i)[^a-z]', name):
print("Invalid name")
else:
break
Check the type of each character with the type() function.
u_input = raw_input()
valid = ""
for char in u_input:
if str(type(char)) == "<type 'int'>":
valid = "False"
break
else:
pass
if valid == 'False':
print 'This string has a number! Gosh darn it!"
Place this in a function/while loop, and you have your looping error message. You can add other loops to ensure any other parameters.
This is the easiest, and likely the most efficient way.
More information on type() here: https://docs.python.org/2/library/functions.html#type

Categories